Python mistune.Markdown() Examples

The following are 22 code examples of mistune.Markdown(). 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: test_plugins.py    From mistune with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_plugin(plugin_name, ast=False):
    _plugin = getattr(plugins, 'plugin_{}'.format(plugin_name))

    class TestPlugin(BaseTestCase):
        md = Markdown(
            renderer=HTMLRenderer(escape=False),
            plugins=[_plugin]
        )

    def test_ast_renderer(self):
        md = Markdown(renderer=AstRenderer(), plugins=[_plugin])
        data = fixtures.load_json(plugin_name + '.json')
        self.assertEqual(md(data['text']), data['tokens'])

    if ast:
        test_ast_renderer.__doc__ = 'Run {} ast renderer'.format(plugin_name)
        setattr(TestPlugin, 'test_ast_renderer', test_ast_renderer)

    TestPlugin.load_fixtures(plugin_name + '.txt')
    globals()['TestPlugin_' + plugin_name] = TestPlugin 
Example #2
Source File: maxpress.py    From maxpress with MIT License 6 votes vote down vote up
def md2html(text, styles=None, poster='', banner='', convert_list=True, ul_style='\u25CB'):
    md = Markdown()

    # 将markdown列表转化为带序号的普通段落(纯为适应微信中列表序号样式自动丢失的古怪现象)
    if convert_list:
        blocks = text.split('\n```')
        for i in range(0, len(blocks)):
            if i % 2 == 0:
                blocks[i] = re.sub(r'(\n\d+)(\.\s.*?)', r'\n\1\\\2', blocks[i])
                blocks[i] = re.sub(r'\n[\-\+\*](\s.*?)',
                                   u'\n\n{} \1'.format(ul_style), blocks[i])
            else:
                continue  # 跳过代码块内部内容
        text = '\n```'.join(blocks)

    inner_html = md(text)
    result = premailer.transform(pack_html(inner_html, styles, poster, banner))
    return result 
Example #3
Source File: markdown_parser.py    From markdown-search with GNU General Public License v2.0 5 votes vote down vote up
def parse(self, markdown_text, config):
        renderer = ParsingRenderer()
        markdown = mistune.Markdown(renderer=renderer)
        markdown(markdown_text)
        self.blocks = renderer.blocks
        self.headlines = renderer.headlines if renderer.headlines.strip() else u''
        self.tags = self.get_tags_line(markdown_text, config) 
Example #4
Source File: test_misc.py    From mistune with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_plugin(self):
        from mistune.plugins import plugin_url
        md = mistune.Markdown(mistune.HTMLRenderer())
        md.use(plugin_url) 
Example #5
Source File: test_misc.py    From mistune with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_data_protocols(self):
        renderer = mistune.HTMLRenderer(allow_harmful_protocols=['data:'])
        md = mistune.Markdown(renderer)
        result = md('[h](data:alert)')
        expected = '<p><a href="data:alert">h</a></p>'
        self.assertEqual(result.strip(), expected) 
Example #6
Source File: test_misc.py    From mistune with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_harmful_protocols(self):
        renderer = mistune.HTMLRenderer(allow_harmful_protocols=True)
        md = mistune.Markdown(renderer)
        result = md('[h](javascript:alert)')
        expected = '<p><a href="javascript:alert">h</a></p>'
        self.assertEqual(result.strip(), expected) 
Example #7
Source File: renderer.py    From maildown with MIT License 5 votes vote down vote up
def generate_content(
    md_content: str, theme: Optional[str] = None, context: Optional[dict] = None
):
    """
    Generates the content of an email to be sent. This method actually renders two templates:
    1. The extremely simple local template, which writes the stylesheet, header and user-provided md_content to the
    message
    2.  The result of 1. is also treated as a jinja template, and rendered using the arguments provided in the context
    parameter

    Apart from rendering the template, this method also does two other things:
    1. Applies an additional highlight renderer with better support for code blocks
    2. Uses premailer.transform to bake the css into the HTML
    """
    if not theme:
        theme = os.path.join(os.path.dirname(os.path.abspath(__file__)), "style.css")

    if not context:
        context = {}

    with open(theme) as f:
        theme = f.read()

    markdown = mistune.Markdown(renderer=HighlightRenderer())

    with open(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "template.jinja2")
    ) as t:
        template = jinja2.Template(t.read())
    content = premailer.transform(
        template.render(content=markdown(md_content), stylesheet=theme)
    )

    new_template = jinja2.Template(content)
    return new_template.render(context)


