Skip to content

parsers

Class info

Re-exported classes

Class Module Description
CmarkgfmParser mkconvert.parsers.cmarkgfm cmarkgfm: bindings to cmark-gfm, the reference GFM implementation.
ComrakParser mkconvert.parsers.comrak Comrak: fast, CommonMark / GFM compliant, supports every common option.
Markdown2Parser mkconvert.parsers.markdown2 markdown2: pure-Python Markdown (not CommonMark compliant), many "extras".
MarkdownItPyParser mkconvert.parsers.markdown_it_py markdown-it-py + mdit-py-plugins: pure Python, CommonMark compliant, pluggable.
MarkdownItPyrsParser mkconvert.parsers.markdown_it_pyrs markdown-it-pyrs: Rust port of markdown-it. Deprecated, removed in mkconvert 3.0.
MarkdownOptions mkconvert.parsers.base Common Markdown -> HTML options, mapped onto every parser.
MarkdownParser mkconvert.parsers.base Base class for Markdown -> HTML parsers.
MarkoParser mkconvert.parsers.marko Marko: pure-Python CommonMark parser, extensible.
MistuneParser mkconvert.parsers.mistune Mistune: fast pure-Python parser (not fully CommonMark compliant).
PyromarkParser mkconvert.parsers.pyromark Pyromark: bindings to pulldown-cmark, very fast.
PythonMarkdownParser mkconvert.parsers.python_markdown Python-Markdown with pymdown-extensions (not CommonMark compliant).
Registry mkconvert._core Name -> backend class mapping, in order of preference.

🛈 DocStrings

Markdown -> HTML parsers.

Importing this package does not import any parser library: each parser imports its library when instantiated.

registry module-attribute

registry: Registry[MarkdownParser] = Registry('Markdown parser')

Parsers by name. Order is the preference when no parser is named.

CmarkgfmParser

Bases: MarkdownParser

cmarkgfm: bindings to cmark-gfm, the reference GFM implementation.

Not supported: heading_ids, alerts, math, definition_lists. With raw_html=False, raw HTML is replaced by <!-- raw HTML omitted -->.

Source code in src/mkconvert/parsers/cmarkgfm.py
class CmarkgfmParser(MarkdownParser):
    """cmarkgfm: bindings to cmark-gfm, the reference GFM implementation.

    Not supported: `heading_ids`, `alerts`, `math`, `definition_lists`.
    With `raw_html=False`, raw HTML is replaced by `<!-- raw HTML omitted -->`.
    """

    name = "cmarkgfm"
    requires = ("cmarkgfm",)
    extra = "cmarkgfm"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "hard_breaks",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        tagfilter: bool = False,
        github_pre_lang: bool = False,
        sourcepos: bool = False,
    ) -> None:
        """Create a cmarkgfm parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            tagfilter: GFM tag filter: escape `<script>`, `<iframe>`, ... in raw HTML.
            github_pre_lang: GitHub-style `<pre lang="...">` code blocks.
            sourcepos: Add `data-sourcepos` attributes.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        from cmarkgfm.cmark import Options as Flags

        o = self.options
        selected = {
            "table": o.tables,
            "strikethrough": o.strikethrough,
            "autolink": o.autolinks,
            "tasklist": o.task_lists,
            "tagfilter": tagfilter,
        }
        self._extensions = [ext for ext, enabled in selected.items() if enabled]
        flags = {
            Flags.CMARK_OPT_FOOTNOTES: o.footnotes,
            Flags.CMARK_OPT_HARDBREAKS: o.hard_breaks,
            Flags.CMARK_OPT_SMART: o.smart_punctuation,
            Flags.CMARK_OPT_UNSAFE: o.raw_html,
            Flags.CMARK_OPT_GITHUB_PRE_LANG: github_pre_lang,
            Flags.CMARK_OPT_SOURCEPOS: sourcepos,
        }
        self._flags = sum(flag for flag, enabled in flags.items() if enabled)

    def _render(self, text: str) -> str:
        from cmarkgfm.cmark import markdown_to_html_with_extensions

        with _LOCK:
            return markdown_to_html_with_extensions(
                text, options=self._flags, extensions=self._extensions
            )

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    tagfilter: bool = False,
    github_pre_lang: bool = False,
    sourcepos: bool = False,
) -> None

Create a cmarkgfm parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
tagfilter bool

GFM tag filter: escape <script>, <iframe>, ... in raw HTML.

False
github_pre_lang bool

GitHub-style <pre lang="..."> code blocks.

False
sourcepos bool

Add data-sourcepos attributes.

False
Source code in src/mkconvert/parsers/cmarkgfm.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    tagfilter: bool = False,
    github_pre_lang: bool = False,
    sourcepos: bool = False,
) -> None:
    """Create a cmarkgfm parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        tagfilter: GFM tag filter: escape `<script>`, `<iframe>`, ... in raw HTML.
        github_pre_lang: GitHub-style `<pre lang="...">` code blocks.
        sourcepos: Add `data-sourcepos` attributes.
    """
    super().__init__(options, on_unsupported=on_unsupported)
    from cmarkgfm.cmark import Options as Flags

    o = self.options
    selected = {
        "table": o.tables,
        "strikethrough": o.strikethrough,
        "autolink": o.autolinks,
        "tasklist": o.task_lists,
        "tagfilter": tagfilter,
    }
    self._extensions = [ext for ext, enabled in selected.items() if enabled]
    flags = {
        Flags.CMARK_OPT_FOOTNOTES: o.footnotes,
        Flags.CMARK_OPT_HARDBREAKS: o.hard_breaks,
        Flags.CMARK_OPT_SMART: o.smart_punctuation,
        Flags.CMARK_OPT_UNSAFE: o.raw_html,
        Flags.CMARK_OPT_GITHUB_PRE_LANG: github_pre_lang,
        Flags.CMARK_OPT_SOURCEPOS: sourcepos,
    }
    self._flags = sum(flag for flag, enabled in flags.items() if enabled)

ComrakParser

Bases: MarkdownParser

Comrak: fast, CommonMark / GFM compliant, supports every common option.

Source code in src/mkconvert/parsers/comrak.py
class ComrakParser(MarkdownParser):
    """Comrak: fast, CommonMark / GFM compliant, supports every common option."""

    name = "comrak"
    requires = ("comrak",)
    extra = "comrak"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "alerts",
        "math",
        "definition_lists",
        "hard_breaks",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        header_id_prefix: str = "",
        tagfilter: bool = False,
        superscript: bool = False,
        subscript: bool = False,
        underline: bool = False,
        spoiler: bool = False,
        greentext: bool = False,
        wikilinks: bool = False,
        multiline_block_quotes: bool = False,
        math_code: bool = False,
        relaxed_autolinks: bool = False,
        relaxed_tasklist_matching: bool = False,
        default_info_string: str | None = None,
        github_pre_lang: bool = False,
        full_info_string: bool = False,
        sourcepos: bool = False,
    ) -> None:
        """Create a comrak parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            header_id_prefix: Prefix for heading ids (with `heading_ids`).
            tagfilter: GFM tag filter: escape `<script>`, `<iframe>`, ... in raw HTML.
            superscript: `^sup^`.
            subscript: `~sub~`.
            underline: `__underline__`.
            spoiler: `||spoiler||`.
            greentext: `> greentext` lines without blockquote nesting.
            wikilinks: `[[url|title]]` wikilinks.
            multiline_block_quotes: `>>>` fenced block quotes.
            math_code: `` $`math`$ `` math syntax.
            relaxed_autolinks: Looser autolink detection (with `autolinks`).
            relaxed_tasklist_matching: Any character as task list checkmark.
            default_info_string: Language for fenced code blocks without one.
            github_pre_lang: GitHub-style `<pre lang="...">` code blocks.
            full_info_string: Keep the full info string as `data-meta`.
            sourcepos: Add `data-sourcepos` attributes.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import comrak

        o = self.options
        ext = comrak.ExtensionOptions()
        ext.table = o.tables
        ext.strikethrough = o.strikethrough
        ext.autolink = o.autolinks
        ext.tasklist = o.task_lists
        ext.footnotes = o.footnotes
        ext.header_id_prefix = header_id_prefix if o.heading_ids else None
        ext.alerts = o.alerts
        ext.math_dollars = o.math
        ext.description_lists = o.definition_lists
        ext.tagfilter = tagfilter
        ext.superscript = superscript
        ext.subscript = subscript
        ext.underline = underline
        ext.spoiler = spoiler
        ext.greentext = greentext
        ext.wikilinks_title_after_pipe = wikilinks
        ext.multiline_block_quotes = multiline_block_quotes
        ext.math_code = math_code
        parse = comrak.ParseOptions()
        parse.smart = o.smart_punctuation
        parse.relaxed_autolinks = relaxed_autolinks
        parse.relaxed_tasklist_matching = relaxed_tasklist_matching
        parse.default_info_string = default_info_string
        render = comrak.RenderOptions()
        render.hardbreaks = o.hard_breaks
        render.unsafe_ = o.raw_html
        render.escape = not o.raw_html
        render.github_pre_lang = github_pre_lang
        render.full_info_string = full_info_string
        render.sourcepos = sourcepos
        self._options = (ext, parse, render)

    def _render(self, text: str) -> str:
        import comrak

        ext, parse, render = self._options
        return comrak.render_markdown(
            text, extension_options=ext, parse_options=parse, render_options=render
        )

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    header_id_prefix: str = "",
    tagfilter: bool = False,
    superscript: bool = False,
    subscript: bool = False,
    underline: bool = False,
    spoiler: bool = False,
    greentext: bool = False,
    wikilinks: bool = False,
    multiline_block_quotes: bool = False,
    math_code: bool = False,
    relaxed_autolinks: bool = False,
    relaxed_tasklist_matching: bool = False,
    default_info_string: str | None = None,
    github_pre_lang: bool = False,
    full_info_string: bool = False,
    sourcepos: bool = False,
) -> None

