예제 #1
0
    def blockcode(self, text, lang):
        if not lang:
            return '\n<pre><code>{}</code></pre>\n'.format(
                h.escape_html(text.strip()))

        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter()

        return highlight(m.smartypants(text), lexer, formatter)
 def test_apostrophes(self):
     ok(smartypants('\'s')) == '&rsquo;s'
     ok(smartypants('\'t')) == '&rsquo;t'
     ok(smartypants('\'m')) == '&rsquo;m'
     ok(smartypants('\'d')) == '&rsquo;d'
     ok(smartypants('\'re')) == '&rsquo;re'
     ok(smartypants('\'ll')) == '&rsquo;ll'
     ok(smartypants('\'ve')) == '&rsquo;ve'
예제 #3
0
파일: markdown.py 프로젝트: the-cc-dev/Publ
def to_html(text, config, search_path):
    """ Convert Markdown text to HTML """
    processor = misaka.Markdown(HtmlRenderer(config, search_path),
                                extensions=ENABLED_EXTENSIONS)

    text = processor(text)
    if not config.get('no_smartquotes'):
        text = misaka.smartypants(text)

    return flask.Markup(text)
예제 #4
0
def process(text, config, search_path):
    """ Process an HTML entry's HTML """
    processor = HTMLEntry(config, search_path)
    processor.feed(text)
    text = processor.get_data()

    if not config.get('no_smartquotes'):
        text = misaka.smartypants(text)

    return flask.Markup(text)
예제 #5
0
def markdown(text, renderer=None, **options):
    ext, rndr = make_flags(**options)
    if renderer:
        md = misaka.Markdown(renderer, ext)
        result = md(text)
    else:
        result = misaka.html(text, extensions=ext, render_flags=rndr)
    if options.get("smartypants"):
        result = misaka.smartypants(result)
    return Markup(result)
예제 #6
0
 def render(text):
     renderer = MyRenderer(page)
     markdown = misaka.Markdown(renderer,
                                extensions=('fenced-code', 'smartypants',
                                            'strikethrough', 'superscript',
                                            'tables', 'footnotes'))
     content = misaka.smartypants(markdown(text))
     if not content:
         return content
     document = lxml.html.fromstring(content)
     for image in document.xpath("//img"):
         src = image.get('src')
         if src.startswith("+"):
             image_url = (os.path.splitext(src[1:])[0] + "/").lower()
             image_document = app.jinja_env.site.post(image_url)
             if image_document is None:
                 logging.error("Failed to get document for image '%s'" %
                               (image_url, ))
                 continue
             template = app.jinja_env.get_template("image.html")
             title = None
             try:
                 title = image_document['title']
             except KeyError:
                 pass
             html = template.render(site=app.jinja_env.site,
                                    image=image_document)
             replacement_image = lxml.html.fromstring(html)
             parent = image.getparent()
             parent.insert(parent.index(image) + 1, replacement_image)
             parent.remove(image)
         else:
             image.set('src', fixup_relative_image_url(src, page["path"]))
             image.set(
                 'srcset',
                 fixup_relative_image_srcset(image.get('srcset'),
                                             page["path"]))
     for source in document.xpath("//picture/source"):
         srcset = source.get('srcset')
         source.set('srcset',
                    fixup_relative_image_url(srcset, page["path"]))
     for anchor in document.xpath("//a"):
         anchor.set('href',
                    fixup_relative_url(anchor.get('href'), page["path"]))
     results = lxml.html.tostring(document,
                                  method='html',
                                  encoding='unicode')
     return results
예제 #7
0
def to_html(text, args, search_path):
    """ Convert Markdown text to HTML """

    # first process as Markdown
    processor = misaka.Markdown(
        HtmlRenderer(args, search_path),
        args.get('markdown_extensions') or config.markdown_extensions)
    text = processor(text)

    # convert smartquotes, if so configured
    if not args.get('no_smartquotes'):
        text = misaka.smartypants(text)

    # now filter through html_entry to rewrite local src/href links
    text = html_entry.process(text, args, search_path)

    return flask.Markup(text)
