API Reference

Here are the list of API reference; it might be helpful for developers.

Basic

mistune.html(text)
Parameters:text – markdown formatted text

Turn markdown text into HTML without escaping. For instance:

text = '**hello** <span>world</span>'
mistune.html(text)

# =>
'<p><strong>hello</strong> <span>world</span></p>'
mistune.create_markdown(escape=True, hard_wrap=False, renderer='html', plugins=None)

Create a Markdown instance based on the given condition.

Parameters:
  • escape – Boolean. If using html renderer, escape html.
  • hard_wrap – Boolean. Break every new line into <br>.
  • renderer – renderer instance, default is HTMLRenderer.
  • plugins – List of plugins.

This method is used when you want to re-use a Markdown instance:

markdown = create_markdown(
    escape=False,
    hard_wrap=True,
)
# re-use markdown function
markdown('.... your text ...')

Utilities

mistune.escape(s, quote=True)

Escape characters of &<>. If quote=True, " will be converted to &quote;.

mistune.escape_url(link)

Escape URL for safety.

mistune.safe_entity(s)

Escape characters for safety.

mistune.unikey(s)

Generate a unique key for links and footnotes.

Advanced

class mistune.Markdown(renderer=None, block=None, inline=None, plugins=None)

Markdown instance to convert markdown text into HTML or other formats. Here is an example with the HTMLRenderer:

from mistune import HTMLRenderer

md = Markdown(renderer=HTMLRenderer(escape=False))
md('hello **world**')
Parameters:
  • renderer – a renderer to convert parsed tokens
  • block – block level syntax parser
  • inline – inline level syntax parser
  • plugins – mistune plugins to use
class mistune.BlockState(parent=None)

The state to save block parser’s cursor and tokens.

append_token(token)

Add token to the end of token list.

prepend_token(token)

Insert token before the last token.

class mistune.InlineState(env)

The state to save inline parser’s tokens.

append_token(token)

Add token to the end of token list.

copy()

Create a copy of current state.

prepend_token(token)

Insert token before the last token.

class mistune.BlockParser(block_quote_rules: Optional[List[str]] = None, list_rules: Optional[List[str]] = None, max_nested_level: int = 6)
extract_block_quote(m: re.Match, state: mistune.core.BlockState) → Tuple[str, int]

Extract text and cursor end position of a block quote.

parse_axt_heading(m: re.Match, state: mistune.core.BlockState) → int

Parse token for AXT heading. An AXT heading is started with 1 to 6 symbol of #.

parse_blank_line(m: re.Match, state: mistune.core.BlockState) → int

Parse token for blank lines.

parse_block_quote(m: re.Match, state: mistune.core.BlockState) → int

Parse token for block quote. Here is an example of the syntax:

> a block quote starts
> with right arrows
parse_fenced_code(m: re.Match, state: mistune.core.BlockState) → Optional[int]

