Skip to content

extension.py

This module holds the code of the Markdown extension responsible for matching "autodoc" instructions.

The extension is composed of a Markdown block processor that matches indented blocks starting with a line like '::: identifier'.

For each of these blocks, it uses a handler to collect documentation about the given identifier and render it with Jinja templates.

Both the collection and rendering process can be configured by adding YAML configuration under the "autodoc" instruction:

::: some.identifier
    handler: python
    selection:
      option1: value1
      option2:
        - value2a
        - value2b
    rendering:
      option_x: etc

AutoDocProcessor ¤

Our "autodoc" Markdown block processor.

It has a test method that tells if a block matches a criterion, and a run method that processes it.

It also has utility methods allowing to get handlers and their configuration easily, useful when processing a matched block.

__init__(self, parser, md, config, handlers, autorefs) special ¤

Initialize the object.

Parameters:

Name Type Description Default
parser BlockParser

A markdown.blockparser.BlockParser instance.

required
md Markdown

A markdown.Markdown instance.

required
config dict

The configuration of the mkdocstrings plugin.

required
handlers Handlers

A mkdocstrings.handlers.base.Handlers instance.

required
autorefs AutorefsPlugin

A mkdocs_autorefs.plugin.AutorefsPlugin instance.

required
Source code in mkdocstrings/extension.py
def __init__(
    self, parser: BlockParser, md: Markdown, config: dict, handlers: Handlers, autorefs: AutorefsPlugin
) -> None:
    """Initialize the object.

    Arguments:
        parser: A `markdown.blockparser.BlockParser` instance.
        md: A `markdown.Markdown` instance.
        config: The [configuration][mkdocstrings.plugin.MkdocstringsPlugin.config_scheme]
            of the `mkdocstrings` plugin.
        handlers: A [mkdocstrings.handlers.base.Handlers][] instance.
        autorefs: A [mkdocs_autorefs.plugin.AutorefsPlugin][] instance.
    """
    super().__init__(parser=parser)
    self.md = md
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs
    self._updated_env = False

run(self, parent, blocks) ¤

Run code on the matched blocks.

The identifier and configuration lines are retrieved from a matched block and used to collect and render an object.

Parameters:

Name Type Description Default
parent Element

The parent element in the XML tree.

required
blocks MutableSequence[str]

The rest of the blocks to be processed.

required
Source code in mkdocstrings/extension.py
def run(self, parent: Element, blocks: MutableSequence[str]) -> None:
    """Run code on the matched blocks.

    The identifier and configuration lines are retrieved from a matched block
    and used to collect and render an object.

    Arguments:
        parent: The parent element in the XML tree.
        blocks: The rest of the blocks to be processed.
    """
    block = blocks.pop(0)
    match = self.regex.search(block)

    if match:
        if match.start() > 0:
            self.parser.parseBlocks(parent, [block[: match.start()]])
        # removes the first line
        block = block[match.end() :]  # type: ignore

    block, the_rest = self.detab(block)

    if match:
        identifier = match["name"]
        heading_level = match["heading"].count("#")
        log.debug(f"Matched '::: {identifier}'")

        html, handler = self._process_block(identifier, block, heading_level)
        el = Element("div", {"class": "mkdocstrings"})
        # The final HTML is inserted as opaque to subsequent processing, and only revealed at the end.
        el.text = self.md.htmlStash.store(html)
        # So we need to duplicate the headings directly (and delete later), just so 'toc' can pick them up.
        headings = handler.renderer.get_headings()
        el.extend(headings)

        for heading in headings:
            page = self._autorefs.current_page
            anchor = heading.attrib["id"]
            self._autorefs.register_anchor(page, anchor)

            if "data-role" in heading.attrib:
                self._handlers.inventory.register(
                    name=anchor,
                    domain=handler.domain,
                    role=heading.attrib["data-role"],
                    uri=f"{page}#{anchor}",
                )

        parent.append(el)

    if the_rest:
        # This block contained unindented line(s) after the first indented
        # line. Insert these lines as the first block of the master blocks
        # list for future processing.
        blocks.insert(0, the_rest)

