Python mistune.escape() Examples

The following are 21 code examples of mistune.escape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mistune , or try the search function .
Example #1
Source File: mistune_markdown.py    From Django-blog with MIT License 6 votes vote down vote up
def block_code(self, code, lang=None):
        """Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.
        """
        code = code.rstrip('\n')  # 去掉尾部的换行符
        # 如果没有lang, 就返回代码块
        if not lang:
            code = mistune.escape(code)
            return '<pre><code>%s\n</code></pre>\n' % code

        # 给代码加上高亮  例如: lang='python'的话
        # ```python
        #   print('666')
        # ```
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ClassNotFound:
            # 如果lang是不合法, 没有匹配到, 就设置为python
            lexer = get_lexer_by_name('python', stripall=True)
        formatter = html.HtmlFormatter()  # linenos=True
        return highlight(code, lexer, formatter) 
Example #2
Source File: highlight.py    From mistune-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def block_code(text, lang, inlinestyles=False, linenos=False):
    if not lang:
        text = text.strip()
        return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

    try:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter(
            noclasses=inlinestyles, linenos=linenos
        )
        code = highlight(text, lexer, formatter)
        if linenos:
            return '<div class="highlight-wrapper">%s</div>\n' % code
        return code
    except:
        return '<pre class="%s"><code>%s</code></pre>\n' % (
            lang, mistune.escape(text)
        ) 
Example #3
Source File: md.py    From codimension with GNU General Public License v3.0 6 votes vote down vote up
def block_code(uuid, text, lang, inlinestyles=False, linenos=False):
    """Renders a code block"""
    if is_plant_uml(text, lang):
        fName = Settings().plantUMLCache.getResource(text, uuid)
        if fName is None:
            return '<br/><img src="cdm-image:na50.png"><br/>\n'
        return '<br/><img src="plantuml:' + fName + '"><br/>\n'

    lexer = get_lexer(text, lang)
    if lexer:
        try:
            formatter = HtmlFormatter(noclasses=inlinestyles, linenos=linenos)
            code = highlight(text, lexer, formatter)
            return ''.join([PRE_WRAP_START, '<pre>',
                            code.replace('125%', '100%'), '</pre>',
                            PRE_WRAP_END, '\n'])
        except:
            pass

    return ''.join([PRE_WRAP_START, '<pre>', mistune.escape(text),
                    '</pre>', PRE_WRAP_END, '\n']) 
Example #4
Source File: html.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
def from_text(txt):
    def replace(match):
        txt = match.group()
        if '\n' in txt:
            return '<br>' * txt.count('\n')
        else:
            return '&nbsp;' * txt.count(' ')

    tpl = '<p>%s</p>'
    htm = escape(txt)
    htm = fromstring(tpl % htm)
    fix_links(htm)
    htm = tostring(htm, encoding='unicode')
    htm = htm[3:-4]
    htm = re.sub('(?m)((\r?\n)+| [ ]+|^ )', replace, htm)
    htm = tpl % htm
    return htm 
Example #5
Source File: markdown_mistune.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def markdown2html_mistune(source):
    """Convert a markdown string to HTML using mistune"""
    return MarkdownWithMath(renderer=IPythonRenderer(
        escape=False)).render(source) 
Example #6
Source File: markdown_mistune.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def escape_html(self, text):
        return cgi.escape(text) 
Example #7
Source File: markdown_mistune.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def header(self, text, level, raw=None):
        html = super(IPythonRenderer, self).header(text, level, raw=raw)
        anchor_link_text = self.options.get('anchor_link_text', u'¶')
        return add_anchor(html, anchor_link_text=anchor_link_text)

    # We must be careful here for compatibility
    # html.escape() is not availale on python 2.7
    # For more details, see:
    # https://wiki.python.org/moin/EscapingHtml 
Example #8
Source File: markdown_mistune.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def block_code(self, code, lang):
        if lang:
            try:
                lexer = get_lexer_by_name(lang, stripall=True)
            except ClassNotFound:
                code = lang + '\n' + code
                lang = None

        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                mistune.escape(code)

        formatter = HtmlFormatter()
        return highlight(code, lexer, formatter) 
Example #9
Source File: renderer.py    From maildown with MIT License 5 votes vote down vote up
def block_code(code, lang=None):
        if not lang:
            return "\n<pre><code>%s</code></pre>\n" % mistune.escape(code)
        lexer = lexers.get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter()
        return pygments.highlight(code, lexer, formatter) 
Example #10
Source File: poll.py    From Spirit with MIT License 5 votes vote down vote up
def _clean_choices(self):
        choices_raw = self.data['choices']
        choices = []

        for choice in choices_raw.splitlines()[:self.choices_limit + 1]:
            number, description = choice.split('.', 1)
            description = mistune.escape(description.strip(), quote=True)
            choices.append({
                'number': int(number),
                'description': description[:self._field_description.max_length]
                # 'poll_name': ...  # Added in clean() method
            })

        self.cleaned_data['choices'] = choices 