Create a comrak parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
header_id_prefix str

Prefix for heading ids (with heading_ids).

''
tagfilter bool

GFM tag filter: escape <script>, <iframe>, ... in raw HTML.

False
superscript bool

^sup^.

False
subscript bool

~sub~.

False
underline bool

__underline__.

False
spoiler bool

||spoiler||.

False
greentext bool

> greentext lines without blockquote nesting.

False
wikilinks bool

[[url|title]] wikilinks.

False
multiline_block_quotes bool

>>> fenced block quotes.

False
math_code bool

$`math`$ math syntax.

False
relaxed_autolinks bool

Looser autolink detection (with autolinks).

False
relaxed_tasklist_matching bool

Any character as task list checkmark.

False
default_info_string str | None

Language for fenced code blocks without one.

None
github_pre_lang bool

GitHub-style <pre lang="..."> code blocks.

False
full_info_string bool

Keep the full info string as data-meta.

False
sourcepos bool

Add data-sourcepos attributes.

False
Source code in src/mkconvert/parsers/comrak.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    header_id_prefix: str = "",
    tagfilter: bool = False,
    superscript: bool = False,
    subscript: bool = False,
    underline: bool = False,
    spoiler: bool = False,
    greentext: bool = False,
    wikilinks: bool = False,
    multiline_block_quotes: bool = False,
    math_code: bool = False,
    relaxed_autolinks: bool = False,
    relaxed_tasklist_matching: bool = False,
    default_info_string: str | None = None,
    github_pre_lang: bool = False,
    full_info_string: bool = False,
    sourcepos: bool = False,
) -> None:
    """Create a comrak parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        header_id_prefix: Prefix for heading ids (with `heading_ids`).
        tagfilter: GFM tag filter: escape `<script>`, `<iframe>`, ... in raw HTML.
        superscript: `^sup^`.
        subscript: `~sub~`.
        underline: `__underline__`.
        spoiler: `||spoiler||`.
        greentext: `> greentext` lines without blockquote nesting.
        wikilinks: `[[url|title]]` wikilinks.
        multiline_block_quotes: `>>>` fenced block quotes.
        math_code: `` $`math`$ `` math syntax.
        relaxed_autolinks: Looser autolink detection (with `autolinks`).
        relaxed_tasklist_matching: Any character as task list checkmark.
        default_info_string: Language for fenced code blocks without one.
        github_pre_lang: GitHub-style `<pre lang="...">` code blocks.
        full_info_string: Keep the full info string as `data-meta`.
        sourcepos: Add `data-sourcepos` attributes.
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import comrak

    o = self.options
    ext = comrak.ExtensionOptions()
    ext.table = o.tables
    ext.strikethrough = o.strikethrough
    ext.autolink = o.autolinks
    ext.tasklist = o.task_lists
    ext.footnotes = o.footnotes
    ext.header_id_prefix = header_id_prefix if o.heading_ids else None
    ext.alerts = o.alerts
    ext.math_dollars = o.math
    ext.description_lists = o.definition_lists
    ext.tagfilter = tagfilter
    ext.superscript = superscript
    ext.subscript = subscript
    ext.underline = underline
    ext.spoiler = spoiler
    ext.greentext = greentext
    ext.wikilinks_title_after_pipe = wikilinks
    ext.multiline_block_quotes = multiline_block_quotes
    ext.math_code = math_code
    parse = comrak.ParseOptions()
    parse.smart = o.smart_punctuation
    parse.relaxed_autolinks = relaxed_autolinks
    parse.relaxed_tasklist_matching = relaxed_tasklist_matching
    parse.default_info_string = default_info_string
    render = comrak.RenderOptions()
    render.hardbreaks = o.hard_breaks
    render.unsafe_ = o.raw_html
    render.escape = not o.raw_html
    render.github_pre_lang = github_pre_lang
    render.full_info_string = full_info_string
    render.sourcepos = sourcepos
    self._options = (ext, parse, render)

Markdown2Parser

Bases: MarkdownParser

markdown2: pure-Python Markdown (not CommonMark compliant), many "extras".

Not supported: autolinks, math, definition_lists.

Source code in src/mkconvert/parsers/markdown2.py
class Markdown2Parser(MarkdownParser):
    """markdown2: pure-Python Markdown (not CommonMark compliant), many "extras".

    Not supported: `autolinks`, `math`, `definition_lists`.
    """

    name = "markdown2"
    requires = ("markdown2",)
    extra = "markdown2"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "task_lists",
        "footnotes",
        "heading_ids",
        "alerts",
        "hard_breaks",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        extras: Mapping[str, Any] | None = None,
        highlight: bool = False,
        html4tags: bool = False,
    ) -> None:
        """Create a markdown2 parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            extras: Further markdown2 extras with their settings (`None` for defaults),
                e.g. `{"cuddled-lists": None, "toc": {"depth": 3}}`.
            highlight: Highlight fenced code blocks with Pygments (if installed).
            html4tags: HTML4-style tags (`<br>` instead of `<br />`).
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import markdown2

        o = self.options
        selected: dict[str, tuple[bool, Any]] = {
            "fenced-code-blocks": (True, None),
            "highlightjs-lang": (not highlight, None),
            "tables": (o.tables, None),
            "strike": (o.strikethrough, None),
            "task_list": (o.task_lists, None),
            "footnotes": (o.footnotes, None),
            "header-ids": (o.heading_ids, None),
            "alerts": (o.alerts, None),
            "breaks": (o.hard_breaks, {"on_newline": True}),
            "smarty-pants": (o.smart_punctuation, None),
        }
        all_extras = {name: value for name, (enabled, value) in selected.items() if enabled}
        all_extras.update(extras or {})
        self._md = markdown2.Markdown(
            extras=all_extras,
            safe_mode=None if o.raw_html else "escape",
            html4tags=html4tags,
        )
        self._lock = threading.Lock()

    def _render(self, text: str) -> str:
        with self._lock:
            return str(self._md.convert(text))

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extras: Mapping[str, Any] | None = None,
    highlight: bool = False,
    html4tags: bool = False,
) -> None