예제 #8
0
def markdown(text, renderer=None, **options):
    """
    Parses the provided Markdown-formatted text into valid HTML, and returns
    it as a :class:`flask.Markup` instance.

    :param text: Markdown-formatted text to be rendered into HTML
    :param renderer: A custom misaka renderer to be used instead of the default one
    :param options: Additional options for customizing the default renderer
    :return: A :class:`flask.Markup` instance representing the rendered text
    """
    ext, rndr = make_flags(**options)
    if options.get("smartypants"):
        text = misaka.smartypants(text)
    if renderer:
        md = misaka.Markdown(renderer,ext)
        return Markup(md(text))
    else:
        return Markup(misaka.html(text, extensions=ext, render_flags=rndr))
예제 #9
0
def markdown(text, renderer=None, **options):
    """
    Parses the provided Markdown-formatted text into valid HTML, and returns
    it as a :class:`flask.Markup` instance.

    :param text: Markdown-formatted text to be rendered into HTML
    :param renderer: A custom misaka renderer to be used instead of the default one
    :param options: Additional options for customizing the default renderer
    :return: A :class:`flask.Markup` instance representing the rendered text
    """
    ext, rndr = make_flags(**options)
    if options.get("smartypants"):
        text = misaka.smartypants(text)
    if renderer:
        md = misaka.Markdown(renderer, ext)
        return Markup(md(text))
    else:
        return Markup(misaka.html(text, extensions=ext, render_flags=rndr))
예제 #10
0
파일: markdown.py 프로젝트: the-cc-dev/Publ
def render_title(text, markup=True, no_smartquotes=False):
    """ Convert a Markdown title to HTML """

    # HACK: If the title starts with something that looks like a list, save it
    # for later
    pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
    text = pfx + misaka.Markdown(TitleRenderer(),
                                 extensions=TITLE_EXTENSIONS)(text)

    if not markup:
        strip = HTMLStripper()
        strip.feed(text)
        text = strip.get_data()

    if not no_smartquotes:
        text = misaka.smartypants(text)

    return flask.Markup(text)
예제 #11
0
파일: markdown.py 프로젝트: colinta/plywood
def markdown(states, scope, arguments, block):
    code = block.get_value(scope).python_value(scope)
    markup = misaka.smartypants(compiler(code).strip())
    return [Continue()], markup
def render_markdown(source, relative_url):
    # Rendering the hard way because we need pygments
    renderer = MarkdownRenderer()
    md = misaka.Markdown(renderer,
                         extensions=misaka.EXT_TABLES | misaka.EXT_FENCED_CODE
                         | misaka.EXT_AUTOLINK | misaka.EXT_STRIKETHROUGH)
    pre_rendered = md(source)
    rendered = misaka.smartypants(pre_rendered)

    # Yay slowest markdown renderer ever
    hygiene = BeautifulSoup(rendered, 'html5lib')

    # Styling tables
    for tag in hygiene.find_all('table'):
        tag.attrs[
            'class'] = 'table table-striped table-condensed table-bordered'

    # Fixing local path entries
    def fix_path(path):
        path = path.strip()
        if path.startswith('/') or path.startswith('#') or ':/' in path:
            return path
        return '/'.join([relative_url, path])

    for tag_name in ['a', 'img']:
        for x in hygiene.find_all(tag_name):
            for attr_name in ['src', 'href']:
                if attr_name in x.attrs:
                    x.attrs[attr_name] = fix_path(x.attrs[attr_name])

    # Every image must be wrapped into a link tag
    for img in hygiene.find_all('img'):
        if img.parent.name != 'a':
            a = hygiene.new_tag('a', href=img.attrs['src'])
            img.insert_after(a)
            img.extract()
            a.append(img)

    # Enabling Lightbox on images
    image_id = 0
    for a in hygiene.find_all('a'):
        if a.img:
            a.attrs['data-lightbox'] = 'image-%d' % image_id
            image_id += 1
            if a.img.attrs.get('title') or a.img.attrs.get('alt'):
                a.attrs['data-title'] = a.img.attrs.get(
                    'title') or a.img.attrs.get('alt')

    # Rendering alert boxes
    for alert_name in ['info', 'warning', 'danger']:
        for x in hygiene.find_all(alert_name):
            alert_name = x.name
            x.name = 'div'
            x.attrs['class'] = 'alert alert-' + alert_name

    # Generating table of contents anchors.
    # JS-based solution doesn't quite work because if anchors are not set at page load time the browser won't scroll.
    for header in ['h2', 'h3', 'h4', 'h5']:
        for h in hygiene.find_all(header):
            anchor = ''.join(h.strings).strip()
            anchor = re.sub(r'\s', '_', anchor)
            anchor = re.sub(r'[^A-Za-z0-9\-_:\.]', '', anchor)
            h.attrs['id'] = anchor

    # Oi moroz moroz ne moroz mena
    return Markup(str(hygiene))  # Ne moroz mena moigo kona
