Skip to content

rendering ¤

This module holds helpers responsible for augmentations to the Markdown sub-documents produced by handlers.

Classes:

HeadingShiftingTreeprocessor ¤

HeadingShiftingTreeprocessor(md: Markdown, shift_by: int)

Bases: Treeprocessor

Shift levels of all Markdown headings according to the configured base level.

Parameters:

  • md ¤

    (Markdown) –

    A markdown.Markdown instance.

  • shift_by ¤

    (int) –

    The number of heading "levels" to add to every heading.

Attributes:

  • shift_by (int) –

    The number of heading "levels" to add to every heading. <h2> with shift_by = 3 becomes <h5>.

Source code in src/mkdocstrings/handlers/rendering.py
198
199
200
201
202
203
204
205
206
def __init__(self, md: Markdown, shift_by: int):
    """Initialize the object.

    Arguments:
        md: A `markdown.Markdown` instance.
        shift_by: The number of heading "levels" to add to every heading.
    """
    super().__init__(md)
    self.shift_by = shift_by

shift_by instance-attribute ¤

shift_by: int = shift_by

The number of heading "levels" to add to every heading. <h2> with shift_by = 3 becomes <h5>.

Highlighter ¤

Highlighter(md: Markdown)

Bases: Highlight

Code highlighter that tries to match the Markdown configuration.

Picking up the global config and defaults works only if you use the codehilite or pymdownx.highlight (recommended) Markdown extension.

  • If you use pymdownx.highlight, highlighting settings are picked up from it, and the default CSS class is .highlight. This also means the default of guess_lang: false.

  • Otherwise, if you use the codehilite extension, settings are picked up from it, and the default CSS class is .codehilite. Also consider setting guess_lang: false.

  • If neither are added to markdown_extensions, highlighting is enabled anyway. This is for backwards compatibility. If you really want to disable highlighting even in mkdocstrings, add one of these extensions anyway and set use_pygments: false.

The underlying implementation is pymdownx.highlight regardless.

Parameters:

  • md ¤

    (Markdown) –

    The Markdown instance to read configs from.

Methods:

Source code in src/mkdocstrings/handlers/rendering.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(self, md: Markdown):
    """Configure to match a `markdown.Markdown` instance.

    Arguments:
        md: The Markdown instance to read configs from.
    """
    config: dict[str, Any] = {}
    self._highlighter: str | None = None
    for ext in md.registeredExtensions:
        if isinstance(ext, HighlightExtension) and (ext.enabled or not config):
            self._highlighter = "highlight"
            config = ext.getConfigs()
            break  # This one takes priority, no need to continue looking
        if isinstance(ext, CodeHiliteExtension) and not config:
            self._highlighter = "codehilite"
            config = ext.getConfigs()
            config["language_prefix"] = config["lang_prefix"]
    self._css_class = config.pop("css_class", "highlight")
    super().__init__(**{name: opt for name, opt in config.items() if name in self._highlight_config_keys})

highlight ¤

highlight(
    src: str,
    language: str | None = None,
    *,
    inline: bool = False,
    dedent: bool = True,
    linenums: bool | None = None,
    **kwargs: Any
) -> str

Highlight a code-snippet.

Parameters:

  • src ¤

    (str) –

    The code to highlight.

  • language ¤

    (str | None, default: None ) –

    Explicitly tell what language to use for highlighting.

  • inline ¤

    (bool, default: False ) –

    Whether to highlight as inline.

  • dedent ¤

    (bool, default: True ) –

    Whether to dedent the code before highlighting it or not.

  • linenums ¤

    (bool | None, default: None ) –

    Whether to add line numbers in the result.

  • **kwargs ¤

    (Any, default: {} ) –

    Pass on to pymdownx.highlight.Highlight.highlight.

Returns:

  • str

    The highlighted code as HTML text, marked safe (not escaped for HTML).