#
# with open('test.md') as r:
#     with open('test.html', 'w') as f:
#         f.write(generate_content(r.read(), theme='my-style.css', context=dict(things=['Thing 1', 'Thing 2']))) 
Example #8
Source File: articles.py    From cmddocs with MIT License 5 votes vote down vote up
def view_article(article, dir, pager, extension, pagerflags, colors):
    "view an article within your docs"
    a = add_fileextension(article, extension)
    a = os.path.join(dir, a)
    # read original file
    try:
        article = open(a, "r")
    except IOError:
        print("Error: Could not find %s" % article)
        return False

    content = article.read()
    article.close()

    # hand everything over to mistune lexer
    with tempfile.NamedTemporaryFile(delete=False, mode='w') as tmp:
        md = mistune.Markdown(renderer=md_to_ascii(colors))
        tmp.write(md.render(content))

    # start pager and cleanup tmp file afterwards
    # also parse flags for local pager
    try:
        if pagerflags is False:
            subprocess.call([pager, tmp.name])
        else:
            subprocess.call([pager, pagerflags, tmp.name])
    except OSError:
        print("Error: '%s' No such file or directory" % pager)

    try:
        os.remove(tmp.name)
    except OSError:
        print("Error: Could not remove %s" % tmp.name) 
Example #9
Source File: maxpress.py    From maxpress with MIT License 5 votes vote down vote up
def report_error(func):
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            return result
        except Exception as e:
            print('错误: {}'.format(e))
            input('提示:运行前请将所有要转换的Markdown文档放入temp目录中\n'
                  '请按回车键退出程序:')

    return wrapper

# 用于处理嵌套目录 
Example #10
Source File: report.py    From sklearn-evaluation with MIT License 5 votes vote down vote up
def __init__(self, evaluator, template=None):
        self.evaluator = evaluator

        if template is None:
            template = jinja_env().get_template(self.evaluator.TEMPLATE_NAME)
        elif isinstance(template, Path):
            template = Template(template.read_text())
        elif isinstance(template, str):
            template = Template(template)

        rendered = template.render(e=evaluator)
        md = mistune.Markdown()
        self.rendered = md(rendered) 
Example #11
Source File: populate.py    From PcbDraw with MIT License 5 votes vote down vote up
def parse_content(renderer, content):
    lexer = PcbDrawInlineLexer(renderer)
    processor = mistune.Markdown(renderer=renderer, inline=lexer)
    processor(content)
    return renderer.output() 
Example #12
Source File: markdown.py    From Spirit with MIT License 5 votes vote down vote up
def __call__(self, text):
        return super(Markdown, self).__call__(text).strip() 
Example #13
Source File: markdown.py    From Spirit with MIT License 5 votes vote down vote up
def __init__(self, no_follow=True):
        renderer = Renderer(
            escape=True,
            hard_wrap=True,
            no_follow=no_follow
        )
        super(Markdown, self).__init__(
            renderer=renderer,
            block=BlockLexer,
            inline=InlineLexer,
            parse_block_html=False,
            parse_inline_html=False
        )

    # Override 
Example #14
Source File: news_extra.py    From pythonic-news with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup(cls):
        renderer = cls(escape=True, hard_wrap=True)
        return mistune.Markdown(renderer=renderer) 
Example #15
Source File: t.py    From TemPy with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self._html_parser = TempyParser()
        self._markdown_parser = Markdown(renderer=TempyMarkdownRenderer()) 
Example #16
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 #17
Source File: test_toc.py    From mistune-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_toc():
    toc = TocRenderer()
    md = mistune.Markdown(renderer=toc)
    toc.reset_toc()
    assert 'toc-0' in md.parse(text)
    rv = toc.render_toc(level=3)
    rv = rv.replace('\n', '').replace(' ', '')
    assert rv == expected.replace('\n', '').replace(' ', '') 