Create a markdown2 parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
extras Mapping[str, Any] | None

Further markdown2 extras with their settings (None for defaults), e.g. {"cuddled-lists": None, "toc": {"depth": 3}}.

None
highlight bool

Highlight fenced code blocks with Pygments (if installed).

False
html4tags bool

HTML4-style tags (<br> instead of <br />).

False
Source code in src/mkconvert/parsers/markdown2.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extras: Mapping[str, Any] | None = None,
    highlight: bool = False,
    html4tags: bool = False,
) -> None:
    """Create a markdown2 parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        extras: Further markdown2 extras with their settings (`None` for defaults),
            e.g. `{"cuddled-lists": None, "toc": {"depth": 3}}`.
        highlight: Highlight fenced code blocks with Pygments (if installed).
        html4tags: HTML4-style tags (`<br>` instead of `<br />`).
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import markdown2

    o = self.options
    selected: dict[str, tuple[bool, Any]] = {
        "fenced-code-blocks": (True, None),
        "highlightjs-lang": (not highlight, None),
        "tables": (o.tables, None),
        "strike": (o.strikethrough, None),
        "task_list": (o.task_lists, None),
        "footnotes": (o.footnotes, None),
        "header-ids": (o.heading_ids, None),
        "alerts": (o.alerts, None),
        "breaks": (o.hard_breaks, {"on_newline": True}),
        "smarty-pants": (o.smart_punctuation, None),
    }
    all_extras = {name: value for name, (enabled, value) in selected.items() if enabled}
    all_extras.update(extras or {})
    self._md = markdown2.Markdown(
        extras=all_extras,
        safe_mode=None if o.raw_html else "escape",
        html4tags=html4tags,
    )
    self._lock = threading.Lock()

MarkdownItPyParser

Bases: MarkdownParser

markdown-it-py + mdit-py-plugins: pure Python, CommonMark compliant, pluggable.

Supports every common option. Further syntax (MkDocs-style !!! admonitions, MyST directives, attributes, ...) comes from mdit-py-plugins via plugins.

Source code in src/mkconvert/parsers/markdown_it_py.py
class MarkdownItPyParser(MarkdownParser):
    """markdown-it-py + mdit-py-plugins: pure Python, CommonMark compliant, pluggable.

    Supports every common option. Further syntax (MkDocs-style `!!!` admonitions, MyST
    directives, attributes, ...) comes from mdit-py-plugins via `plugins`.
    """

    name = "markdown-it-py"
    requires = ("markdown_it", "mdit_py_plugins")
    extra = "markdown-it-py"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "alerts",
        "math",
        "definition_lists",
        "hard_breaks",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        plugins: Sequence[Callable[..., None] | tuple[Callable[..., None], dict[str, Any]]] = (),
        xhtml: bool = True,
        heading_levels: tuple[int, int] = (1, 6),
    ) -> None:
        """Create a markdown-it-py parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            plugins: Further plugins, each a plugin function or a `(function, kwargs)`
                pair, e.g. `[mdit_py_plugins.admon.admon_plugin]`.
            xhtml: Self-closing tags with a trailing slash (`<br />`).
            heading_levels: Lowest and highest heading level that get ids
                (with `heading_ids`).
        """
        super().__init__(options, on_unsupported=on_unsupported)
        from markdown_it import MarkdownIt

        o = self.options
        md = MarkdownIt(
            "commonmark",
            {
                "html": o.raw_html,
                "xhtmlOut": xhtml,
                "breaks": o.hard_breaks,
                "typographer": o.smart_punctuation,
                "tasklists": o.task_lists,
                "alerts": o.alerts,
            },
        )
        if not o.raw_html:
            md.disable(["html_block", "html_inline"])
        if o.tables:
            md.enable("table")
        if o.strikethrough:
            md.enable("strikethrough")
        if o.smart_punctuation:
            md.enable(["replacements", "smartquotes"])
        if o.autolinks:
            from mdit_py_plugins.gfm_autolink import gfm_autolink_plugin

            md.use(gfm_autolink_plugin)
        if o.footnotes:
            from mdit_py_plugins.footnote import footnote_plugin

            md.use(footnote_plugin, inline=False)
        if o.heading_ids:
            from mdit_py_plugins.anchors import anchors_plugin

            md.use(anchors_plugin, min_level=heading_levels[0], max_level=heading_levels[1])
        if o.math:
            from mdit_py_plugins.dollarmath import dollarmath_plugin

            md.use(dollarmath_plugin)
        if o.definition_lists:
            from mdit_py_plugins.deflist import deflist_plugin

            md.use(deflist_plugin)
        for plugin in plugins:
            func, kwargs = plugin if isinstance(plugin, tuple) else (plugin, {})
            md.use(func, **kwargs)
        self._md: MarkdownIt = md

    def _render(self, text: str) -> str:
        return self._md.render(text)

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    plugins: Sequence[Callable[..., None] | tuple[Callable[..., None], dict[str, Any]]] = (),
    xhtml: bool = True,
    heading_levels: tuple[int, int] = (1, 6),
) -> None

Create a markdown-it-py parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
plugins Sequence[Callable[..., None] | tuple[Callable[..., None], dict[str, Any]]]

Further plugins, each a plugin function or a (function, kwargs) pair, e.g. [mdit_py_plugins.admon.admon_plugin].

()
xhtml bool

Self-closing tags with a trailing slash (<br />).

True
heading_levels tuple[int, int]

Lowest and highest heading level that get ids (with heading_ids).

(1, 6)
Source code in src/mkconvert/parsers/markdown_it_py.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    plugins: Sequence[Callable[..., None] | tuple[Callable[..., None], dict[str, Any]]] = (),
    xhtml: bool = True,
    heading_levels: tuple[int, int] = (1, 6),
) -> None:
    """Create a markdown-it-py parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        plugins: Further plugins, each a plugin function or a `(function, kwargs)`
            pair, e.g. `[mdit_py_plugins.admon.admon_plugin]`.
        xhtml: Self-closing tags with a trailing slash (`<br />`).
        heading_levels: Lowest and highest heading level that get ids
            (with `heading_ids`).
    """
    super().__init__(options, on_unsupported=on_unsupported)
    from markdown_it import MarkdownIt

    o = self.options
    md = MarkdownIt(
        "commonmark",
        {
            "html": o.raw_html,
            "xhtmlOut": xhtml,
            "breaks": o.hard_breaks,
            "typographer": o.smart_punctuation,
            "tasklists": o.task_lists,
            "alerts": o.alerts,
        },
    )
    if not o.raw_html:
        md.disable(["html_block", "html_inline"])
    if o.tables:
        md.enable("table")
    if o.strikethrough:
        md.enable("strikethrough")
    if o.smart_punctuation:
        md.enable(["replacements", "smartquotes"])
    if o.autolinks:
        from mdit_py_plugins.gfm_autolink import gfm_autolink_plugin

        md.use(gfm_autolink_plugin)
    if o.footnotes:
        from mdit_py_plugins.footnote import footnote_plugin

        md.use(footnote_plugin, inline=False)
    if o.heading_ids:
        from mdit_py_plugins.anchors import anchors_plugin

        md.use(anchors_plugin, min_level=heading_levels[0], max_level=heading_levels[1])
    if o.math:
        from mdit_py_plugins.dollarmath import dollarmath_plugin

        md.use(dollarmath_plugin)
    if o.definition_lists:
        from mdit_py_plugins.deflist import deflist_plugin

        md.use(deflist_plugin)
    for plugin in plugins:
        func, kwargs = plugin if isinstance(plugin, tuple) else (plugin, {})
        md.use(func, **kwargs)
    self._md: MarkdownIt = md

MarkdownItPyrsParser

Bases: MarkdownParser

markdown-it-pyrs: Rust port of markdown-it. Deprecated, removed in mkconvert 3.0.

Use comrak / pyromark (Rust) or markdown-it-py instead. Not supported: alerts, math, hard_breaks.

Source code in src/mkconvert/parsers/markdown_it_pyrs.py
class MarkdownItPyrsParser(MarkdownParser):
    """markdown-it-pyrs: Rust port of markdown-it. Deprecated, removed in mkconvert 3.0.

    Use `comrak` / `pyromark` (Rust) or `markdown-it-py` instead.
    Not supported: `alerts`, `math`, `hard_breaks`.
    """

    name = "markdown-it-pyrs"
    requires = ("markdown_it_pyrs",)
    extra = "markdown_it_pyrs"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "definition_lists",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        xhtml: bool = True,
        sourcepos: bool = False,
        plugins: list[_PLUGIN_NAME] | None = None,
    ) -> None:
        """Create a markdown-it-pyrs parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            xhtml: Self-closing tags with a trailing slash (`<br />`).
            sourcepos: Add `data-sourcepos` attributes.
            plugins: Further plugins / rules to enable.
        """
        warnings.warn(DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=2)
        super().__init__(options, on_unsupported=on_unsupported)
        from markdown_it_pyrs import MarkdownIt

        o = self.options
        rules = list(_COMMONMARK_RULES)
        if o.raw_html:
            rules += ["html_block", "html_inline"]
        selected: dict[_PLUGIN_NAME, bool] = {
            "table": o.tables,
            "strikethrough": o.strikethrough,
            "autolink_ext": o.autolinks,
            "tasklist": o.task_lists,
            "footnote": o.footnotes,
            "heading_anchors": o.heading_ids,
            "deflist": o.definition_lists,
            "smartquotes": o.smart_punctuation,
            "replacements": o.smart_punctuation,
            "sourcepos": sourcepos,
        }
        rules += [rule for rule, enabled in selected.items() if enabled]
        rules += plugins or []
        self._md = MarkdownIt("zero").enable_many(rules)
        self._xhtml = xhtml

    def _render(self, text: str) -> str:
        return self._md.render(text, xhtml=self._xhtml)

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    xhtml: bool = True,
    sourcepos: bool = False,
    plugins: list[_PLUGIN_NAME] | None = None,
) -> None

Create a markdown-it-pyrs parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
xhtml bool

Self-closing tags with a trailing slash (<br />).

True
sourcepos bool

Add data-sourcepos attributes.

False
plugins list[_PLUGIN_NAME] | None

Further plugins / rules to enable.

None
Source code in src/mkconvert/parsers/markdown_it_pyrs.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    xhtml: bool = True,
    sourcepos: bool = False,
    plugins: list[_PLUGIN_NAME] | None = None,
) -> None:
    """Create a markdown-it-pyrs parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        xhtml: Self-closing tags with a trailing slash (`<br />`).
        sourcepos: Add `data-sourcepos` attributes.
        plugins: Further plugins / rules to enable.
    """
    warnings.warn(DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=2)
    super().__init__(options, on_unsupported=on_unsupported)
    from markdown_it_pyrs import MarkdownIt

    o = self.options
    rules = list(_COMMONMARK_RULES)
    if o.raw_html:
        rules += ["html_block", "html_inline"]
    selected: dict[_PLUGIN_NAME, bool] = {
        "table": o.tables,
        "strikethrough": o.strikethrough,
        "autolink_ext": o.autolinks,
        "tasklist": o.task_lists,
        "footnote": o.footnotes,
        "heading_anchors": o.heading_ids,
        "deflist": o.definition_lists,
        "smartquotes": o.smart_punctuation,
        "replacements": o.smart_punctuation,
        "sourcepos": sourcepos,
    }
    rules += [rule for rule, enabled in selected.items() if enabled]
    rules += plugins or []
    self._md = MarkdownIt("zero").enable_many(rules)
    self._xhtml = xhtml

MarkdownOptions

Bases: Options

Common Markdown -> HTML options, mapped onto every parser.

The defaults are plain CommonMark (every extension off, raw HTML passed through), except that a leading front matter block is dropped. Check MarkdownParser.supported_options for what a parser can enable.

Source code in src/mkconvert/parsers/base.py
class MarkdownOptions(Options):
    """Common Markdown -> HTML options, mapped onto every parser.

    The defaults are plain CommonMark (every extension off, raw HTML passed through),
    except that a leading front matter block is dropped.
    Check `MarkdownParser.supported_options` for what a parser can enable.
    """

    tables: bool = False
    """GFM pipe tables."""
    strikethrough: bool = False
    """`~~text~~` -> `<del>` (or `<s>`)."""
    autolinks: bool = False
    """Link bare URLs (`https://...`, `www.`) like GFM's autolink extension."""
    task_lists: bool = False
    """`- [x] item` -> list items with checkboxes."""
    footnotes: bool = False
    """`text[^1]` references and `[^1]: ...` definitions."""
    heading_ids: bool = False
    """Add slug `id` attributes to headings."""
    alerts: bool = False
    """GitHub alerts: `> [!NOTE]`, `> [!WARNING]`, ..."""
    math: bool = False
    """`$inline$` and `$$display$$` math, rendered as markup for MathJax / KaTeX."""
    definition_lists: bool = False
    """`Term` followed by `: definition` lines -> `<dl>`."""
    hard_breaks: bool = False
    """Render every newline inside a paragraph as `<br>`."""
    smart_punctuation: bool = False
    """Typographic quotes, dashes and ellipses."""
    raw_html: bool = True
    """Pass raw HTML through. `False` escapes or omits it (parser-dependent).

    This is not a sanitizer: use `mkconvert.sanitize` for untrusted input.
    """
    front_matter: bool = True
    """Drop a leading `---`-delimited front matter block instead of rendering it.

    On by default: almost every Markdown file with a leading `---` block means front
    matter, not a horizontal rule followed by a heading.
    """

    @classmethod
    def gfm(cls, **changes: Any) -> Self:
        """GitHub Flavored Markdown: tables, strikethrough, autolinks and task lists.

        Args:
            changes: Further options to set, e.g. `footnotes=True`.
        """
        values: dict[str, Any] = dict(
            tables=True, strikethrough=True, autolinks=True, task_lists=True
        )
        return cls(**(values | changes))