Parse token for fenced code block. A fenced code block is started with 3 or more backtick(`) or tilde(~).

An example of a fenced code block:

```python
def markdown(text):
    return mistune.html(text)
```
parse_indent_code(m: re.Match, state: mistune.core.BlockState) → int

Parse token for code block which is indented by 4 spaces.

parse_list(m: re.Match, state: mistune.core.BlockState) → int

Parse tokens for ordered and unordered list.

Parse link references and save the link information into state.env.

Here is an example of a link reference:

a [link][example]

[example]: https://example.com "Optional title"

This method will save the link reference into state.env as:

state.env['ref_links']['example'] = {
    'url': 'https://example.com',
    'title': "Optional title",
}
parse_setex_heading(m: re.Match, state: mistune.core.BlockState) → Optional[int]

Parse token for setex style heading. A setex heading syntax looks like:

H1 title
========
parse_thematic_break(m: re.Match, state: mistune.core.BlockState) → int

Parse token for thematic break, e.g. <hr> tag in HTML.

register(name, pattern, func, before=None)

Register a new rule to parse the token. This method is usually used to create a new plugin.

Parameters:
  • name – name of the new grammar
  • pattern – regex pattern in string
  • func – the parsing function
  • before – insert this rule before a built-in rule
state_cls

alias of mistune.core.BlockState

class mistune.InlineParser(hard_wrap=False)
HARD_LINEBREAK = ' *\\n\\s*'

every new line becomes <br>

STD_LINEBREAK = '(?:\\\\| {2,})\\n\\s*'

linebreak leaves two spaces at the end of line

register(name, pattern, func, before=None)

Register a new rule to parse the token. This method is usually used to create a new plugin.

Parameters:
  • name – name of the new grammar
  • pattern – regex pattern in string
  • func – the parsing function
  • before – insert this rule before a built-in rule
state_cls

alias of mistune.core.InlineState

Plugins

mistune.plugins.footnotes.footnotes(md)

A mistune plugin to support footnotes, spec defined at https://michelf.ca/projects/php-markdown/extra/#footnotes

Here is an example:

That's some text with a footnote.[^1]

[^1]: And that's the footnote.

It will be converted into HTML:

<p>That's some text with a footnote.<sup class="footnote-ref" id="fnref-1"><a href="#fn-1">1</a></sup></p>
<section class="footnotes">
<ol>
<li id="fn-1"><p>And that's the footnote.<a href="#fnref-1" class="footnote">&#8617;</a></p></li>
</ol>
</section>
Parameters:md – Markdown instance
mistune.plugins.task_lists.task_lists(md)

A mistune plugin to support task lists. Spec defined by GitHub flavored Markdown and commonly used by many parsers:

- [ ] unchecked task
- [x] checked task
Parameters:md – Markdown instance
mistune.plugins.abbr.abbr(md)

A mistune plugin to support abbreviations, spec defined at https://michelf.ca/projects/php-markdown/extra/#abbr

Here is an example:

The HTML specification
is maintained by the W3C.

*[HTML]: Hyper Text Markup Language
*[W3C]:  World Wide Web Consortium

It will be converted into HTML:

The <abbr title="Hyper Text Markup Language">HTML</abbr> specification
is maintained by the <abbr title="World Wide Web Consortium">W3C</abbr>.
Parameters:md – Markdown instance
mistune.plugins.def_list.def_list(md)

A mistune plugin to support def list, spec defined at https://michelf.ca/projects/php-markdown/extra/#def-list

Here is an example:

Apple
:   Pomaceous fruit of plants of the genus Malus in
    the family Rosaceae.

Orange
:   The fruit of an evergreen tree of the genus Citrus.

It will be converted into HTML:

<dl>
<dt>Apple</dt>
<dd>Pomaceous fruit of plants of the genus Malus in
the family Rosaceae.</dd>

<dt>Orange</dt>
<dd>The fruit of an evergreen tree of the genus Citrus.</dd>
</dl>
Parameters:md – Markdown instance
mistune.plugins.table.table(md)

A mistune plugin to support table, spec defined at https://michelf.ca/projects/php-markdown/extra/#table

Here is an example:

First Header  | Second Header
------------- | -------------
Content Cell  | Content Cell
Content Cell  | Content Cell
Parameters:md – Markdown instance
mistune.plugins.table.table_in_quote(md)

Enable table plugin in block quotes.

mistune.plugins.table.table_in_list(md)

Enable table plugin in list.

mistune.plugins.math.math(md)

A mistune plugin to support math. The syntax is used by many markdown extensions:

Block math is surrounded by $$:

$$
f(a)=f(b)
$$

Inline math is surrounded by `$`, such as $f(a)=f(b)$
Parameters:md – Markdown instance
mistune.plugins.math.math_in_quote(md)

Enable block math plugin in block quote.

mistune.plugins.math.math_in_list(md)

Enable block math plugin in list.

mistune.plugins.ruby.ruby(md)

A mistune plugin to support <ruby> tag. The syntax is defined at https://lepture.com/en/2022/markdown-ruby-markup:

[漢字(ㄏㄢˋㄗˋ)]
[漢(ㄏㄢˋ)字(ㄗˋ)]

[漢字(ㄏㄢˋㄗˋ)][link]
[漢字(ㄏㄢˋㄗˋ)](/url "title")

[link]: /url "title"
Parameters:md – Markdown instance
mistune.plugins.formatting.strikethrough(md)

A mistune plugin to support strikethrough. Spec defined by GitHub flavored Markdown and commonly used by many parsers:

~~This was mistaken text~~

It will be converted into HTML:

<del>This was mistaken text</del>
Parameters:md – Markdown instance
mistune.plugins.formatting.mark(md)

A mistune plugin to add <mark> tag. Spec defined at https://facelessuser.github.io/pymdown-extensions/extensions/mark/:

==mark me== ==mark \=\= equal==
Parameters:md – Markdown instance
mistune.plugins.formatting.insert(md)

A mistune plugin to add <ins> tag. Spec defined at https://facelessuser.github.io/pymdown-extensions/extensions/caret/#insert:

^^insert me^^
Parameters:md – Markdown instance
mistune.plugins.formatting.superscript(md)

A mistune plugin to add <sup> tag. Spec defined at https://pandoc.org/MANUAL.html#superscripts-and-subscripts:

2^10^ is 1024.
Parameters:md – Markdown instance
mistune.plugins.formatting.subscript(md)

A mistune plugin to add <sub> tag. Spec defined at https://pandoc.org/MANUAL.html#superscripts-and-subscripts:

H~2~O is a liquid.
Parameters:md – Markdown instance
mistune.plugins.spoiler.spoiler(md)

A mistune plugin to support block and inline spoiler. The syntax is inspired by stackexchange:

Block level spoiler looks like block quote, but with `>!`:

>! this is spoiler
>!
>! the content will be hidden

Inline spoiler is surrounded by `>!` and `!<`, such as >! hide me !<.
Parameters:md – Markdown instance

TOC hook

mistune.toc.add_toc_hook(md, min_level=1, max_level=3, heading_id=None)

Add a hook to save toc items into state.env. This is usually helpful for doc generator:

import mistune
from mistune.toc import add_toc_hook, render_toc_ul

md = mistune.create_markdown(...)
add_toc_hook(md, level, heading_id)

html, state = md.parse(text)
toc_items = state.env['toc_items']
toc_html = render_toc_ul(toc_items)
Parameters:
  • md – Markdown instance
  • min_level – min heading level
  • max_level – max heading level
  • heading_id – a function to generate heading_id
mistune.toc.render_toc_ul(toc)

Render a <ul> table of content HTML. The param “toc” should be formatted into this structure:

[
  (level, id, text),
]

For example:

[
  (1, 'toc-intro', 'Introduction'),
  (2, 'toc-install', 'Install'),
  (2, 'toc-upgrade', 'Upgrade'),
  (1, 'toc-license', 'License'),
]

Directives

class mistune.directives.RSTDirective(plugins)

A RST style of directive syntax is inspired by reStructuredText. The syntax is very powerful that you can define a lot of custom features on your own. The syntax looks like:

.. directive-name:: directive value
   :option-key: option value
   :option-key: option value

   content text here

To use RSTDirective, developers can add it into plugin list in the Markdown instance:

import mistune
from mistune.directives import RSTDirective, Admonition

md = mistune.create_markdown(plugins=[
    # ...
    RSTDirective([Admonition()]),
])
class mistune.directives.FencedDirective(plugins, markers='`~')

A fenced style of directive looks like a fenced code block, it is inspired by markdown-it-docutils. The syntax looks like:

```{directive-name} title
:option-key: option value
:option-key: option value

content text here
```

To use FencedDirective, developers can add it into plugin list in the Markdown instance:

import mistune
from mistune.directives import FencedDirective, Admonition

md = mistune.create_markdown(plugins=[
    # ...
    FencedDirective([Admonition()]),
])

FencedDirective is using >= 3 backticks or curly-brackets for the fenced syntax. Developers can change it to other characters, e.g. colon:

directive = FencedDirective([Admonition()], ':')

And then the directive syntax would look like:

::::{note} Nesting directives
You can nest directives by ensuring the start and end fence matching
the length. For instance, in this example, the admonition is started
with 4 colons, then it should end with 4 colons.

You can nest another admonition with other length of colons except 4.

:::{tip} Longer outermost fence
It would be better that you put longer markers for the outer fence,
and shorter markers for the inner fence. In this example, we put 4
colons outsie, and 3 colons inside.
:::
::::
Parameters:
  • plugins – list of directive plugins
  • markers – characters to determine the fence, default is backtick and curly-bracket