Example #18
Source File: mistune_markdown.py    From Django-blog with MIT License 5 votes vote down vote up
def article_markdown(text):
    """ 对传入的text文本进行markdown """
    renderer = ArticleRenderer()
    markdown = mistune.Markdown(renderer=renderer)
    return markdown(text) 
Example #19
Source File: markdown.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, app):
        app.jinja_env.filters.setdefault('markdown', self.__call__)
        renderer = Renderer(escape=False, hard_wrap=True)
        self.markdown = mistune.Markdown(renderer=renderer) 
Example #20
Source File: md.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def renderMarkdown(uuid, text, fileName):
    """Renders the given text"""
    warnings = []
    errors = []
    renderedText = None
    try:
        renderer = CDMMarkdownRenderer(uuid, fileName)
        markdown = mistune.Markdown(renderer=renderer)
        renderedText = markdown(text)
    except Exception as exc:
        errors.append(str(exc))
    except:
        errors.append('Unknown markdown rendering exception')
    return renderedText, errors, warnings 
Example #21
Source File: md_helpers.py    From dockerfiles with MIT License 4 votes vote down vote up
def markdown_convert(markdown_string) -> str:
    def _get_contents(text):
        try:
            contents = json.loads(text).get('message', '')
        except json.decoder.JSONDecodeError:
            contents = text
        except AttributeError:
            contents = text

        return contents

    class ButtonRenderer(mistune.Renderer):
        '''
        Syntax for MD buttons
            %%%{JSON.message}%%%
        For example:
            %%%%{"message": "Something here"}%%%%
        Output:
            Something here
        '''

        def paragraph(self, text):
            text = _get_contents(text)
            return f'<p>{text}</p>'

    class ButtonInlineLexer(mistune.InlineLexer):
        def enable_md_button(self):
            self.rules.md_button = re.compile(r'%%%(.*?)%%%')
            self.default_rules.insert(3, 'md_button')

        def placeholder(self):
            pass

        def output_md_button(self, m):
            text = m.group(1)
            return self.renderer.paragraph(text)

    renderer = ButtonRenderer()
    inline_lexer = ButtonInlineLexer(renderer)
    inline_lexer.enable_md_button()

    md = mistune.Markdown(renderer, inline=inline_lexer)
    return md(markdown_string).strip() 
Example #22
Source File: pandoc.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'):
    """Convert an input string using pandoc.

    Pandoc converts an input string `from` a format `to` a target format.

    Parameters
    ----------
    source : string
      Input string, assumed to be valid format `from`.
    fmt : string
      The name of the input format (markdown, etc.)
    to : string
      The name of the output format (html, etc.)

    Returns
    -------
    out : unicode
      Output as returned by pandoc.

    Raises
    ------
    PandocMissing
      If pandoc is not installed.
    
    Any error messages generated by pandoc are printed to stderr.

    """
    cmd = ['pandoc', '-f', fmt, '-t', to]
    if extra_args:
        cmd.extend(extra_args)

    # iOS: we cannot call pandoc, so we just don't convert markdown cells.
    # This is not perfect (...) but it lets the conversion machine work.
    # iOS: we replaced pandoc with a mistune plugin. It's not as good but it works
    # iOS, TODO: tables in LaTeX, html in LaTeX
    if (sys.platform == 'darwin' and platform.machine().startswith('iP')):
        if (fmt.startswith('markdown') and to.startswith('latex')):
            markdown_to_latex = mistune.Markdown(renderer=LatexRenderer())
            return markdown_to_latex(source)
        elif (fmt.startswith('markdown') and to.startswith('rst')):
            return convert(source) # m2r markdown to rst conversion
        elif (fmt.startswith('markdown') and to.startswith('asciidoc')):
            markdown_to_asciidoc = mistune.Markdown(renderer=AsciidocRenderer())
            return markdown_to_asciidoc(source)
        else: 
            return source

    # this will raise an exception that will pop us out of here
    check_pandoc_version()
    
    # we can safely continue
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out, _ = p.communicate(cast_bytes(source, encoding))
    out = TextIOWrapper(BytesIO(out), encoding, 'replace').read()
    return out.rstrip('\n')