test(self, parent, block) ¤

Match our autodoc instructions.

Parameters:

Name Type Description Default
parent Element

The parent element in the XML tree.

required
block str

The block to be tested.

required

Returns:

Type Description
bool

Whether this block should be processed or not.

Source code in mkdocstrings/extension.py
def test(self, parent: Element, block: str) -> bool:  # type: ignore
    """Match our autodoc instructions.

    Arguments:
        parent: The parent element in the XML tree.
        block: The block to be tested.

    Returns:
        Whether this block should be processed or not.
    """
    return bool(self.regex.search(block))

MkdocstringsExtension ¤

Our Markdown extension.

It cannot work outside of mkdocstrings.

__init__(self, config, handlers, autorefs, **kwargs) special ¤

Initialize the object.

Parameters:

Name Type Description Default
config dict

The configuration items from mkdocs and mkdocstrings that must be passed to the block processor when instantiated in extendMarkdown.

required
handlers Handlers

A mkdocstrings.handlers.base.Handlers instance.

required
autorefs AutorefsPlugin

A mkdocs_autorefs.plugin.AutorefsPlugin instance.

required
kwargs

Keyword arguments used by markdown.extensions.Extension.

{}
Source code in mkdocstrings/extension.py
def __init__(self, config: dict, handlers: Handlers, autorefs: AutorefsPlugin, **kwargs) -> None:
    """Initialize the object.

    Arguments:
        config: The configuration items from `mkdocs` and `mkdocstrings` that must be passed to the block processor
            when instantiated in [`extendMarkdown`][mkdocstrings.extension.MkdocstringsExtension.extendMarkdown].
        handlers: A [mkdocstrings.handlers.base.Handlers][] instance.
        autorefs: A [mkdocs_autorefs.plugin.AutorefsPlugin][] instance.
        kwargs: Keyword arguments used by `markdown.extensions.Extension`.
    """
    super().__init__(**kwargs)
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs

extendMarkdown(self, md) ¤

Register the extension.

Add an instance of our AutoDocProcessor to the Markdown parser.

Parameters:

Name Type Description Default
md Markdown

A markdown.Markdown instance.

required
Source code in mkdocstrings/extension.py
def extendMarkdown(self, md: Markdown) -> None:  # noqa: N802 (casing: parent method's name)
    """Register the extension.

    Add an instance of our [`AutoDocProcessor`][mkdocstrings.extension.AutoDocProcessor] to the Markdown parser.

    Arguments:
        md: A `markdown.Markdown` instance.
    """
    md.parser.blockprocessors.register(
        AutoDocProcessor(md.parser, md, self._config, self._handlers, self._autorefs),
        "mkdocstrings",
        priority=75,  # Right before markdown.blockprocessors.HashHeaderProcessor
    )
    md.treeprocessors.register(
        _PostProcessor(md.parser),
        "mkdocstrings_post",
        priority=4,  # Right after 'toc'.
    )

get_item_configs(handler_config, config) ¤

Get the selection and rendering configuration merged into the global configuration of the given handler.

Parameters:

Name Type Description Default
handler_config dict

The global configuration of a handler. It can be an empty dictionary.

required
config dict

The configuration to merge into the global handler configuration.

required

Returns:

Type Description
Tuple[Mapping, Mapping]

Two dictionaries: selection and rendering. The local configurations are merged into the global ones.

Source code in mkdocstrings/extension.py
def get_item_configs(handler_config: dict, config: dict) -> Tuple[Mapping, Mapping]:
    """Get the selection and rendering configuration merged into the global configuration of the given handler.

    Arguments:
        handler_config: The global configuration of a handler. It can be an empty dictionary.
        config: The configuration to merge into the global handler configuration.

    Returns:
        Two dictionaries: selection and rendering. The local configurations are merged into the global ones.
    """
    item_selection_config = ChainMap(config.get("selection", {}), handler_config.get("selection", {}))
    item_rendering_config = ChainMap(config.get("rendering", {}), handler_config.get("rendering", {}))
    return item_selection_config, item_rendering_config
Back to top