Source code in src/mkdocstrings/handlers/rendering.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def highlight(
    self,
    src: str,
    language: str | None = None,
    *,
    inline: bool = False,
    dedent: bool = True,
    linenums: bool | None = None,
    **kwargs: Any,
) -> str:
    """Highlight a code-snippet.

    Arguments:
        src: The code to highlight.
        language: Explicitly tell what language to use for highlighting.
        inline: Whether to highlight as inline.
        dedent: Whether to dedent the code before highlighting it or not.
        linenums: Whether to add line numbers in the result.
        **kwargs: Pass on to `pymdownx.highlight.Highlight.highlight`.

    Returns:
        The highlighted code as HTML text, marked safe (not escaped for HTML).
    """
    if isinstance(src, Markup):
        src = src.unescape()
    if dedent:
        src = textwrap.dedent(src)

    kwargs.setdefault("css_class", self._css_class)
    old_linenums = self.linenums  # type: ignore[has-type]
    if linenums is not None:
        self.linenums = linenums
    try:
        result = super().highlight(src, language, inline=inline, **kwargs)
    finally:
        self.linenums = old_linenums

    if inline:
        # From the maintainer of codehilite, the codehilite CSS class, as defined by the user,
        # should never be added to inline code, because codehilite does not support inline code.
        # See https://github.com/Python-Markdown/markdown/issues/1220#issuecomment-1692160297.
        css_class = "" if self._highlighter == "codehilite" else kwargs["css_class"]
        return Markup(f'<code class="{css_class} language-{language}">{result.text}</code>')
    return Markup(result)

IdPrependingTreeprocessor ¤

IdPrependingTreeprocessor(md: Markdown, id_prefix: str)

Bases: Treeprocessor

Prepend the configured prefix to IDs of all HTML elements.

Parameters:

  • md ¤

    (Markdown) –

    A markdown.Markdown instance.

  • id_prefix ¤

    (str) –

    The prefix to add to every ID. It is prepended without any separator.

Attributes:

  • id_prefix (str) –

    The prefix to add to every ID. It is prepended without any separator; specify your own separator if needed.

Source code in src/mkdocstrings/handlers/rendering.py
141
142
143
144
145
146
147
148
149
def __init__(self, md: Markdown, id_prefix: str):
    """Initialize the object.

    Arguments:
        md: A `markdown.Markdown` instance.
        id_prefix: The prefix to add to every ID. It is prepended without any separator.
    """
    super().__init__(md)
    self.id_prefix = id_prefix

id_prefix instance-attribute ¤

id_prefix: str = id_prefix

The prefix to add to every ID. It is prepended without any separator; specify your own separator if needed.

MkdocstringsInnerExtension ¤

MkdocstringsInnerExtension(headings: list[Element])

Bases: Extension

Extension that should always be added to Markdown sub-documents that handlers request (and only them).

Parameters:

  • headings ¤

    (list[Element]) –

    A list that will be populated with all HTML heading elements encountered in the document.

Methods:

Source code in src/mkdocstrings/handlers/rendering.py
261
262
263
264
265
266
267
268
def __init__(self, headings: list[Element]):
    """Initialize the object.

    Arguments:
        headings: A list that will be populated with all HTML heading elements encountered in the document.
    """
    super().__init__()
    self.headings = headings

extendMarkdown ¤

extendMarkdown(md: Markdown) -> None

Register the extension.

Parameters:

  • md ¤

    (Markdown) –

    A markdown.Markdown instance.

Source code in src/mkdocstrings/handlers/rendering.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def extendMarkdown(self, md: Markdown) -> None:  # noqa: N802 (casing: parent method's name)
    """Register the extension.

    Arguments:
        md: A `markdown.Markdown` instance.
    """
    md.registerExtension(self)
    md.treeprocessors.register(
        HeadingShiftingTreeprocessor(md, 0),
        HeadingShiftingTreeprocessor.name,
        priority=12,
    )
    md.treeprocessors.register(
        IdPrependingTreeprocessor(md, ""),
        IdPrependingTreeprocessor.name,
        priority=4,  # Right after 'toc' (needed because that extension adds ids to headers).
    )
    md.treeprocessors.register(
        _HeadingReportingTreeprocessor(md, self.headings),
        _HeadingReportingTreeprocessor.name,
        priority=1,  # Close to the end.
    )
    md.treeprocessors.register(
        ParagraphStrippingTreeprocessor(md),
        ParagraphStrippingTreeprocessor.name,
        priority=0.99,  # Close to the end.
    )

ParagraphStrippingTreeprocessor ¤

Bases: Treeprocessor

Unwraps the

element around the whole output.