def safe_markdown(comment, extensions=[]):
html = markdown.markdown(comment, extensions=extensions)
return bleach.clean(
text=html,
tags=[
'a', 'abbr', 'acronym', 'b', 'blockqote', 'code', 'em', 'i', 'li',
'ol', 'strong', 'ul', 'p', 'span', 'h1', 'h2', 'h3', 'pre',
'blockquote', 'table', 'thead', 'tr', 'th', 'td', 'tbody', 'dl',
'dt', 'sup', 'div', 'hr',
],
attributes={
'*': ['class'],
'a': ['href', 'title', 'class', 'id'],
'acronym': ['title'],
'abbr': ['title'],
'sup': ['id'],
'li': ['id']
},
)
python类extensions()的实例源码
def html(text, lazy_images=False):
"""
To render a markdown format text into HTML.
- If you want to also build a Table of Content inside of the markdow,
add the tags: [TOC]
It will include a <ul><li>...</ul> of all <h*>
:param text:
:param lazy_images: bool - If true, it will activate the LazyImageExtension
:return:
"""
extensions = [
'markdown.extensions.nl2br',
'markdown.extensions.sane_lists',
'markdown.extensions.toc',
'markdown.extensions.tables',
OEmbedExtension()
]
if lazy_images:
extensions.append(LazyImageExtension())
return markdown.markdown(text, extensions=extensions)
def registerExtensions(self, extensions, configs): # noqa
"""
Register extensions with this instance of Markdown.
Keyword arguments:
* extensions: A list of extensions, which can either
be strings or objects. See the docstring on Markdown.
* configs: A dictionary mapping module names to config options.
"""
from markdown import util
from markdown.extensions import Extension
for ext in extensions:
try:
if isinstance(ext, util.string_type):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
ext.extendMarkdown(self, globals())
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
% (ext.__class__.__module__, ext.__class__.__name__)
)
except Exception:
# We want to gracefully continue even if an extension fails.
_log('Failed to load markdown module!')
_debug(traceback.format_exc(), ERROR)
return self
def registerExtensions(self, extensions, configs): # noqa
"""
Register extensions with this instance of Markdown.
Keyword arguments:
* extensions: A list of extensions, which can either
be strings or objects. See the docstring on Markdown.
* configs: A dictionary mapping module names to config options.
"""
from markdown import util
from markdown.extensions import Extension
for ext in extensions:
try:
if isinstance(ext, util.string_type):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
ext.extendMarkdown(self, globals())
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
% (ext.__class__.__module__, ext.__class__.__name__)
)
except Exception:
# We want to gracefully continue even if an extension fails.
_log('Failed to load markdown module!')
_debug(traceback.format_exc(), ERROR)
return self
def registerExtensions(self, extensions, configs): # noqa
"""
Register extensions with this instance of Markdown.
Keyword arguments:
* extensions: A list of extensions, which can either
be strings or objects. See the docstring on Markdown.
* configs: A dictionary mapping module names to config options.
"""
from markdown import util
from markdown.extensions import Extension
for ext in extensions:
try:
if isinstance(ext, util.string_type):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
ext.extendMarkdown(self, globals())
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
% (ext.__class__.__module__, ext.__class__.__name__)
)
except Exception:
# We want to gracefully continue even if an extension fails.
_log('Failed to load markdown module!')
_debug(traceback.format_exc(), ERROR)
return self
def compile_markdown(md, comments=False):
"""compiles markdown to html"""
extensions = [
GFM(),
NomMD(),
MathJaxExtension(),
FigureCaptionExtension(),
InlineGraphvizExtension(),
'markdown.extensions.footnotes',
'markdown.extensions.attr_list'
]
if comments:
extensions.append(CommentExtension())
return markdown.markdown(md, extensions=extensions, lazy_ol=False)
def toc(text):
"""
Return a table of context list
:param text:
:return:
"""
extensions = ['markdown.extensions.toc']
mkd = markdown.Markdown(extensions=extensions)
html = mkd.convert(text)
return mkd.toc
def extract_images(text):
"""
Extract all images in the content
:param text:
:return:
"""
extensions = [ExtractImagesExtension()]
mkd = markdown.Markdown(extensions=extensions)
html = mkd.convert(text)
return mkd.images
# ------------------------------------------------------------------------------
def __init__(self, environment):
super(MarkdownTagExtension, self).__init__(environment)
environment.extend(
markdowner=markdown.Markdown(extensions=['extra'])
)
def md2html(view, markup, template_vars=None, template_env_options=None, nl2br=True):
"""Convert Markdown to HTML."""
if _get_setting('mdpopups.use_sublime_highlighter'):
sublime_hl = (True, _get_sublime_highlighter(view))
else:
sublime_hl = (False, None)
extensions = [
"markdown.extensions.attr_list",
"markdown.extensions.codehilite",
"mdpopups.mdx.superfences",
"mdpopups.mdx.betterem",
"mdpopups.mdx.magiclink",
"mdpopups.mdx.inlinehilite",
"mdpopups.mdx.extrarawhtml",
"markdown.extensions.admonition",
"markdown.extensions.def_list"
]
if nl2br:
extensions.append('markdown.extensions.nl2br')
configs = {
"mdpopups.mdx.inlinehilite": {
"style_plain_text": True,
"css_class": "inline-highlight",
"use_codehilite_settings": False,
"guess_lang": False,
"sublime_hl": sublime_hl
},
"markdown.extensions.codehilite": {
"guess_lang": False,
"css_class": "highlight"
},
"mdpopups.mdx.superfences": {
"uml_flow": False,
"uml_sequence": False,
"sublime_hl": sublime_hl
}
}
return _MdWrapper(
extensions=extensions,
extension_configs=configs
).convert(_markup_template(markup, template_vars, template_env_options)).replace('"', '"').replace('\n', '')
def md2html(view, markup, template_vars=None, template_env_options=None, nl2br=True):
"""Convert Markdown to HTML."""
if _get_setting('mdpopups.use_sublime_highlighter'):
sublime_hl = (True, _get_sublime_highlighter(view))
else:
sublime_hl = (False, None)
extensions = [
"markdown.extensions.attr_list",
"markdown.extensions.codehilite",
"mdpopups.mdx.superfences",
"mdpopups.mdx.betterem",
"mdpopups.mdx.magiclink",
"mdpopups.mdx.inlinehilite",
"mdpopups.mdx.extrarawhtml",
"markdown.extensions.admonition",
"markdown.extensions.def_list"
]
if nl2br:
extensions.append('markdown.extensions.nl2br')
configs = {
"mdpopups.mdx.inlinehilite": {
"style_plain_text": True,
"css_class": "inline-highlight",
"use_codehilite_settings": False,
"guess_lang": False,
"sublime_hl": sublime_hl
},
"markdown.extensions.codehilite": {
"guess_lang": False,
"css_class": "highlight"
},
"mdpopups.mdx.superfences": {
"uml_flow": False,
"uml_sequence": False,
"sublime_hl": sublime_hl
}
}
return _MdWrapper(
extensions=extensions,
extension_configs=configs
).convert(_markup_template(markup, template_vars, template_env_options)).replace('"', '"').replace('\n', '')
def md2html(view, markup, template_vars=None, template_env_options=None, nl2br=True):
"""Convert Markdown to HTML."""
if _get_setting('mdpopups.use_sublime_highlighter'):
sublime_hl = (True, _get_sublime_highlighter(view))
else:
sublime_hl = (False, None)
extensions = [
"markdown.extensions.attr_list",
"markdown.extensions.codehilite",
"mdpopups.mdx.superfences",
"mdpopups.mdx.betterem",
"mdpopups.mdx.magiclink",
"mdpopups.mdx.inlinehilite",
"mdpopups.mdx.extrarawhtml",
"markdown.extensions.admonition",
"markdown.extensions.def_list"
]
if nl2br:
extensions.append('markdown.extensions.nl2br')
configs = {
"mdpopups.mdx.inlinehilite": {
"style_plain_text": True,
"css_class": "inline-highlight",
"use_codehilite_settings": False,
"guess_lang": False,
"sublime_hl": sublime_hl
},
"markdown.extensions.codehilite": {
"guess_lang": False,
"css_class": "highlight"
},
"mdpopups.mdx.superfences": {
"uml_flow": False,
"uml_sequence": False,
"sublime_hl": sublime_hl
}
}
return _MdWrapper(
extensions=extensions,
extension_configs=configs
).convert(_markup_template(markup, template_vars, template_env_options)).replace('"', '"').replace('\n', '')