Skip to content

extension ¤

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
    options:
      option1: value1
      option2:
      - value2a
      - value2b
      option_x: etc

Classes:

AutoDocProcessor ¤

AutoDocProcessor(
    parser: BlockParser,
    md: Markdown,
    config: dict,
    handlers: Handlers,
    autorefs: AutorefsPlugin,
)

Bases: BlockProcessor

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.

Parameters:

  • parser ¤

    (BlockParser) –

    A markdown.blockparser.BlockParser instance.

  • md ¤

    (Markdown) –

    A markdown.Markdown instance.

  • config ¤

    (dict) –

    The configuration of the mkdocstrings plugin.

  • handlers ¤

    (Handlers) –

    The handlers container.

  • autorefs ¤

    (AutorefsPlugin) –

    The autorefs plugin instance.

Methods:

  • run

    Run code on the matched blocks.

  • test

    Match our autodoc instructions.

Source code in src/mkdocstrings/extension.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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.PluginConfig] of the `mkdocstrings` plugin.
        handlers: The handlers container.
        autorefs: The autorefs plugin instance.
    """
    super().__init__(parser=parser)
    self.md = md
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs
    self._updated_envs: set = set()

run ¤

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:

Source code in src/mkdocstrings/extension.py
 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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() :]

    block, the_rest = self.detab(block)

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

        html, handler, data = 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.get_headings()
        el.extend(headings)

        page = self._autorefs.current_page
        if page is not None:
            for heading in headings:
                rendered_anchor = heading.attrib["id"]
                self._autorefs.register_anchor(page, rendered_anchor)

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

                    # also register other anchors for this object in the inventory
                    try:
                        data_object = handler.collect(rendered_anchor, handler.fallback_config)
                    except CollectionError:
                        continue
                    for anchor in handler.get_anchors(data_object):
                        if anchor not in self._handlers.inventory:
                            self._handlers.inventory.register(
                                name=anchor,
                                domain=handler.domain,
                                role=heading.attrib["data-role"],
                                priority=2,  # register with lower priority
                                uri=f"{page}#{rendered_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 ¤

test(parent: Element, block: str) -> bool

Match our autodoc instructions.

Parameters:

  • parent ¤

    (Element) –

    The parent element in the XML tree.

  • block ¤

    (str) –

    The block to be tested.

Returns:

  • bool

    Whether this block should be processed or not.

Source code in src/mkdocstrings/extension.py
86
87
88
89
90
91
92
93
94
95
96
def test(self, parent: Element, block: str) -> bool:  # noqa: ARG002
    """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 ¤

MkdocstringsExtension(
    config: dict,
    handlers: Handlers,
    autorefs: AutorefsPlugin,
    **kwargs: Any,
)

Bases: Extension

Our Markdown extension.

It cannot work outside of mkdocstrings.

Parameters:

  • config ¤

    (dict) –

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

  • handlers ¤

    (Handlers) –

    The handlers container.

  • autorefs ¤

    (AutorefsPlugin) –

    The autorefs plugin instance.

  • **kwargs ¤

    (Any, default: {} ) –

    Keyword arguments used by markdown.extensions.Extension.

Methods:

Source code in src/mkdocstrings/extension.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def __init__(self, config: dict, handlers: Handlers, autorefs: AutorefsPlugin, **kwargs: Any) -> 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: The handlers container.
        autorefs: The autorefs plugin instance.
        **kwargs: Keyword arguments used by `markdown.extensions.Extension`.
    """
    super().__init__(**kwargs)
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs

extendMarkdown ¤

extendMarkdown(md: Markdown) -> None

Register the extension.

Add an instance of our AutoDocProcessor to the Markdown parser.

Parameters:

  • md ¤

    (Markdown) –

    A markdown.Markdown instance.

Source code in src/mkdocstrings/extension.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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(
        _HeadingsPostProcessor(md),
        "mkdocstrings_post_headings",
        priority=4,  # Right after 'toc'.
    )
    md.treeprocessors.register(
        _TocLabelsTreeProcessor(md),
        "mkdocstrings_post_toc_labels",
        priority=4,  # Right after 'toc'.
    )