alerts class-attribute instance-attribute

alerts: bool = False

GitHub alerts: > [!NOTE], > [!WARNING], ...

autolinks: bool = False

Link bare URLs (https://..., www.) like GFM's autolink extension.

definition_lists class-attribute instance-attribute

definition_lists: bool = False

Term followed by : definition lines -> <dl>.

footnotes class-attribute instance-attribute

footnotes: bool = False

text[^1] references and [^1]: ... definitions.

front_matter class-attribute instance-attribute

front_matter: bool = True

Drop a leading ----delimited front matter block instead of rendering it.

On by default: almost every Markdown file with a leading --- block means front matter, not a horizontal rule followed by a heading.

hard_breaks class-attribute instance-attribute

hard_breaks: bool = False

Render every newline inside a paragraph as <br>.

heading_ids class-attribute instance-attribute

heading_ids: bool = False

Add slug id attributes to headings.

math class-attribute instance-attribute

math: bool = False

$inline$ and $$display$$ math, rendered as markup for MathJax / KaTeX.

raw_html class-attribute instance-attribute

raw_html: bool = True

Pass raw HTML through. False escapes or omits it (parser-dependent).

This is not a sanitizer: use mkconvert.sanitize for untrusted input.

smart_punctuation class-attribute instance-attribute

smart_punctuation: bool = False

Typographic quotes, dashes and ellipses.

strikethrough class-attribute instance-attribute

strikethrough: bool = False

~~text~~ -> <del> (or <s>).

tables class-attribute instance-attribute

tables: bool = False

GFM pipe tables.

task_lists class-attribute instance-attribute

task_lists: bool = False

- [x] item -> list items with checkboxes.

gfm classmethod

gfm(**changes: Any) -> Self

GitHub Flavored Markdown: tables, strikethrough, autolinks and task lists.

Parameters:

Name Type Description Default
changes Any

Further options to set, e.g. footnotes=True.

{}
Source code in src/mkconvert/parsers/base.py
@classmethod
def gfm(cls, **changes: Any) -> Self:
    """GitHub Flavored Markdown: tables, strikethrough, autolinks and task lists.

    Args:
        changes: Further options to set, e.g. `footnotes=True`.
    """
    values: dict[str, Any] = dict(
        tables=True, strikethrough=True, autolinks=True, task_lists=True
    )
    return cls(**(values | changes))

MarkdownParser

Bases: Backend[MarkdownOptions]

Base class for Markdown -> HTML parsers.

Subclasses take MarkdownOptions plus their own keyword-only options, map them onto the wrapped library once in __init__ and implement _render.

Source code in src/mkconvert/parsers/base.py
class MarkdownParser(Backend[MarkdownOptions]):
    """Base class for Markdown -> HTML parsers.

    Subclasses take `MarkdownOptions` plus their own keyword-only options, map them onto
    the wrapped library once in `__init__` and implement `_render`.
    """

    options_class: ClassVar[type[MarkdownOptions]] = MarkdownOptions

    def convert(self, text: str) -> str:
        """Convert Markdown `text` to HTML."""
        if self.options.front_matter:
            _, text = split_front_matter(text)
        return self._render(text)

    @abstractmethod
    def _render(self, text: str) -> str:
        """Render Markdown to HTML with the wrapped library."""

convert

convert(text: str) -> str

Convert Markdown text to HTML.

Source code in src/mkconvert/parsers/base.py
def convert(self, text: str) -> str:
    """Convert Markdown `text` to HTML."""
    if self.options.front_matter:
        _, text = split_front_matter(text)
    return self._render(text)

MarkoParser

Bases: MarkdownParser

Marko: pure-Python CommonMark parser, extensible.

Not supported: math, definition_lists, smart_punctuation.

Source code in src/mkconvert/parsers/marko.py
class MarkoParser(MarkdownParser):
    """Marko: pure-Python CommonMark parser, extensible.

    Not supported: `math`, `definition_lists`, `smart_punctuation`.
    """

    name = "marko"
    requires = ("marko",)
    extra = "marko"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "alerts",
        "hard_breaks",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        extensions: Sequence[str | MarkoExtension] = (),
    ) -> None:
        """Create a Marko parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            extensions: Further Marko extensions, e.g. `"codehilite"` or `"pangu"`.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import marko
        from marko.ext.gfm import elements as gfm, renderer as gfm_renderer
        from marko.helpers import MarkoExtension

        o = self.options
        selected = {
            (gfm.Table, gfm.TableRow, gfm.TableCell): o.tables,
            (gfm.Strikethrough,): o.strikethrough,
            (gfm.Url,): o.autolinks,
            (gfm.Paragraph,): o.task_lists,
            (gfm.Alert,): o.alerts,
        }
        elements: list[type[Element]] = [
            e for group, enabled in selected.items() if enabled for e in group
        ]
        exts: list[str | MarkoExtension] = []
        if elements:
            exts.append(
                MarkoExtension(elements=elements, renderer_mixins=[gfm_renderer.GFMRendererMixin])
            )
        if o.footnotes:
            exts.append("footnote")
        if o.heading_ids:
            exts.append("toc")
        mixins: list[type] = [
            mixin
            for mixin, enabled in [
                (_EscapeHtmlMixin, not o.raw_html),
                (_HardBreaksMixin, o.hard_breaks),
            ]
            if enabled
        ]
        if mixins:
            exts.append(MarkoExtension(renderer_mixins=mixins))
        exts.extend(extensions)
        self._md = marko.Markdown(extensions=exts)
        self._lock = threading.Lock()

    def _render(self, text: str) -> str:
        with self._lock:
            return self._md.convert(text)

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extensions: Sequence[str | MarkoExtension] = (),
) -> None

Create a Marko parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
extensions Sequence[str | MarkoExtension]

Further Marko extensions, e.g. "codehilite" or "pangu".

()
Source code in src/mkconvert/parsers/marko.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extensions: Sequence[str | MarkoExtension] = (),
) -> None:
    """Create a Marko parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        extensions: Further Marko extensions, e.g. `"codehilite"` or `"pangu"`.
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import marko
    from marko.ext.gfm import elements as gfm, renderer as gfm_renderer
    from marko.helpers import MarkoExtension

    o = self.options
    selected = {
        (gfm.Table, gfm.TableRow, gfm.TableCell): o.tables,
        (gfm.Strikethrough,): o.strikethrough,
        (gfm.Url,): o.autolinks,
        (gfm.Paragraph,): o.task_lists,
        (gfm.Alert,): o.alerts,
    }
    elements: list[type[Element]] = [
        e for group, enabled in selected.items() if enabled for e in group
    ]
    exts: list[str | MarkoExtension] = []
    if elements:
        exts.append(
            MarkoExtension(elements=elements, renderer_mixins=[gfm_renderer.GFMRendererMixin])
        )
    if o.footnotes:
        exts.append("footnote")
    if o.heading_ids:
        exts.append("toc")
    mixins: list[type] = [
        mixin
        for mixin, enabled in [
            (_EscapeHtmlMixin, not o.raw_html),
            (_HardBreaksMixin, o.hard_breaks),
        ]
        if enabled
    ]
    if mixins:
        exts.append(MarkoExtension(renderer_mixins=mixins))
    exts.extend(extensions)
    self._md = marko.Markdown(extensions=exts)
    self._lock = threading.Lock()

