| 1 |
On this page you will find various recipes, tips and tricks |
| 2 |
for *mkdocstrings* and more generally Markdown documentation. |
| 3 |
|
| 4 |
## Automatic code reference pages |
| 5 |
|
| 6 |
TIP: **[mkdocs-autoapi](https://github.com/jcayers20/mkdocs-autoapi) and [mkdocs-api-autonav](https://github.com/tlambert03/mkdocs-api-autonav) are MkDocs plugins that automatically generate API documentation from your project's source code. They were inspired by the recipe below.** |
| 7 |
|
| 8 |
*mkdocstrings* allows to inject documentation for any object |
| 9 |
into Markdown pages. But as the project grows, it quickly becomes |
| 10 |
quite tedious to keep the autodoc instructions, or even the dedicated |
| 11 |
Markdown files in sync with all your source files and objects. |
| 12 |
|
| 13 |
In this recipe, we will iteratively automate the process |
| 14 |
of generating these pages at each build of the documentation. |
| 15 |
|
| 16 |
--- |
| 17 |
|
| 18 |
Let say you have a project called `project`. |
| 19 |
This project has a lot of source files, or modules, |
| 20 |
which live in the `src` folder: |
| 21 |
|
| 22 |
```tree |
| 23 |
repo/ |
| 24 |
src/ |
| 25 |
project/ |
| 26 |
lorem |
| 27 |
ipsum |
| 28 |
dolor |
| 29 |
sit |
| 30 |
amet |
| 31 |
``` |
| 32 |
|
| 33 |
Without an automatic process, you will have to manually |
| 34 |
create a Markdown page for each one of these modules, |
| 35 |
with the corresponding autodoc instruction, for example `::: project.lorem`, |
| 36 |
and also add entry in MkDocs' navigation option (`nav` in `mkdocs.yml`). |
| 37 |
With a lot of modules, this is quickly getting cumbersome. |
| 38 |
|
| 39 |
Lets fix that. |
| 40 |
|
| 41 |
### Generate pages on-the-fly |
| 42 |
|
| 43 |
In this recipe, we suggest to use the [mkdocs-gen-files plugin](https://github.com/oprypin/mkdocs-gen-files). |
| 44 |
This plugin exposes utilities to generate files at build time. |
| 45 |
These files won't be written to the docs directory: you don't have |
| 46 |
to track and version them. They are transparently generated each |
| 47 |
time you build your docs. This is perfect for our use-case! |
| 48 |
|
| 49 |
Add `mkdocs-gen-files` to your project's docs dependencies, |
| 50 |
and configure it like so: |
| 51 |
|
| 52 |
```yaml title="mkdocs.yml" |
| 53 |
plugins: |
| 54 |
- search # (1)! |
| 55 |
- gen-files: |
| 56 |
scripts: |
| 57 |
- scripts/gen_ref_pages.py # (2)! |
| 58 |
- mkdocstrings |
| 59 |
``` |
| 60 |
|
| 61 |
1. Don't forget to load the `search` plugin when redefining the `plugins` item. |
| 62 |
2. The magic happens here, see below how it works. |
| 63 |
|
| 64 |
mkdocs-gen-files is able to run Python scripts at build time. |
| 65 |
The Python script that we will execute lives in a scripts folder, |
| 66 |
and is named `gen_ref_pages.py`, like "generate code reference pages". |
| 67 |
|
| 68 |
```tree |
| 69 |
repo/ |
| 70 |
docs/ |
| 71 |
index.md |
| 72 |
scripts/ |
| 73 |
gen_ref_pages.py |
| 74 |
src/ |
| 75 |
project/ |
| 76 |
mkdocs.yml |
| 77 |
``` |
| 78 |
|
| 79 |
```python title="scripts/gen_ref_pages.py" |
| 80 |
"""Generate the code reference pages.""" |
| 81 |
|
| 82 |
from pathlib import Path |
| 83 |
|
| 84 |
import mkdocs_gen_files |
| 85 |
|
| 86 |
root = Path(__file__).parent.parent |
| 87 |
src = root / "src" # (1)! |
| 88 |
|
| 89 |
for path in sorted(src.rglob("*.py")): # (2)! |
| 90 |
module_path = path.relative_to(src).with_suffix("") # (3)! |
| 91 |
doc_path = path.relative_to(src).with_suffix(".md") # (4)! |
| 92 |
full_doc_path = Path("reference", doc_path) # (5)! |
| 93 |
|
| 94 |
parts = tuple(module_path.parts) |
| 95 |
|
| 96 |
if parts[-1] == "__init__": # (6)! |
| 97 |
parts = parts[:-1] |
| 98 |
elif parts[-1] == "__main__": |
| 99 |
continue |
| 100 |
|
| 101 |
with mkdocs_gen_files.open(full_doc_path, "w") as fd: # (7)! |
| 102 |
identifier = ".".join(parts) # (8)! |
| 103 |
print("::: " + identifier, file=fd) # (9)! |
| 104 |
|
| 105 |
mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root)) # (10)! |
| 106 |
``` |
| 107 |
|
| 108 |
1. It's important to build a path relative to the script itself, |
| 109 |
to make it possible to build the docs with MkDocs' |
| 110 |
[`-f` option](https://www.mkdocs.org/user-guide/cli/#mkdocs-build). |
| 111 |
2. Here we recursively list all `.py` files, but you can adapt the code to list |
| 112 |
files with other extensions of course, supporting other languages than Python. |
| 113 |
3. The module path will look like `project/lorem`. |
| 114 |
It will be used to build the *mkdocstrings* autodoc identifier. |
| 115 |
4. This is the partial path of the Markdown page for the module. |
| 116 |
5. This is the full path of the Markdown page within the docs. |
| 117 |
Here we put all reference pages into a `reference` folder. |
| 118 |
6. This part is only relevant for Python modules. We skip `__main__` modules and |
| 119 |
remove `__init__` from the module parts as it's implicit during imports. |
| 120 |
7. Magic! Add the file to MkDocs pages, without actually writing it in the docs folder. |
| 121 |
8. Build the autodoc identifier. Here we document Python modules, so the identifier |
| 122 |
is a dot-separated path, like `project.lorem`. |
| 123 |
9. Actually write to the magic file. |
| 124 |
10. We can even set the `edit_uri` on the pages. |
| 125 |
|
| 126 |
> NOTE: |
| 127 |
> It is important to look out for correct edit page behaviour when using generated pages. |
| 128 |
> For example, if we have `edit_uri` set to `blob/master/docs/` and the following |
| 129 |
> file structure: |
| 130 |
> |
| 131 |
> ```tree |
| 132 |
> repo/ |
| 133 |
> mkdocs.yml |
| 134 |
> docs/ |
| 135 |
> index.md |
| 136 |
> scripts/ |
| 137 |
> gen_ref_pages.py |
| 138 |
> src/ |
| 139 |
> project/ |
| 140 |
> lorem.py |
| 141 |
> ipsum.py |
| 142 |
> dolor.py |
| 143 |
> sit.py |
| 144 |
> amet.py |
| 145 |
> ``` |
| 146 |
> |
| 147 |
> Then we will have to change our `set_edit_path` call to: |
| 148 |
> |
| 149 |
> ```python |
| 150 |
> mkdocs_gen_files.set_edit_path(full_doc_path, Path("../") / path) # (1)! |
| 151 |
> ``` |
| 152 |
> |
| 153 |
> 1. Path can be used to traverse the structure in any way you may need, but |
| 154 |
> remember to use relative paths! |
| 155 |
> |
| 156 |
> ...so that it correctly sets the edit path of (for example) `lorem.py` to |
| 157 |
> `<repo_url>/blob/master/src/project/lorem.py` instead of |
| 158 |
> `<repo_url>/blob/master/docs/src/project/lorem.py`. |
| 159 |
|
| 160 |
With this script, a `reference` folder is automatically created |
| 161 |
each time we build our docs. This folder contains a Markdown page |
| 162 |
for each of our source modules, and each of these pages |
| 163 |
contains a single line of the form `::: project.module` |
| 164 |
(module being `lorem`, `ipsum`, etc.). Great! |
| 165 |
But, we still have to actually add those pages into our MkDocs |
| 166 |
navigation: |
| 167 |
|
| 168 |
```yaml title="mkdocs.yml" |
| 169 |
nav: |
| 170 |
# rest of the navigation... |
| 171 |
- Code Reference: |
| 172 |
- project: |
| 173 |
- lorem: reference/project/lorem.md |
| 174 |
- ipsum: reference/project/ipsum.md |
| 175 |
- dolor: reference/project/dolor.md |
| 176 |
- sit: reference/project/sit.md |
| 177 |
- amet: reference/project/amet.md |
| 178 |
# rest of the navigation... |
| 179 |
``` |
| 180 |
|
| 181 |
Err... so this process is only semi-automatic? |
| 182 |
Yes, but don't worry, we can fully automate it. |
| 183 |
|
| 184 |
### Generate a literate navigation file |
| 185 |
|
| 186 |
mkdocs-gen-files is able to generate a literate navigation file. |
| 187 |
But to make use of it, we will need an additional plugin: |
| 188 |
[mkdocs-literate-nav](https://github.com/oprypin/mkdocs-literate-nav). |
| 189 |
This plugin allows to specify the whole navigation, or parts of it, |
| 190 |
into Markdown pages, as plain Markdown lists. |
| 191 |
We use it here to specify the navigation for the code reference pages. |
| 192 |
|
| 193 |
First, add `mkdocs-literate-nav` to your project's docs dependencies, |
| 194 |
and configure the plugin in your MkDocs configuration: |
| 195 |
|
| 196 |
```yaml title="mkdocs.yml" hl_lines="6 7" |
| 197 |
plugins: |
| 198 |
- search |
| 199 |
- gen-files: |
| 200 |
scripts: |
| 201 |
- scripts/gen_ref_pages.py |
| 202 |
- literate-nav: |
| 203 |
nav_file: SUMMARY.md |
| 204 |
- mkdocstrings |
| 205 |
``` |
| 206 |
|
| 207 |
Then, the previous script is updated like so: |
| 208 |
|
| 209 |
```python title="scripts/gen_ref_pages.py" hl_lines="7 24 32 33" |
| 210 |
"""Generate the code reference pages and navigation.""" |
| 211 |
|
| 212 |
from pathlib import Path |
| 213 |
|
| 214 |
import mkdocs_gen_files |
| 215 |
|
| 216 |
nav = mkdocs_gen_files.Nav() |
| 217 |
|
| 218 |
root = Path(__file__).parent.parent |
| 219 |
src = root / "src" |
| 220 |
|
| 221 |
for path in sorted(src.rglob("*.py")): |
| 222 |
module_path = path.relative_to(src).with_suffix("") |
| 223 |
doc_path = path.relative_to(src).with_suffix(".md") |
| 224 |
full_doc_path = Path("reference", doc_path) |
| 225 |
|
| 226 |
parts = tuple(module_path.parts) |
| 227 |
|
| 228 |
if parts[-1] == "__init__": |
| 229 |
parts = parts[:-1] |
| 230 |
elif parts[-1] == "__main__": |
| 231 |
continue |
| 232 |
|
| 233 |
nav[parts] = doc_path.as_posix() # (1)! |
| 234 |
|
| 235 |
with mkdocs_gen_files.open(full_doc_path, "w") as fd: |
| 236 |
ident = ".".join(parts) |
| 237 |
fd.write(f"::: {ident}") |
| 238 |
|
| 239 |
mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root)) |
| 240 |
|
| 241 |
with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file: # (2)! |
| 242 |
nav_file.writelines(nav.build_literate_nav()) # (3)! |
| 243 |
``` |
| 244 |
|
| 245 |
1. Progressively build the navigation object. |
| 246 |
2. At the end, create a magic, literate navigation file called `SUMMARY.md` in the `reference` folder. |
| 247 |
3. Write the navigation as a Markdown list in the literate navigation file. |
| 248 |
|
| 249 |
Now we are able to remove our hard-coded navigation in `mkdocs.yml`, |
| 250 |
and replace it with a single line! |
| 251 |
|
| 252 |
```yaml title="mkdocs.yml" |
| 253 |
nav: |
| 254 |
# rest of the navigation... |
| 255 |
# defer to gen-files + literate-nav |
| 256 |
- Code Reference: reference/ # (1)! |
| 257 |
# rest of the navigation... |
| 258 |
``` |
| 259 |
|
| 260 |
1. Note the trailing slash! It is needed so that `mkdocs-literate-nav` knows |
| 261 |
it has to look for a `SUMMARY.md` file in that folder. |
| 262 |
|
| 263 |
At this point, we should be able to see the tree of our modules |
| 264 |
in the navigation. |
| 265 |
|
| 266 |
### Bind pages to sections themselves |
| 267 |
|
| 268 |
There's a last improvement we can do. |
| 269 |
With the current script, sections, corresponding to folders, |
| 270 |
will expand or collapse when you click on them, |
| 271 |
revealing `__init__` modules under them |
| 272 |
(or equivalent modules in other languages, if relevant). |
| 273 |
Since we are documenting a public API, and given users |
| 274 |
never explicitly import `__init__` modules, it would be nice |
| 275 |
if we could get rid of them and instead render their documentation |
| 276 |
inside the section itself. |
| 277 |
|
| 278 |
Well, this is possible thanks to a third plugin: |
| 279 |
[mkdocs-section-index](https://github.com/oprypin/mkdocs-section-index). |
| 280 |
|
| 281 |
Update the script like this: |
| 282 |
|
| 283 |
```python title="scripts/gen_ref_pages.py" hl_lines="21 22" |
| 284 |
"""Generate the code reference pages and navigation.""" |
| 285 |
|
| 286 |
from pathlib import Path |
| 287 |
|
| 288 |
import mkdocs_gen_files |
| 289 |
|
| 290 |
nav = mkdocs_gen_files.Nav() |
| 291 |
|
| 292 |
root = Path(__file__).parent.parent |
| 293 |
src = root / "src" |
| 294 |
|
| 295 |
for path in sorted(src.rglob("*.py")): |
| 296 |
module_path = path.relative_to(src).with_suffix("") |
| 297 |
doc_path = path.relative_to(src).with_suffix(".md") |
| 298 |
full_doc_path = Path("reference", doc_path) |
| 299 |
|
| 300 |
parts = tuple(module_path.parts) |
| 301 |
|
| 302 |
if parts[-1] == "__init__": |
| 303 |
parts = parts[:-1] |
| 304 |
doc_path = doc_path.with_name("index.md") |
| 305 |
full_doc_path = full_doc_path.with_name("index.md") |
| 306 |
elif parts[-1] == "__main__": |
| 307 |
continue |
| 308 |
|
| 309 |
nav[parts] = doc_path.as_posix() |
| 310 |
|
| 311 |
with mkdocs_gen_files.open(full_doc_path, "w") as fd: |
| 312 |
ident = ".".join(parts) |
| 313 |
fd.write(f"::: {ident}") |
| 314 |
|
| 315 |
mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root)) |
| 316 |
|
| 317 |
with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file: |
| 318 |
nav_file.writelines(nav.build_literate_nav()) |
| 319 |
``` |
| 320 |
|
| 321 |
And update your MkDocs configuration to list the plugin: |
| 322 |
|
| 323 |
```yaml title="mkdocs.yml" hl_lines="8" |
| 324 |
plugins: |
| 325 |
- search |
| 326 |
- gen-files: |
| 327 |
scripts: |
| 328 |
- scripts/gen_ref_pages.py |
| 329 |
- literate-nav: |
| 330 |
nav_file: SUMMARY.md |
| 331 |
- section-index |
| 332 |
- mkdocstrings |
| 333 |
``` |
| 334 |
|
| 335 |
With this, `__init__` modules will be documented and bound to the sections |
| 336 |
themselves, better reflecting our public API. |
| 337 |
|
| 338 |
## Prevent selection of prompts and output in Python code blocks |
| 339 |
|
| 340 |
To prevent the selection of `>>>`, `...` and output in Python "Console" code blocks, |
| 341 |
you can use the `pycon` syntax highlighting on your code blocks, |
| 342 |
and add global CSS rules to your site using MkDocs `extra_css` option: |
| 343 |
|
| 344 |
````md |
| 345 |
```pycon |
| 346 |
>>> for word in ("Hello", "mkdocstrings!"): |
| 347 |
... print(word, end=" ") |
| 348 |
... |
| 349 |
Hello mkdocstrings! |
| 350 |
``` |
| 351 |
```` |
| 352 |
|
| 353 |
```css title="docs/css/code_select.css" |
| 354 |
.highlight .gp, .highlight .go { /* Generic.Prompt, Generic.Output */ |
| 355 |
user-select: none; |
| 356 |
} |
| 357 |
``` |
| 358 |
|
| 359 |
```yaml title="mkdocs.yml" |
| 360 |
extra_css: |
| 361 |
- css/code_select.css |
| 362 |
``` |
| 363 |
|
| 364 |
> WARNING: |
| 365 |
> The `.highlight .gp, .highlight .go` CSS selector can have unintended side-effects. |
| 366 |
> To target `pycon` code blocks more specifically, you can configure the |
| 367 |
> `pymdownx.highlight` extension to use Pygments and set language classes |
| 368 |
> on code blocks: |
| 369 |
> |
| 370 |
> ```yaml title="mkdocs.yml" |
| 371 |
> markdown_extensions: |
| 372 |
> - pymdownx.highlight: |
| 373 |
> use_pygments: true |
| 374 |
> pygments_lang_class: true |
| 375 |
> ``` |
| 376 |
> |
| 377 |
> Then you can update the CSS selector like this: |
| 378 |
> |
| 379 |
> ```css title="docs/css/code_select.css" |
| 380 |
> .language-pycon .gp, .language-pycon .go { /* Generic.Prompt, Generic.Output */ |
| 381 |
> user-select: none; |
| 382 |
> } |
| 383 |
> ``` |
| 384 |
|
| 385 |
If you don't want to enable this globally, |
| 386 |
you can still use `style` tags in the relevant pages, |
| 387 |
with more accurate CSS selectors: |
| 388 |
|
| 389 |
```html |
| 390 |
<style> |
| 391 |
#my-div .highlight .gp, #my-div .highlight .go { /* Generic.Prompt, Generic.Output */ |
| 392 |
user-select: none; |
| 393 |
} |
| 394 |
</style> |
| 395 |
``` |
| 396 |
|
| 397 |
Try to select the following code block's text: |
| 398 |
|
| 399 |
<style> |
| 400 |
.highlight .gp, .highlight .go { /* Generic.Prompt, Generic.Output */ |
| 401 |
user-select: none; |
| 402 |
} |
| 403 |
</style> |
| 404 |
|
| 405 |
```pycon |
| 406 |
>>> for word in ("Hello", "mkdocstrings!"): |
| 407 |
... print(word, end=" ") |
| 408 |
Hello mkdocstrings! |
| 409 |
``` |
| 410 |
|
| 411 |
## Hide documentation strings from source code blocks |
| 412 |
|
| 413 |
Since documentation strings are rendered by handlers, it can sometimes feel redundant to show these same documentation strings in source code blocks (when handlers render those). |
| 414 |
|
| 415 |
There is a general workaround to hide these docstrings from source blocks using CSS: |
| 416 |
|
| 417 |
```css |
| 418 |
/* These CSS classes depend on the handler. */ |
| 419 |
.doc-contents details .highlight code { |
| 420 |
line-height: 0; |
| 421 |
} |
| 422 |
.doc-contents details .highlight code > * { |
| 423 |
line-height: initial; |
| 424 |
} |
| 425 |
.doc-contents details .highlight code > .sd { /* Literal.String.Doc */ |
| 426 |
display: none; |
| 427 |
} |
| 428 |
``` |
| 429 |
|
| 430 |
Note that this is considered a workaround and not a proper solution, because it has side-effects like also removing blank lines. |
| 431 |
|
| 432 |
## Automatic highlighting for indented code blocks in docstrings |
| 433 |
|
| 434 |
Depending on the language used in your code base and the mkdocstrings handler used to document it, you might want to set a default syntax for code blocks added to your docstrings. For example, to default to the Python syntax: |
| 435 |
|
| 436 |
```yaml title="mkdocs.yml" |
| 437 |
markdown_extensions: |
| 438 |
- pymdownx.highlight: |
| 439 |
default_lang: python |
| 440 |
``` |
| 441 |
|
| 442 |
Then in your docstrings, indented code blocks will be highlighted as Python code: |
| 443 |
|
| 444 |
```python |
| 445 |
def my_function(): |
| 446 |
"""This is my function. |
| 447 |
|
| 448 |
The following code will be highlighted as Python: |
| 449 |
|
| 450 |
result = my_function() |
| 451 |
print(result) |
| 452 |
|
| 453 |
End of the docstring. |
| 454 |
""" |
| 455 |
pass |
| 456 |
``` |