-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmacros.py
78 lines (56 loc) · 2.48 KB
/
macros.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# License: MIT
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
"""This module defines macros for use in Markdown files."""
from typing import Any
import markdown as md
from markdown.extensions import toc
from mkdocs_macros import plugin as macros
_CODE_ANNOTATION_MARKER: str = (
r'<span class="md-annotation">'
r'<span class="md-annotation__index" tabindex="-1">'
r'<span data-md-annotation-id="1"></span>'
r"</span>"
r"</span>"
)
def _slugify(text: str) -> str:
"""Slugify a text.
Args:
text: The text to slugify.
Returns:
The slugified text.
"""
return toc.slugify_unicode(text, "-")
def _hook_macros_plugin(env: macros.MacrosPlugin) -> None:
"""Integrate the `mkdocs-macros` plugin into `mkdocstrings`.
This is a temporary workaround to make `mkdocs-macros` work with
`mkdocstrings` until a proper `mkdocs-macros` *pluglet* is available. See
https://github.com/mkdocstrings/mkdocstrings/issues/615 for details.
Args:
env: The environment to hook the plugin into.
"""
# get mkdocstrings' Python handler
python_handler = env.conf["plugins"]["mkdocstrings"].get_handler("python")
# get the `update_env` method of the Python handler
update_env = python_handler.update_env
# override the `update_env` method of the Python handler
def patched_update_env(markdown: md.Markdown, config: dict[str, Any]) -> None:
update_env(markdown, config)
# get the `convert_markdown` filter of the env
convert_markdown = python_handler.env.filters["convert_markdown"]
# build a chimera made of macros+mkdocstrings
def render_convert(markdown: str, *args: Any, **kwargs: Any) -> Any:
return convert_markdown(env.render(markdown), *args, **kwargs)
# patch the filter
python_handler.env.filters["convert_markdown"] = render_convert
# patch the method
python_handler.update_env = patched_update_env
def define_env(env: macros.MacrosPlugin) -> None:
"""Define the hook to create macro functions for use in Markdown.
Args:
env: The environment to define the macro functions in.
"""
# A variable to easily show an example code annotation from mkdocs-material.
# https://squidfunk.github.io/mkdocs-material/reference/code-blocks/#adding-annotations
env.variables["code_annotation_marker"] = _CODE_ANNOTATION_MARKER
# This hook needs to be done at the end of the `define_env` function.
_hook_macros_plugin(env)