예제 #13
0
 def postprocess(self, context):
     context['body'] = misaka.smartypants(context['body'])
 def test_double_quotes(self):
     ok(smartypants('"Quotes"')) == '&ldquo;Quotes&rdquo;'
 def test_dash(self):
     ok(smartypants('--')) == '&ndash;'
     ok(smartypants('---')) == '&mdash;'
 def test_ellipsis(self):
     ok(smartypants('...')) == '&hellip;'
     ok(smartypants('. . .')) == '&hellip;'
예제 #17
0
def render_markdown(source, relative_url):
    # Rendering the hard way because we need pygments
    renderer = MarkdownRenderer()
    md = misaka.Markdown(renderer, extensions=misaka.EXT_TABLES | misaka.EXT_FENCED_CODE | misaka.EXT_AUTOLINK |
                         misaka.EXT_STRIKETHROUGH)
    pre_rendered = md(source)
    rendered = misaka.smartypants(pre_rendered)

    # Yay slowest markdown renderer ever
    hygiene = BeautifulSoup(rendered, 'html5lib')

    # Styling tables
    for tag in hygiene.find_all('table'):
        tag.attrs['class'] = 'table table-striped table-condensed table-bordered'

    # Fixing local path entries
    def fix_path(path):
        path = path.strip()
        if path.startswith('/') or path.startswith('#') or ':/' in path:
            return path
        return '/'.join([relative_url, path])

    for tag_name in ['a', 'img']:
        for x in hygiene.find_all(tag_name):
            for attr_name in ['src', 'href']:
                if attr_name in x.attrs:
                    x.attrs[attr_name] = fix_path(x.attrs[attr_name])

    # Every image must be wrapped into a link tag
    for img in hygiene.find_all('img'):
        if img.parent.name != 'a':
            a = hygiene.new_tag('a', href=img.attrs['src'])
            img.insert_after(a)
            img.extract()
            a.append(img)

    # Enabling Lightbox on images
    image_id = 0
    for a in hygiene.find_all('a'):
        if a.img:
            a.attrs['data-lightbox'] = 'image-%d' % image_id
            image_id += 1
            if a.img.attrs.get('title') or a.img.attrs.get('alt'):
                a.attrs['data-title'] = a.img.attrs.get('title') or a.img.attrs.get('alt')

    # Rendering alert boxes
    for alert_name in ['info', 'warning', 'danger']:
        for x in hygiene.find_all(alert_name):
            alert_name = x.name
            x.name = 'div'
            x.attrs['class'] = 'alert alert-' + alert_name

    # Generating table of contents anchors.
    # JS-based solution doesn't quite work because if anchors are not set at page load time the browser won't scroll.
    for header in ['h2', 'h3', 'h4', 'h5']:
        for h in hygiene.find_all(header):
            anchor = ''.join(h.strings).strip()
            anchor = re.sub(r'\s', '_', anchor)
            anchor = re.sub(r'[^A-Za-z0-9\-_:\.]', '', anchor)
            h.attrs['id'] = anchor

    # Oi moroz moroz ne moroz mena
    return Markup(str(hygiene))  # Ne moroz mena moigo kona
예제 #18
0
def markdown(markdown):
    return misaka.smartypants(markdowner(markdown).strip())
 def test_parens(self):
     ok(smartypants('(c)')) == '&copy;'
     ok(smartypants('(r)')) == '&reg;'
     ok(smartypants('(tm)')) == '&trade;'
 def test_fractions(self):
     ok(smartypants('3/4ths')) == '&frac34;ths'
     ok(smartypants('3/4')) == '&frac34;'
     ok(smartypants('1/2')) == '&frac12;'
     ok(smartypants('1/4')) == '&frac14;'