Markdown-It-Py Plugin Extensions#
Built-in#
The following plugins are embedded within the core package:
tables (GFM)
strikethrough (GFM)
These can be enabled individually:
from markdown_it import MarkdownIt
md = MarkdownIt("commonmark").enable("table")
or as part of a configuration:
from markdown_it import MarkdownIt
md = MarkdownIt("gfm-like")
See also
mdit-py-plugins package#
The mdit_py_plugins package contains a number of common plugins.
Each plugin is a function in its own submodule (for example mdit_py_plugins.footnote.footnote_plugin),
so import it from there; the top-level package does not re-export them.
Load a plugin with MarkdownIt.use, passing any options as keyword arguments.
use returns the MarkdownIt instance, so the calls can be chained:
from markdown_it import MarkdownIt
from mdit_py_plugins.footnote import footnote_plugin
from mdit_py_plugins.front_matter import front_matter_plugin
from mdit_py_plugins.tasklists import tasklists_plugin
md = (
MarkdownIt("commonmark")
.use(front_matter_plugin)
.use(footnote_plugin)
.use(tasklists_plugin, enabled=True)
)
text = """\
---
title: Example
---
- [x] Some *Markdown*[^1]
[^1]: A footnote.
"""
html_string = md.render(text)
The options of each plugin are listed in its section below.
Front-Matter#
- mdit_py_plugins.front_matter.front_matter_plugin(md: MarkdownIt) None[source]#
Plugin ported from markdown-it-front-matter.
It parses initial metadata, stored between opening/closing dashes:
--- valid-front-matter: true ---
Extract metadata and render HTML#
Register the plugin, parse the source once, then render the resulting tokens:
from markdown_it import MarkdownIt
from mdit_py_plugins.front_matter import front_matter_plugin
md = MarkdownIt("commonmark").use(front_matter_plugin)
source = "---\ntitle: Example\ndraft: false\n---\n# Welcome\n"
env = {}
tokens = md.parse(source, env)
front_matter = next(
(token.content for token in tokens if token.type == "front_matter"), None
)
html = md.renderer.render(tokens, md.options, env)
assert front_matter == "title: Example\ndraft: false"
assert html == "\n<h1>Welcome</h1>\n"
The front_matter token contains the metadata text without its delimiters.
It is hidden, so the default HTML renderer omits it.
Pass the same env to parsing and rendering so other plugins can share their state.
Calling md.render(source) instead would parse the source again.
The plugin does not parse YAML or store metadata in env.
To convert YAML text into Python objects, use a YAML parser separately.
For example, with PyYAML installed:
import yaml
metadata = yaml.safe_load(front_matter) if front_matter else {}
assert metadata == {"title": "Example", "draft": False}
YAML can also produce lists or scalar values; validate the result if your application
requires a mapping or particular fields.
The extraction example returns None when no front matter is present and an empty
string for an empty front-matter block.
Place the opening --- at the very start of the document, without leading blank
lines or indentation, and close the block with another --- line.
GFM (GitHub Flavored Markdown)#
- mdit_py_plugins.gfm.gfm_plugin(md: MarkdownIt, *, dollarmath: bool = False, front_matter: bool = False, tasklists_editable: bool = False) None[source]#
Enable GFM-like rendering.
Starts from the current parser configuration and enables the GFM components on top.
- Parameters:
dollarmath – Enable dollar-delimited math (
$...$,$$...$$).front_matter – Enable YAML front matter (
---).tasklists_editable – If True, rendered task list checkboxes are not disabled (i.e. they are interactive).
GFM Autolinks#
- mdit_py_plugins.gfm_autolink.gfm_autolink_plugin(md: MarkdownIt) None[source]#
Enable the GFM autolink extension.
Recognises bare
www.URLs,http(s)://URLs,mailto:/xmpp:links, and bare email addresses.Requires markdown-it-py ≥ 4.1.0.
Footnotes#
- mdit_py_plugins.footnote.footnote_plugin(md: MarkdownIt, *, inline: bool = True, move_to_end: bool = True, always_match_refs: bool = False) None[source]#
Plugin ported from markdown-it-footnote.
It is based on the pandoc definition:
Normal footnote: Here is a footnote reference,[^1] and another.[^longnote] [^1]: Here is the footnote. [^longnote]: Here's one with multiple blocks. Subsequent paragraphs are indented to show that they belong to the previous footnote.
- Parameters:
inline – If True, also parse inline footnotes (^[…]).
move_to_end – If True, move footnote definitions to the end of the token stream.
always_match_refs – If True, match references, even if the footnote is not defined.
Definition Lists#
- mdit_py_plugins.deflist.deflist_plugin(md: MarkdownIt) None[source]#
Plugin ported from markdown-it-deflist.
The syntax is based on pandoc definition lists:
Term 1 : Definition 1 long form second paragraph Term 2 with *inline markup* ~ Definition 2a compact style ~ Definition 2b
Task lists#
- mdit_py_plugins.tasklists.tasklists_plugin(md: MarkdownIt, enabled: bool = False, label: bool = False, label_after: bool = False) None[source]#
Plugin for building task/todo lists out of markdown lists with items starting with [ ] or [x] .. Nothing else
- For example::
[ ] An item that needs doing
[x] An item that is complete
The rendered HTML checkboxes are disabled; to change this, pass a truthy value into the enabled property of the plugin options.
- Parameters:
enabled – True enables the rendered checkboxes
label – True wraps the rendered list items in a <label> element for UX purposes,
label_after – True adds the <label> element after the checkbox.
Field Lists#
- mdit_py_plugins.field_list.fieldlist_plugin(md: MarkdownIt) None[source]#
Field lists are mappings from field names to field bodies, based on the reStructureText syntax.
:name *markup*: :name1: body content :name2: paragraph 1 paragraph 2 :name3: paragraph 1 paragraph 2A field name may consist of any characters except colons (“:”). Inline markup is parsed in field names.
The field name is followed by whitespace and the field body. The field body may be empty or contain multiple body elements.
Since the field marker may be quite long, the second and subsequent lines of the field body do not have to line up with the first line, but they must be indented relative to the field name marker, and they must line up with each other.
Heading Anchors#
- mdit_py_plugins.anchors.anchors_plugin(md: MarkdownIt, min_level: int = 1, max_level: int = 2, slug_func: Callable[[str], str] | None = None, permalink: bool = False, permalinkSymbol: str = '¶', permalinkBefore: bool = False, permalinkSpace: bool = True) None[source]#
Plugin for adding header anchors, based on markdown-it-anchor
# Title Stringrenders as:
<h1 id="title-string">Title String <a class="header-anchor" href="#title-string">¶</a></h1>
Explicit heading IDs (e.g.
{#id}fromattrs_block_plugin) are preserved, at any level, and generated IDs avoid collisions with them. Explicit IDs are not de-duplicated, and an empty explicit ID counts as no ID.- Parameters:
min_level – minimum header level to apply anchors
max_level – maximum header level to apply anchors
slug_func – function to convert title text to id slug.
permalink – Add a permalink next to the title
permalinkSymbol – the symbol to show
permalinkBefore – Add the permalink before the title, otherwise after
permalinkSpace – Add a space between the permalink and the title
Note, the default slug function aims to mimic the GitHub Markdown format, see:
Word Count#
- mdit_py_plugins.wordcount.wordcount_plugin(md: ~markdown_it.main.MarkdownIt, *, per_minute: int = 200, count_func: ~collections.abc.Callable[[str], int] = <function basic_count>, store_text: bool = False) None[source]#
Plugin for computing and storing the word count.
Stores in the
enve.g.:env["wordcount"] = { "words": 200 "minutes": 1, }
If “wordcount” is already in the env, it will update it.
- Parameters:
per_minute – Words per minute reading speed
store_text – store all text under a “text” key, as a list of strings
Containers#
- mdit_py_plugins.container.container_plugin(md: MarkdownIt, name: str, marker: str = ':', validate: Callable[[str, str], bool] | None = None, render: Callable[[...], str] | None = None) None[source]#
Plugin ported from markdown-it-container.
It is a plugin for creating block-level custom containers:
:::: name ::: name *markdown* ::: ::::- Parameters:
name – the name of the container to parse
marker – the marker character to use
validate – func(marker, param) -> bool, default matches against the name
render – render func
- mdit_py_plugins.admon.admon_plugin(md: MarkdownIt, render: Callable[[...], str] | None = None) None[source]#
Plugin to use python-markdown style admonitions.
!!! note *content*And mkdocs-style collapsible blocks.
???+ note *content*Note, this is ported from markdown-it-admon.
Attributes#
- mdit_py_plugins.attrs.attrs_plugin(md: MarkdownIt, *, after: Sequence[str] = ('image', 'code_inline', 'link_close', 'span_close'), spans: bool = False, span_after: str = 'link', allowed: Sequence[str] | None = None) None[source]#
Parse inline attributes that immediately follow certain inline elements:
{#id .a b=c}This syntax is inspired by Djot spans.
Inside the curly braces, the following syntax is possible:
.foo specifies foo as a class. Multiple classes may be given in this way; they will be combined.
#foo specifies foo as an identifier. An element may have only one identifier; if multiple identifiers are given, the last one is used.
- key=”value” or key=value specifies a key-value attribute.
Quotes are not needed when the value consists entirely of ASCII alphanumeric characters or _ or : or -. Backslash escapes may be used inside quoted values, to allow a
"character within the value. Note that the backslash is retained in the value:{k="a\"b"}giveskthe valuea\"b.
% begins a comment, which ends with the next %. If no further % occurs in the rest of the line (for a block attribute) or of the inline content (for an inline attribute), the comment instead ends at the next }, which also ends the attribute.
Multiple attribute blocks are merged.
- Parameters:
md – The MarkdownIt instance to modify.
after – The names of inline elements after which attributes may be specified. This plugin does not support attributes after emphasis, strikethrough or text elements, which all require post-parse processing.
spans – If True, also parse attributes after spans of text, encapsulated by []. Note Markdown link references take precedence over this syntax.
span_after – The name of an inline rule after which spans may be specified.
allowed – A list of allowed attribute names. If not
None, any attributes not in this list will be removed and placed in the token’s meta under the key “insecure_attrs”. IfNone(the default), event-handler attributes (any name starting withon, such asonclick) are still removed, as a baseline protection against script injection. Other attributes, includingstyle, are kept. Whateverallowedsays, the URL-valued attributeshref,src,action,formactionandxlink:hrefare removed whenmd.validateLinkrejects their value (for example ajavascript:URL), as for Markdown links and images. This is not a full sanitiser: to safely render untrusted input, pass an explicitallowedlist (e.g.("id", "class")).
- mdit_py_plugins.attrs.attrs_block_plugin(md: MarkdownIt, *, allowed: Sequence[str] | None = None) None[source]#
Parse block attributes.
Block attributes are attributes on a single line, with no other content. They attach the specified attributes to the block below them:
{.a #b c=1} A paragraph, that will be assigned the class ``a`` and the identifier ``b``.Attributes can be stacked, with classes accumulating and lower attributes overriding higher:
{#a .a c=1} {#b .b c=2} A paragraph, that will be assigned the class ``a b c``, and the identifier ``b``.This syntax is inspired by Djot block attributes.
- Parameters:
allowed – A list of allowed attribute names. If not
None, any attributes not in this list will be removed and placed in the token’s meta under the key “insecure_attrs”. IfNone(the default), event-handler attributes (any name starting withon, such asonclick) are still removed, as a baseline protection against script injection. Other attributes, includingstyle, are kept. Whateverallowedsays, the URL-valued attributeshref,src,action,formactionandxlink:hrefare removed whenmd.validateLinkrejects their value (for example ajavascript:URL), as for Markdown links and images. This is not a full sanitiser: to safely render untrusted input, pass an explicitallowedlist (e.g.("id", "class")).
Math#
- mdit_py_plugins.texmath.texmath_plugin(md: MarkdownIt, delimiters: str = 'dollars', macros: Any = None) None[source]#
Plugin ported from markdown-it-texmath.
It parses TeX math equations set inside opening and closing delimiters:
$\alpha = \frac{1}{2}$- Parameters:
delimiters – one of: brackets, dollars, gitlab, julia, kramdown
- mdit_py_plugins.amsmath.amsmath_plugin(md: MarkdownIt, *, renderer: Callable[[str], str] | None = None) None[source]#
Parses TeX math equations, without any surrounding delimiters, only for top-level amsmath environments:
\begin{gather*} a_1=b_1+c_1\\ a_2=b_2+c_2-d_2+e_2 \end{gather*}
- Parameters:
renderer – Function to render content, by default escapes HTML
- mdit_py_plugins.dollarmath.dollarmath_plugin(md: MarkdownIt, *, allow_labels: bool = True, allow_space: bool = True, allow_digits: bool = True, allow_blank_lines: bool = True, double_inline: bool = False, label_normalizer: Callable[[str], str] | None = None, renderer: Callable[[str, dict[str, Any]], str] | None = None, label_renderer: Callable[[str], str] | None = None) None[source]#
Plugin for parsing dollar enclosed math, e.g. inline:
$a=1$, block:$$b=2$$This is an improved version of
texmath; it is more performant, and handles\escaping properly and allows for more configuration.- Parameters:
allow_labels – Capture math blocks with label suffix, e.g.
$$a=1$$ (eq1)allow_space – Parse inline math when there is space after/before the opening/closing
$, e.g.$ a $allow_digits – Parse inline math when there is a digit before/after the opening/closing
$, e.g.1$or$2. This is useful when also using currency.allow_blank_lines – Allow blank lines inside
$$. Note that blank lines are not allowed in LaTeX, executablebooks/markdown-it-dollarmath, or the Github or StackExchange markdown dialects. Hoever, they have special semantics if used within Sphinx ..math admonitions, so are allowed for backwards-compatibility.double_inline – Search for double-dollar math within inline contexts
label_normalizer – Function to normalize the label, by default replaces whitespace with -
renderer – Function to render content: (str, {“display_mode”: bool}) -> str, by default escapes HTML. Its return value is placed inside the element as is, so a custom renderer is responsible for escaping it (the default renderer does).
label_renderer – Function to render labels, by default creates anchor
The plugin does not typeset the math. Each token becomes an HTML element holding the rendered content, and typesetting is left to a library such as MathJax or KaTeX:
math_inline($a$):<span class="math inline">, withdisplay_mode=Falsemath_inline_double($$a$$inside a paragraph, withdouble_inline):<div class="math inline">, withdisplay_mode=Truemath_block($$a$$on its own lines):<div class="math block">, withdisplay_mode=Truemath_block_label($$a$$ (eq1)):<div id="eq1" class="math block">, starting with the label anchor, withdisplay_mode=True
The tag says how to display the math (
divfor display,spanfor inline), and the class says where it was written (inlineinside a paragraph,blockon its own lines), as in executablebooks/markdown-it-dollarmath.
Rendering dollarmath output#
dollarmath_plugin does not typeset math: it wraps each piece of math in an HTML element, listed above.
The tag says how to display the math, and the class says where it was written.
So inline $$x$$ (with double_inline=True) becomes <div class="math inline">:
display math written inside a paragraph.
Pick the display mode from the tag (div or span), not from the class.
There are two common ways to typeset the output.
Add delimiters on the server, with renderer=.
The renderer function receives the math content and {"display_mode": bool},
and returns the HTML to put inside the element.
Wrapping the content in \(...\) or \[...\] lets MathJax (with its default configuration)
or KaTeX’s auto-render extension find it in the page:
from markdown_it import MarkdownIt
from markdown_it.common.utils import escapeHtml
from mdit_py_plugins.dollarmath import dollarmath_plugin
def render_tex(content: str, options: dict) -> str:
content = escapeHtml(content)
if options["display_mode"]:
return rf"\[{content}\]"
return rf"\({content}\)"
md = MarkdownIt().use(dollarmath_plugin, double_inline=True, renderer=render_tex)
html_string = md.render("Inline $a<b$ and $$x^2$$ in a paragraph.")
which gives:
<p>Inline <span class="math inline">\(a<b\)</span> and <div class="math inline">\[x^2\]</div> in a paragraph.</p>
A browser closes the <p> before the <div>, so in the page the text after inline $$...$$
falls outside the paragraph: allow for that when styling or selecting this output.
The returned string is inserted as is, so escape the content, as above, unless it comes from a trusted source (the default renderer escapes it for you). The same function can instead return fully typeset output, such as MathML from a converter library.
Typeset the elements in the browser.
Without a renderer, each element holds the escaped LaTeX source,
and a script can typeset the elements in place, for example with KaTeX:
for (const el of document.querySelectorAll("span.math, div.math")) {
// a labelled block starts with its permalink anchor: keep it out of the math
const label = el.querySelector(".mathlabel");
if (label) label.remove();
katex.render(el.textContent.trim(), el, {
displayMode: el.tagName === "DIV",
throwOnError: false,
});
if (label) el.prepend(label);
}
To change the label anchor, pass label_renderer=.
To change the tags or classes themselves, replace the render rule for a token type
with md.add_render_rule after loading the plugin.
Subscripts#
- mdit_py_plugins.subscript.sub_plugin(md: MarkdownIt) None[source]#
Markdown-it-py plugin to introduce <sub> markup using ~subscript~.
Ported from markdown-it/markdown-it-sub
Originally ported during implementation of hasgeek/funnel
Superscript#
- mdit_py_plugins.superscript.superscript_plugin(md: MarkdownIt) None[source]#
Superscript (
<sup>) tag plugin for Markdown-It-Py.This plugin is ported from markdown-it-sup. Markup is based on the Pandoc superscript extension.
Place superscripted text within caret
^characters. You must escape any spaces in the superscripted text. Note that you cannot use newline or tab characters, and that nested markup is not supported.Example usage:
>>> from markdown_it import MarkdownIt >>> from mdit_py_plugins.superscript import superscript_plugin >>> md = MarkdownIt().use(superscript_plugin) >>> md.render("1^st^") '<p>1<sup>st</sup></p>\n' >>> md.render("this^text\\ has\\ spaces^") '<p>this<sup>text has spaces</sup></p>\n'
Section References#
- mdit_py_plugins.section_ref.section_ref_plugin(md: MarkdownIt) None[source]#
Parse section-sign references such as
§1,§1.1and§2.3.4.The grammar is normative:
A reference is
§(U+00A7) immediately followed by one or more.-separated levels, with no spaces. Each level is 1 to 9 ASCII digits,§([0-9]{1,9}(\.[0-9]{1,9})*), and the match is maximal. Only ASCII0-9are digits: other Unicode digits, such as Arabic-Indic (U+0660 to U+0669) or fullwidth (U+FF10 to U+FF19) digits, do not form a reference, so a§followed by one stays literal text.A trailing
.is not part of the reference, so insee §1.the reference is§1and the.stays text.There is no reference, and the whole run stays literal text, if the character after the match is an ASCII letter (
§1a,§1.2b), or if any level has more than nine digits, counting leading zeros (§1234567890,§0000000001). No shorter prefix is taken, so§1.1234567890.2stays literal too. A non-ASCII letter after the match does not block it, so见§3章captures§3.References are recognised wherever inline text is parsed, and not inside code spans, autolinks, inline math or raw HTML tags (an attribute value is not inline text, but the text between two tags is, so
<span title="§1">§2</span>captures§2only).\§is not a CommonMark backslash escape, because§is not ASCII punctuation: in\§1the backslash stays visible and no reference is formed.\\§1is a literal backslash followed by the reference§1. To write a literal sign, use§or§, which never form a reference (§1renders as the text§1).
Each reference becomes a single
section_refleaf token (nesting=0,children=None,tag="",attrs={}), withmarkupset to"§", the text as written (e.g."§01.02") as itscontent, andmeta["numbers"]holding the integer value of each level as a list of ints ([1, 2]for§01.02; every value is at most 999,999,999), so that downstream renderers can resolve it to a heading target without re-parsing. The token shape is part of the public API from 0.7.0.The default rendering is
<span class="section-ref">§1.1</span>. Override it withmd.add_render_rule("section_ref", ...). markdown-it-py’srenderInlineAsText, which renders imagealttext, keeps onlytexttokens, sorendersalt="a b"(as it does for inline math). A renderer that wants the reference in the alt text should use thesection_reftoken’scontent.Added in version 0.7.0.
Requires markdown-it-py >= 4.1.0.
MyST plugins#
myst_blocks and myst_role plugins are also available, for utilisation by the MyST renderer
- mdit_py_plugins.myst_role.myst_role_plugin(md: MarkdownIt) None[source]#
Parse
{role-name}`content`
- mdit_py_plugins.myst_blocks.myst_block_plugin(md: MarkdownIt) None[source]#
Parse MyST targets (
(name)=), blockquotes (% comment) and block breaks (+++).
Write your own#
Use the mdit_py_plugins as a guide to write your own, following the markdown-it design principles.
There are many other plugins which could easily be ported from the JS versions (and hopefully will):
… and others