MistuneParser

Bases: MarkdownParser

Mistune: fast pure-Python parser (not fully CommonMark compliant).

Not supported: alerts, smart_punctuation. autolinks links bare https:// URLs only, not www. ones.

Source code in src/mkconvert/parsers/mistune.py
class MistuneParser(MarkdownParser):
    """Mistune: fast pure-Python parser (not fully CommonMark compliant).

    Not supported: `alerts`, `smart_punctuation`. `autolinks` links bare `https://`
    URLs only, not `www.` ones.
    """

    name = "mistune"
    requires = ("mistune",)
    extra = "mistune"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "math",
        "definition_lists",
        "hard_breaks",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        plugins: Sequence[str | Callable[..., None]] = (),
    ) -> None:
        """Create a mistune parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            plugins: Further mistune plugins: names (e.g. `"abbr"`, `"mark"`,
                `"superscript"`) or plugin objects (e.g. a `mistune.directives.FencedDirective`
                for MyST-style admonitions).
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import mistune
        from mistune.toc import add_toc_hook

        o = self.options
        selected = {
            "table": o.tables,
            "strikethrough": o.strikethrough,
            "url": o.autolinks,
            "task_lists": o.task_lists,
            "footnotes": o.footnotes,
            "math": o.math,
            "def_list": o.definition_lists,
        }
        names: list[str | Callable[..., None]] = [n for n, enabled in selected.items() if enabled]
        names += [p for p in plugins if p not in names]
        self._md = mistune.create_markdown(
            escape=not o.raw_html,
            hard_wrap=o.hard_breaks,
            plugins=names,  # type: ignore[arg-type]
        )
        if o.heading_ids:
            add_toc_hook(self._md, max_level=6, heading_id=_slugify)

    def _render(self, text: str) -> str:
        return str(self._md(text))

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    plugins: Sequence[str | Callable[..., None]] = (),
) -> None

Create a mistune parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
plugins Sequence[str | Callable[..., None]]

Further mistune plugins: names (e.g. "abbr", "mark", "superscript") or plugin objects (e.g. a mistune.directives.FencedDirective for MyST-style admonitions).

()
Source code in src/mkconvert/parsers/mistune.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    plugins: Sequence[str | Callable[..., None]] = (),
) -> None:
    """Create a mistune parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        plugins: Further mistune plugins: names (e.g. `"abbr"`, `"mark"`,
            `"superscript"`) or plugin objects (e.g. a `mistune.directives.FencedDirective`
            for MyST-style admonitions).
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import mistune
    from mistune.toc import add_toc_hook

    o = self.options
    selected = {
        "table": o.tables,
        "strikethrough": o.strikethrough,
        "url": o.autolinks,
        "task_lists": o.task_lists,
        "footnotes": o.footnotes,
        "math": o.math,
        "def_list": o.definition_lists,
    }
    names: list[str | Callable[..., None]] = [n for n, enabled in selected.items() if enabled]
    names += [p for p in plugins if p not in names]
    self._md = mistune.create_markdown(
        escape=not o.raw_html,
        hard_wrap=o.hard_breaks,
        plugins=names,  # type: ignore[arg-type]
    )
    if o.heading_ids:
        add_toc_hook(self._md, max_level=6, heading_id=_slugify)

