How to Use Mistune

Mistune is super easy to use. Here is how you can convert Markdown formatted text into HTML:

import mistune


The .html() methods has enabled all the features you might want by default:

  • No escape of HTML tags
  • With strikethough plugin
  • With table plugin
  • With footnote plugin

Customize Mistune

Mistune provides a function to create Markdown instance easily:

import mistune

markdown = mistune.create_markdown()

This method will create a “escaped” Markdown instance without any plugins, which means:

# ==>

Non escaped version:

markdown = mistune.create_markdown(escape=False)
# ==>

Adding plugins:

markdown = mistune.create_markdown()
# ==>

markdown = mistune.create_markdown(plugins=['strikethough'])
# ==>

Find out what plugins mistune has built-in in Mistune Markdown Plugins sections.

Customize Renderer

Mistune supports renderer feature which enables developers to customize the output. For instance, to add code syntax highlight:

import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html

class HighlightRenderer(mistune.HTMLRenderer):
    def block_code(self, code, lang=None):
        if lang:
            lexer = get_lexer_by_name(lang, stripall=True)
            formatter = html.HtmlFormatter()
            return highlight(code, lexer, formatter)
        return '<pre><code>' + mistune.escape(code) + '</code></pre>'

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

print(markdown('```python\nassert 1 == 1\n```'))

In this way, we can use Pygments to highlight the fenced code. Learn more at Use renderers.


Mistune can produce AST by default with mistune.AstRenderer:

markdown = mistune.create_markdown(renderer=mistune.AstRenderer())

This markdown function will generate a list of tokens instead of HTML:

text = 'hello **world**'
# ==>
    'children': [
        {'text': 'hello ', 'type': 'text'},
            'children': [{'text': 'world', 'type': 'text'}],
            'type': 'strong'
    'type': 'paragraph'

It is also possible to pass renderer='ast' to create the markdown instance:

markdown = mistune.create_markdown(renderer='ast')