Example #11
Source File: poll.py    From Spirit with MIT License 5 votes vote down vote up
def _clean_poll(self):
        name_raw = self.data['name']
        title_raw = self.data['title']
        min_raw = self.data['min']
        max_raw = self.data['max']
        close_at_raw = self.data['close']
        mode_raw = self.data['mode']

        poll = {
            'name': name_raw[:self._field_name.max_length]
        }

        if title_raw:
            title = mistune.escape(title_raw.strip(), quote=True)
            poll['title'] = title[:self._field_title.max_length]  # May be empty

        if min_raw:
            poll['choice_min'] = int(min_raw)

        if max_raw:
            poll['choice_max'] = int(max_raw)

        if close_at_raw:
            days = int(close_at_raw[:self.close_max_len])
            poll['close_at'] = timezone.now() + timezone.timedelta(days=days)

        if mode_raw:
            poll['mode'] = PollMode.BY_NAME[mode_raw]

        self.cleaned_data['poll'] = poll 
Example #12
Source File: html.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def to_text(htm):
    htm = fromstring(htm)
    return '\n'.join(escape(i) for i in htm.xpath('//text()') if i) 
Example #13
Source File: html.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def block_code(self, code, lang):
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                mistune.escape(code)
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter(noclasses=True)
        return highlight(code, lexer, formatter) 
Example #14
Source File: mathoid.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def inline_math(self, math):
        math = format_math(math)
        return self.get_result(math) or r'\(%s\)' % escape(math) 
Example #15
Source File: mathoid.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def display_math(self, math):
        math = format_math(math)
        return self.get_result(r'\displaystyle ' + math) or r'\[%s\]' % escape(math) 
Example #16
Source File: math.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def math(self, math):
        if self.mathoid is None or not math:
            return r'\(%s\)' % mistune.escape(str(math))
        return self.mathoid.inline_math(math) 
Example #17
Source File: __init__.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def markdown(value, style, math_engine=None, lazy_load=False):
    styles = settings.MARKDOWN_STYLES.get(style, settings.MARKDOWN_DEFAULT_STYLE)
    escape = styles.get('safe_mode', True)
    nofollow = styles.get('nofollow', True)
    texoid = TEXOID_ENABLED and styles.get('texoid', False)
    math = getattr(settings, 'MATHOID_URL') and styles.get('math', False)
    bleach_params = styles.get('bleach', {})

    post_processors = []
    if styles.get('use_camo', False) and camo_client is not None:
        post_processors.append(camo_client.update_tree)
    if lazy_load:
        post_processors.append(lazy_load_processor)

    renderer = AwesomeRenderer(escape=escape, nofollow=nofollow, texoid=texoid,
                               math=math and math_engine is not None, math_engine=math_engine)
    markdown = mistune.Markdown(renderer=renderer, inline=AwesomeInlineLexer,
                                parse_block_html=1, parse_inline_html=1)
    result = markdown(value)

    if post_processors:
        tree = fragments_to_tree(result)
        for processor in post_processors:
            processor(tree)
        result = fragment_tree_to_str(tree)
    if bleach_params:
        result = get_cleaner(style, bleach_params).clean(result)
    return Markup(result) 
Example #18
Source File: __init__.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def block_html(self, html):
        if self.texoid and html.startswith('<latex'):
            attr = html[6:html.index('>')]
            latex = html[html.index('>') + 1:html.rindex('<')]
            latex = self.parser.unescape(latex)
            result = self.texoid.get_result(latex)
            if not result:
                return '<pre>%s</pre>' % mistune.escape(latex, smart_amp=False)
            elif 'error' not in result:
                img = ('''<img src="%(svg)s" onerror="this.src='%(png)s';this.onerror=null"'''
                       'width="%(width)s" height="%(height)s"%(tail)s>') % {
                    'svg': result['svg'], 'png': result['png'],
                    'width': result['meta']['width'], 'height': result['meta']['height'],
                    'tail': ' /' if self.options.get('use_xhtml') else '',
                }
                style = ['max-width: 100%',
                         'height: %s' % result['meta']['height'],
                         'max-height: %s' % result['meta']['height'],
                         'width: %s' % result['meta']['height']]
                if 'inline' in attr:
                    tag = 'span'
                else:
                    tag = 'div'
                    style += ['text-align: center']
                return '<%s style="%s">%s</%s>' % (tag, ';'.join(style), img, tag)
            else:
                return '<pre>%s</pre>' % mistune.escape(result['error'], smart_amp=False)
        return super(AwesomeRenderer, self).block_html(html) 
Example #19
Source File: __init__.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def block_code(self, code, lang=None):
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code).rstrip()
        return highlight_code(code, lang) 
Example #20
Source File: __init__.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def link(self, link, title, text):
        link = mistune.escape_link(link)
        if not title:
            return '<a href="%s"%s>%s</a>' % (link, self._link_rel(link), text)
        title = mistune.escape(title, quote=True)
        return '<a href="%s" title="%s"%s>%s</a>' % (link, title, self._link_rel(link), text) 
Example #21
Source File: __init__.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def autolink(self, link, is_email=False):
        text = link = mistune.escape(link)
        if is_email:
            link = 'mailto:%s' % link
        return '<a href="%s"%s>%s</a>' % (link, self._link_rel(link), text)