PyromarkParser

Bases: MarkdownParser

Pyromark: bindings to pulldown-cmark, very fast.

Not supported: autolinks, heading_ids (only explicit # Title {#id} via heading_attributes), hard_breaks and raw_html=False.

Source code in src/mkconvert/parsers/pyromark.py
class PyromarkParser(MarkdownParser):
    """Pyromark: bindings to pulldown-cmark, very fast.

    Not supported: `autolinks`, `heading_ids` (only explicit `# Title {#id}` via
    `heading_attributes`), `hard_breaks` and `raw_html=False`.
    """

    name = "pyromark"
    requires = ("pyromark",)
    extra = "pyromark"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "task_lists",
        "footnotes",
        "alerts",
        "math",
        "definition_lists",
        "smart_punctuation",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        heading_attributes: bool = False,
        superscript: bool = False,
        subscript: bool = False,
        wikilinks: bool = False,
        old_footnotes: bool = False,
        highlight: pyromark.Theme | None = None,
    ) -> None:
        """Create a pyromark parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            heading_attributes: `# Heading {#id .class}` attributes.
            superscript: `^sup^`.
            subscript: `~sub~`.
            wikilinks: `[[wikilinks]]`.
            old_footnotes: Footnotes with the older, looser pulldown-cmark syntax.
            highlight: Syntax-highlight code blocks with this theme.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import pyromark

        flags = pyromark.Options
        o = self.options
        selected = {
            flags.ENABLE_TABLES: o.tables,
            flags.ENABLE_STRIKETHROUGH: o.strikethrough,
            flags.ENABLE_TASKLISTS: o.task_lists,
            flags.ENABLE_FOOTNOTES: o.footnotes,
            flags.ENABLE_GFM: o.alerts,
            flags.ENABLE_MATH: o.math,
            flags.ENABLE_DEFINITION_LIST: o.definition_lists,
            flags.ENABLE_SMART_PUNCTUATION: o.smart_punctuation,
            flags.ENABLE_HEADING_ATTRIBUTES: heading_attributes,
            flags.ENABLE_SUPERSCRIPT: superscript,
            flags.ENABLE_SUBSCRIPT: subscript,
            flags.ENABLE_WIKILINKS: wikilinks,
            flags.ENABLE_OLD_FOOTNOTES: old_footnotes,
        }
        value = flags(0)
        for flag, enabled in selected.items():
            if enabled:
                value |= flag
        self._md = pyromark.Markdown(options=value, highlight=highlight)

    def _render(self, text: str) -> str:
        return self._md.html(text)

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    heading_attributes: bool = False,
    superscript: bool = False,
    subscript: bool = False,
    wikilinks: bool = False,
    old_footnotes: bool = False,
    highlight: Theme | None = None,
) -> None

Create a pyromark parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
heading_attributes bool

# Heading {#id .class} attributes.

False
superscript bool

^sup^.

False
subscript bool

~sub~.

False
wikilinks bool

[[wikilinks]].

False
old_footnotes bool

Footnotes with the older, looser pulldown-cmark syntax.

False
highlight Theme | None

Syntax-highlight code blocks with this theme.

None
Source code in src/mkconvert/parsers/pyromark.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    heading_attributes: bool = False,
    superscript: bool = False,
    subscript: bool = False,
    wikilinks: bool = False,
    old_footnotes: bool = False,
    highlight: pyromark.Theme | None = None,
) -> None:
    """Create a pyromark parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        heading_attributes: `# Heading {#id .class}` attributes.
        superscript: `^sup^`.
        subscript: `~sub~`.
        wikilinks: `[[wikilinks]]`.
        old_footnotes: Footnotes with the older, looser pulldown-cmark syntax.
        highlight: Syntax-highlight code blocks with this theme.
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import pyromark

    flags = pyromark.Options
    o = self.options
    selected = {
        flags.ENABLE_TABLES: o.tables,
        flags.ENABLE_STRIKETHROUGH: o.strikethrough,
        flags.ENABLE_TASKLISTS: o.task_lists,
        flags.ENABLE_FOOTNOTES: o.footnotes,
        flags.ENABLE_GFM: o.alerts,
        flags.ENABLE_MATH: o.math,
        flags.ENABLE_DEFINITION_LIST: o.definition_lists,
        flags.ENABLE_SMART_PUNCTUATION: o.smart_punctuation,
        flags.ENABLE_HEADING_ATTRIBUTES: heading_attributes,
        flags.ENABLE_SUPERSCRIPT: superscript,
        flags.ENABLE_SUBSCRIPT: subscript,
        flags.ENABLE_WIKILINKS: wikilinks,
        flags.ENABLE_OLD_FOOTNOTES: old_footnotes,
    }
    value = flags(0)
    for flag, enabled in selected.items():
        if enabled:
            value |= flag
    self._md = pyromark.Markdown(options=value, highlight=highlight)

