Debian Codegraph @

docs/usage/handlers.md

raw
1 # Handlers
2
3 A handler is what makes it possible to collect and render documentation for a particular language.
4
5 ## Available handlers
6
7 - [C](https://mkdocstrings.github.io/c/){ .external }
8 - [Crystal](https://mkdocstrings.github.io/crystal/){ .external }
9 - [GitHub Actions](https://watermarkhu.nl/mkdocstrings-github/){ .external }
10 - [Python](https://mkdocstrings.github.io/python/){ .external }
11 - [Python (Legacy)](https://mkdocstrings.github.io/python-legacy/){ .external }
12 - [MATLAB](https://watermarkhu.nl/mkdocstrings-matlab/){ .external }
13 - [Shell](https://mkdocstrings.github.io/shell/){ .external }
14 - [TypeScript](https://mkdocstrings.github.io/typescript/){ .external }
15 - [VBA](https://pypi.org/project/mkdocstrings-vba/){ .external }
16
17 ## About the Python handlers
18
19 Since version 0.18, a new Python handler is available.
20 It is based on [Griffe](https://github.com/mkdocstrings/griffe),
21 which is an improved version of [pytkdocs](https://github.com/mkdocstrings/pytkdocs).
22
23 If you want to keep using the legacy handler as long as possible,
24 you can depend on `mkdocstrings-python-legacy` directly,
25 or specify the `python-legacy` extra when depending on *mkdocstrings*:
26
27 ```toml title="pyproject.toml"
28 # PEP 621 dependencies declaration
29 # adapt to your dependencies manager
30 [project]
31 dependencies = [
32 "mkdocstrings[python-legacy]>=0.18",
33 ]
34 ```
35
36 The legacy handler will continue to "work" for many releases,
37 as long as the new handler does not cover all previous use-cases.
38
39 ### Migrate to the new Python handler
40
41 To use the new Python handler,
42 you can depend on `mkdocstrings-python` directly,
43 or specify the `python` extra when depending on *mkdocstrings*:
44
45 ```toml title="pyproject.toml"
46 # PEP 621 dependencies declaration
47 # adapt to your dependencies manager
48 [project]
49 dependencies = [
50 "mkdocstrings[python]>=0.18",
51 ]
52 ```
53
54 #### Selection options
55
56 WARNING: Since *mkdocstrings* 0.19, the YAML `selection` key is merged into the `options` key.
57
58 - [x] `filters` is implemented, and used as before.
59 - [x] `members` is implemented, and used as before.
60 - [x] `inherited_members` is implemented.
61 - [x] `docstring_style` is implemented, and used as before,
62 except for the `restructured-text` style which is renamed `sphinx`.
63 Numpy-style is now built-in, so you can stop depending on `pytkdocs[numpy-style]`
64 or `docstring_parser`.
65 - [x] `docstring_options` is implemented, and used as before.
66 Refer to the [`griffe` documentation](https://mkdocstrings.github.io/griffe/docstrings/#parsing-options)
67 for the updated list of supported docstring options.
68 - [x] `new_path_syntax` is irrelevant now. If you were setting it to True,
69 remove the option and replace every colon (`:`) in your autodoc identifiers
70 by dots (`.`).
71
72 See [all the handler's options](https://mkdocstrings.github.io/python/usage/).
73
74 #### Rendering options
75
76 WARNING: Since *mkdocstrings* 0.19, the YAML `rendering` key is merged into the `options` key.
77
78 Every previous option is supported.
79 Additional options are available:
80
81 - [x] `separate_signature`: Render the signature (or attribute value) in a code block below the heading,
82 instead as inline code. Useful for long signatures. If Black is installed,
83 the signature is formatted. Default: `False`.
84 - [x] `line_length`: The maximum line length to use when formatting signatures. Default: `60`.
85 - [x] `show_submodules`: Whether to render submodules of a module when iterating on children.
86 Default: `False`.
87 - [x] `docstring_section_style`: The style to use to render docstring sections such as attributes,
88 parameters, etc. Available styles: `"table"` (default), `"list"` and `"spacy"`. The SpaCy style
89 is a poor implementation of their [table style](https://spacy.io/api/doc/#init).
90 We are open to improvements through PRs!
91
92 See [all the handler's options](https://mkdocstrings.github.io/python/usage/).
93
94 #### Templates
95
96 Templates are mostly the same as before, but the file layout has changed,
97 as well as some file names.
98 See [the documentation about the Python handler templates](https://mkdocstrings.github.io/python/usage/customization/#templates).
99
100 ## Custom handlers
101
102 Since version 0.14, you can create and use custom handlers
103 thanks to namespace packages. For more information about namespace packages,
104 [see their documentation](https://packaging.python.org/guides/packaging-namespace-packages/).
105
106 TIP: **TL;DR - Project template for handlers.**
107 *mkdocstrings* provides a [Copier](https://github.com/copier-org/copier) template to kickstart
108 new handlers: https://github.com/mkdocstrings/handler-template. To use it, install Copier
109 (`pipx install copier`), then run `copier gh:mkdocstrings/handler-template my_handler`
110 to generate a new project. See [its upstream documentation](https://pawamoy.github.io/copier-pdm/)
111 to learn how to work on the generated project.
112
113 ### Packaging
114
115 For *mkdocstrings*, a custom handler package would have the following structure:
116
117 ```
118 πŸ“ your_repository
119 β””β”€β•΄πŸ“ mkdocstrings_handlers
120 β””β”€β•΄πŸ“ custom_handler
121 β”œβ”€β•΄πŸ“ templates
122 β”‚Β  β”œβ”€β•΄πŸ“ material
123 β”‚ β”œβ”€β•΄πŸ“ mkdocs
124 β”‚ β””β”€β•΄πŸ“ readthedocs
125 β””β”€β•΄πŸ“„ __init__.py
126 ```
127
128 NOTE: **Note the absence of `__init__.py` module in `mkdocstrings_handlers`!**
129
130 ### Code
131
132 A handler is a subclass of the base handler provided by *mkdocstrings*.
133 See the documentation for the [`BaseHandler`][mkdocstrings.BaseHandler].
134
135 Subclasses of the base handler must declare a `name` and `domain` as class attributes,
136 as well as implement the following methods:
137
138 - `collect(identifier, options)` (**required**): method responsible for collecting and returning data (extracting
139 documentation from source code, loading introspecting objects in memory, other sources? etc.)
140 - `render(identifier, options)` (**required**): method responsible for actually rendering the data to HTML,
141 using the Jinja templates provided by your package.
142 - `get_options(local_options)` (**required**): method responsible for combining global options with local ones.
143 - `get_aliases(identifier)` (**recommended**): method responsible for returning known aliases of object identifiers,
144 in order to register cross-references in the autorefs plugin.
145 - `get_inventory_urls()` (optional): method responsible for returning a list of URLs to download (object inventories)
146 along with configuration options (for loading the inventory with `load_inventory`).
147 - `load_inventory(in_file, url, **options)` (optional): method responsible for loading an inventory (binary file-handle)
148 and yielding tuples of identifiers and URLs.
149 - `update_env(config)` (optional): Gives you a chance to customize the Jinja environment used to render templates,
150 for examples by adding/removing Jinja filters and global context variables.
151 - `teardown()` (optional): Clean up / teardown anything that needs it at the end of the build.
152
153 You must implement a `get_handler` method at the module level,
154 which returns an instance of your handler.
155 This function takes the following parameters:
156
157 - `theme` (string, theme name)
158 - `custom_templates` (optional string, path to custom templates directory)
159 - `mdx` (list, Markdown extensions)
160 - `mdx_config` (dict, extensions configuration)
161 - `handler_config` (dict, handle configuration)
162 - `tool_config` (dict, the whole MkDocs configuration)
163
164 These arguments are all passed as keyword arguments, so you can ignore them
165 by adding `**kwargs` or similar to your signature.
166
167 You should not modify the MkDocs config but can use it to get
168 information about the MkDocs instance such as where the current `site_dir` lives.
169 See the [Mkdocs Configuration](https://www.mkdocs.org/user-guide/configuration/) for
170 more info about what is accessible from it.
171
172 Check out how the
173 [Python handler](https://github.com/mkdocstrings/python/blob/master/src/mkdocstrings_handlers/python)
174 is written for inspiration.
175
176 ### Templates
177
178 Your handler's implementation should normally be backed by templates, which go
179 to the directory `mkdocstrings_handlers/custom_handler/templates/some_theme`
180 (`custom_handler` here should be replaced with the actual name of your handler,
181 and `some_theme` should be the name of an actual MkDocs theme that you support,
182 e.g. `material`).
183
184 With that structure, you can use `self.env.get_template("foo.html")` inside
185 your `render` method. This already chooses the subdirectory based on
186 the current MkDocs theme.
187
188 If you wish to support *any* MkDocs theme, rather than a few specifically
189 selected ones, you can pick one theme's subdirectory to be the fallback for
190 when an unknown theme is encountered. Then you just need to set the
191 `fallback_theme` variable on your handler subclass. The fallback directory can
192 be used even for themes you explicitly support: you can omit some template from
193 one of the other theme directories in case they're exactly the same as in the
194 fallback theme.
195
196 If your theme's HTML requires CSS to go along with it, put it into a file named
197 `mkdocstrings_handlers/custom_handler/templates/some_theme/style.css`, then this will be
198 included into the final site automatically if this handler is ever used.
199 Alternatively, you can put the CSS as a string into the `extra_css` variable of
200 your handler.
201
202 Finally, it's possible to entirely omit templates, and tell *mkdocstrings*
203 to use the templates of another handler. In you handler, override the
204 `get_templates_dir()` method to return the other handlers templates path:
205
206 ```python
207 from pathlib import Path
208 from mkdocstrings import BaseHandler
209
210
211 class CobraHandler(BaseHandler):
212 def get_templates_dir(self, handler: str | None = None) -> Path:
213 # use the python handler templates
214 # (it assumes the python handler is installed)
215 return super().get_templates_dir("python")
216 ```
217
218 ### Usage
219
220 When a custom handler is installed, it is then available to *mkdocstrings*.
221 You can configure it as usual:
222
223 ```yaml title="mkdocs.yml"
224 plugins:
225 - mkdocstrings:
226 handlers:
227 custom_handler:
228 handler_config_option: yes
229 options:
230 some_config_option: "a"
231 other_config_option: 0
232 ```
233
234 ...and use it in your autodoc instructions:
235
236 ```md title="docs/some_page.md"
237 # Documentation for an object
238
239 ::: some.objects.path
240 handler: custom_handler
241 options:
242 some_config_option: "b"
243 other_config_option: 1
244 ```
245
246 ## Handler extensions
247
248 *mkdocstrings* provides a way for third-party packages
249 to extend or alter the behavior of handlers.
250 For example, an extension of the Python handler
251 could add specific support for another Python library.
252
253 NOTE: This feature is intended for developers.
254 If you are a user and want to customize how objects are rendered,
255 see [Theming / Customization](theming.md#customization).
256
257 Such extensions can register additional template folders
258 that will be used when rendering collected data.
259 Extensions are responsible for synchronizing
260 with the handler itself so that it uses the additional templates.
261
262 An extension is a Python package
263 that defines an entry-point for a specific handler:
264
265 ```toml title="pyproject.toml"
266 [project.entry-points."mkdocstrings.python.templates"] # (1)!
267 extension-name = "extension_package:get_templates_path" # (2)!
268 ```
269
270 1. Replace `python` by the name of the handler you want to add templates to.
271 1. Replace `extension-name` by any name you want,
272 and replace `extension_package:get_templates_path`
273 by the actual module path and function name in your package.
274
275 This entry-point assumes that the extension provides
276 a `get_templates_path` function directly under the `extension_package` package:
277
278 ```tree
279 pyproject.toml
280 extension_package/
281 __init__.py
282 templates/
283 ```
284
285 ```python title="extension_package/__init__.py"
286 from pathlib import Path
287
288
289 def get_templates_path() -> Path:
290 return Path(__file__).parent / "templates"
291 ```
292
293 This function doesn't accept any argument
294 and returns the path ([`pathlib.Path`][] or [`str`][])
295 to a directory containing templates.
296 The directory must contain one subfolder
297 for each supported theme, even if empty
298 (see "fallback theme" in [custom handlers templates](#templates_1)).
299 For example:
300
301 ```tree
302 pyproject.toml
303 extension_package/
304 __init__.py
305 templates/
306 material/
307 readthedocs/
308 mkdocs/
309 ```
310
311 *mkdocstrings* will add the folders corresponding to the user-selected theme,
312 and to the handler's defined fallback theme, as usual.
313
314 The names of the extension templates
315 must not overlap with the handler's original templates.
316
317 The extension is then responsible, in collaboration with its target handler,
318 for mutating the collected data in order to instruct the handler
319 to use one of the extension template when rendering particular objects.
320 See each handler's docs to see if they support extensions, and how.