Python mistune 模块,escape() 实例源码
我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用mistune.escape()。
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 = html.HtmlFormatter(
noclasses=inlinestyles, linenos=linenos
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight-wrapper">%s</div>\n' % code
return code
except BaseException:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
def block_code(self, code, lang):
"Block code Highlighter and formater"
try:
if not lang:
lexer = guess_lexer(code, stripall=True)
else:
lexer = get_lexer_by_name(lang, stripall=True)
detected = True
code = highlight(code, self.code_formatter)
except:
code = escape(code)
lang = None
self.info.code.append(code)
template = self.jinja2.get_template('code')
rv = template.render(code=code, lang=lang, site=self.site, Meta=self.Meta)
rv = rv.encode('utf-8')
return rv
def block_code(self, lang=None):
"""Rendering block level code. ``pre > code``.
"""
lexer = None
if code.endswith('\n\n'):
code = code[:-1]
if HtmlFormatter and lang:
try:
lexer = get_lexer_by_name(lang, stripall=True)
except ClassNotFound:
code = lang + '\n' + code
if not lexer or not HtmlFormatter:
return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)
formatter = HtmlFormatter()
return highlight(code, formatter)
def slide_footer(self):
slide_id = self.get_slide_id()
header = self.cur_header or self.slide_img_tag or self.alt_header or ''
if header and not header.startswith('<img '):
header = mistune.escape(header)
if self.cur_header or self.untitled_header or not self.toggle_slide_id:
self.toggle_slide_id = slide_id
elif header:
# nested header
header = ' ' + header
classes = []
if 'hide' in self.slide_options and not self.options['config'].unhide_slides:
if self.slide_number > 1 and not self.qtypes[-1] and self.options['config'].pace != QUESTION_PACE:
# Explicitly hidden,not first slide,not question slide,and not question paced
self.sheet_attributes['hiddenSlides'].append(self.slide_number)
classes.append('slidoc-slide-hidden')
else:
message(' ****HIDDEN-WARNING: %s: Slide %s,Hidden: ignored for first slide/question slide/question-paced sessions' % (self.options["filename"], self.slide_number))
attrs = ''
if self.all_params:
attrs += ' data-param-count="%d"' % len(self.all_params)
html = '''<div id="%s-footer-toggle" class="slidoc-footer-toggle %s-footer-toggle %s" %s style="display: none;">%s</div>\n''' % (slide_id, self.toggle_slide_id, ' '.join(classes), attrs, header)
return html
def block_code(self, text, lang):
linenos = inlinestyles = 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, cssclass='codehilite'
)
code = highlight(text, formatter)
if linenos:
return '<div class="highlight-wrapper">%s</div>\n' % code
return '<div class="doc doc-code">%s</div>%s' % (lang.upper(), code)
except:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
def block_code(self, lang):
lang = 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()
return highlight(code, formatter)
# renderer = HighlightRenderer()
# markdown = mistune.Markdown(renderer=renderer)
# print(markdown('```python\nassert 1 == 1\n```'))
def block_code(self, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return highlight(code, formatter)
def new_img_tag(src, alt, title, classes=[], image_url='', image_dir=''):
'''Return img tag string,supporting extension of including align/height/width attributes in title string'''
attrs = ''
style = ''
classList = classes[:]
if title:
for attr in shlex.split(title):
if attr.startswith('.'):
classList.append(attr[1:])
title = title.replace(attr, '')
for attr in ('align', 'height', 'width'):
value = get_html_tag_attr(attr, ' '+title)
if value:
attrs += ' ' + attr + '=' + value
title = re.sub(Attr_re_format % attr, '', title)
for attr in ('crop',):
value = get_html_tag_attr(attr, ' '+title)
if value:
if attr == 'crop':
style += 'object-fit:cover;object-position:' + ' '.join(value.strip().split(',')) + ';'
title = re.sub(Attr_re_format % attr, title)
if title.strip():
attrs += ' title="' + mistune.escape(title.strip(), quote=True) + '"'
if style:
attrs += ' style="' + style + '"'
if get_url_scheme(src) == 'rel_path':
if image_url:
src = image_url + src
elif image_dir and not src.startswith(image_dir+'/'):
# Ensure relative paths point to image dir
src = image_dir + '/' + os.path.basename(src)
if classList:
attrs += ' class="%s"' % ' '.join(classList)
return '<img src="%s" alt="%s" %s>' % (src, attrs)
def link(self, text):
link = escape_link(link)
site = Site.objects.get_current()
nofollow = "" if link.find(site.domain) > 0 else "rel='nofollow'"
if not link:
link = "#"
if not title:
return '<a href="%s" %s>%s</a>' % (link, text)
title = escape(title, quote=True)
return '<a href="%s" title="%s" %s>%s</a>' % (link, text)
def get_markdown(value):
renderer = BlogMarkDownRenderer(inlinestyles=False)
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)
def codespan(self, text):
return '<codeph>{0}</codeph>'.format(escape(text.rstrip()))
def link(self, content):
return '<xref href="{0}">{1}</xref>'.format(link, escape(content or title))
def block_code(self, language=None):
code = escape(code.rstrip('\n'))
if language:
return ('<codeblock outputclass="language-{0}">{1}</codeblock>'
.format(language, code))
else:
return '<codeblock>{0}</codeblock>'.format(code)
def image(self, src, text):
# Derived from the mistune library source code
src = mistune.escape_link(src)
text = escape(text, quote=True)
if title:
title = escape(title, quote=True)
output = ('<fig><title>{0}</title>\n'
'<image href="{1}" alt="{2}"/></fig>'
.format(title, text))
else:
output = '<image href="{0}" alt="{1}"/>'.format(src, text)
return output
def autolink(self, is_email=False):
text = link = escape(link)
if is_email:
link = 'mailto:{0}'.format(link)
return '<xref href="{0}">{1}</xref>'.format(link, text)
def block_code(self, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)
lexer = get_lexer_by_name(lang, formatter)
def inline_formula(self, alt_text):
text = text.strip()
alt_text = alt_text.strip() if alt_text is not None else alt_text
js_format = alt_text or ''
slide_id = self.get_slide_id()
plugin_refs = []
imatch = INLINE_METHOD_RE.match(text)
if imatch and imatch.group(1) not in FORMULA_NAMESPACE:
plugin_def_name = imatch.group(1)
action = imatch.group(2)
js_arg = imatch.group(3)
if action in ('answerSave', 'buttonClick', 'disable', 'display', 'enterSlide', 'expect', 'incrementSlide', 'init', 'initGlobal', 'initSetup', 'leaveSlide', 'response'):
abort(" ****PLUGIN-ERROR: %s: disallowed inline plugin action `=%s.%s()` in slide %s" % (self.options["filename"], plugin_def_name, action, self.slide_number))
else:
plugin_def_name = 'Params'
action = 'formula'
js_arg = text
for match in INLINE_PLUGIN_RE.findall(text):
if match.group(1) == '$':
plugin_refs.append( [match.group(2), int(match.group(3) or 0)] )
elif match.group(1) == '$$':
self.global_plugin_refs.add(match.group(2))
js_func = plugin_def_name + '.' + action
alt_html = mistune.escape('='+js_func+'()' if alt_text is None else alt_text)
if 'inline_formula' in self.options['config'].strip:
return '<code>%s</code>' % exponentiate(alt_html, times=True)
if plugin_def_name == 'Params' and action == 'formula':
self.slide_formulas.append(js_arg)
self.plugin_loads.add(plugin_def_name)
plugin_refs.append( [plugin_def_name, 0] )
for name, instance_num in plugin_refs:
if name not in self.slide_plugin_refs:
self.slide_plugin_refs[name] = instance_num
else:
self.slide_plugin_refs[name] = max(self.slide_plugin_refs[name], instance_num)
return '<code class="slidoc-inline-js" data-slidoc-js-function="%s" data-slidoc-js-argument="%s" data-slidoc-js-format="%s" data-slide-id="%s">%s</code>' % (js_func, mistune.escape(js_arg or ''), mistune.escape(js_format or ''), slide_id or '', alt_html)