PythonMarkdownParser

Bases: MarkdownParser

Python-Markdown with pymdown-extensions (not CommonMark compliant).

Fenced code blocks are always on. Strikethrough, task lists, autolinks and math come from pymdown-extensions. Not supported: alerts.

Source code in src/mkconvert/parsers/python_markdown.py
class PythonMarkdownParser(MarkdownParser):
    """Python-Markdown with pymdown-extensions (not CommonMark compliant).

    Fenced code blocks are always on. Strikethrough, task lists, autolinks and math
    come from pymdown-extensions. Not supported: `alerts`.
    """

    name = "python-markdown"
    requires = ("markdown", "pymdownx")
    extra = "markdown"
    supported_options: ClassVar[frozenset[str]] = frozenset({
        "tables",
        "strikethrough",
        "autolinks",
        "task_lists",
        "footnotes",
        "heading_ids",
        "math",
        "definition_lists",
        "hard_breaks",
        "smart_punctuation",
        "raw_html",
        "front_matter",
    })

    def __init__(
        self,
        options: MarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        extensions: Sequence[str | Extension] = (),
        extension_configs: Mapping[str, Mapping[str, Any]] | None = None,
        output_format: Literal["html", "xhtml"] = "html",
    ) -> None:
        """Create a Python-Markdown parser.

        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            extensions: Further extensions, e.g. `"admonition"` or `"pymdownx.superfences"`.
            extension_configs: Settings per extension name; merged over the ones mkconvert
                uses for the common options.
            output_format: `"html"` or `"xhtml"`.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import markdown

        o = self.options
        selected = {
            "tables": o.tables,
            "pymdownx.tilde": o.strikethrough,
            "pymdownx.magiclink": o.autolinks,
            "pymdownx.tasklist": o.task_lists,
            "footnotes": o.footnotes,
            "toc": o.heading_ids,
            "pymdownx.arithmatex": o.math,
            "def_list": o.definition_lists,
            "nl2br": o.hard_breaks,
            "smarty": o.smart_punctuation,
        }
        exts: list[str | Extension] = ["fenced_code"]
        exts += [name for name, enabled in selected.items() if enabled]
        exts += list(extensions)
        configs: dict[str, Any] = {
            "pymdownx.tilde": {"subscript": False},
            "pymdownx.arithmatex": {"generic": True},
        }
        for name, cfg in (extension_configs or {}).items():
            configs[name] = {**configs.get(name, {}), **cfg}
        self._md = markdown.Markdown(
            extensions=exts, extension_configs=configs, output_format=output_format
        )
        if not o.raw_html:
            self._md.preprocessors.deregister("html_block")
            self._md.inlinePatterns.deregister("html")
        self._lock = threading.Lock()

    def _render(self, text: str) -> str:
        with self._lock:
            return self._md.reset().convert(text)

__init__

__init__(
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extensions: Sequence[str | Extension] = (),
    extension_configs: Mapping[str, Mapping[str, Any]] | None = None,
    output_format: Literal["html", "xhtml"] = "html",
) -> None

Create a Python-Markdown parser.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Common options.

None
on_unsupported OnUnsupported

See Backend.

'warn'
extensions Sequence[str | Extension]

Further extensions, e.g. "admonition" or "pymdownx.superfences".

()
extension_configs Mapping[str, Mapping[str, Any]] | None

Settings per extension name; merged over the ones mkconvert uses for the common options.

None
output_format Literal['html', 'xhtml']

"html" or "xhtml".

'html'
Source code in src/mkconvert/parsers/python_markdown.py
def __init__(
    self,
    options: MarkdownOptions | None = None,
    *,
    on_unsupported: OnUnsupported = "warn",
    extensions: Sequence[str | Extension] = (),
    extension_configs: Mapping[str, Mapping[str, Any]] | None = None,
    output_format: Literal["html", "xhtml"] = "html",
) -> None:
    """Create a Python-Markdown parser.

    Args:
        options: Common options.
        on_unsupported: See `Backend`.
        extensions: Further extensions, e.g. `"admonition"` or `"pymdownx.superfences"`.
        extension_configs: Settings per extension name; merged over the ones mkconvert
            uses for the common options.
        output_format: `"html"` or `"xhtml"`.
    """
    super().__init__(options, on_unsupported=on_unsupported)
    import markdown

    o = self.options
    selected = {
        "tables": o.tables,
        "pymdownx.tilde": o.strikethrough,
        "pymdownx.magiclink": o.autolinks,
        "pymdownx.tasklist": o.task_lists,
        "footnotes": o.footnotes,
        "toc": o.heading_ids,
        "pymdownx.arithmatex": o.math,
        "def_list": o.definition_lists,
        "nl2br": o.hard_breaks,
        "smarty": o.smart_punctuation,
    }
    exts: list[str | Extension] = ["fenced_code"]
    exts += [name for name, enabled in selected.items() if enabled]
    exts += list(extensions)
    configs: dict[str, Any] = {
        "pymdownx.tilde": {"subscript": False},
        "pymdownx.arithmatex": {"generic": True},
    }
    for name, cfg in (extension_configs or {}).items():
        configs[name] = {**configs.get(name, {}), **cfg}
    self._md = markdown.Markdown(
        extensions=exts, extension_configs=configs, output_format=output_format
    )
    if not o.raw_html:
        self._md.preprocessors.deregister("html_block")
        self._md.inlinePatterns.deregister("html")
    self._lock = threading.Lock()