-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllms-full.txt
3624 lines (2208 loc) Β· 94.3 KB
/
llms-full.txt
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mkdocstrings
Automatic documentation from sources, for [MkDocs](https://www.mkdocs.org/). Come have a chat or ask questions on our [Gitter channel](https://gitter.im/mkdocstrings/community).
______________________________________________________________________
**[Features](#features)** - **[Installation](#installation)** - **[Quick usage](#quick-usage)**
## Features
- [**Language-agnostic:**](https://mkdocstrings.github.io/handlers/overview/) just like *MkDocs*, *mkdocstrings* is written in Python but is language-agnostic. It means you can use it with any programming language, as long as there is a [**handler**](https://mkdocstrings.github.io/reference/handlers/base/) for it. We currently have [handlers](https://mkdocstrings.github.io/handlers/overview/) for the [C](https://mkdocstrings.github.io/c/), [Crystal](https://mkdocstrings.github.io/crystal/), [Python](https://mkdocstrings.github.io/python/), [TypeScript](https://mkdocstrings.github.io/typescript/), and [VBA](https://pypi.org/project/mkdocstrings-vba/) languages, as well as for [shell scripts/libraries](https://mkdocstrings.github.io/shell/). Maybe you'd like to add another one to the list?
- [**Multiple themes support:**](https://mkdocstrings.github.io/theming/) each handler can offer multiple themes. Currently, we offer the [Material theme](https://squidfunk.github.io/mkdocs-material/) as well as basic support for the ReadTheDocs and MkDocs themes for the Python handler.
- [**Cross-references across pages:**](https://mkdocstrings.github.io/usage/#cross-references) *mkdocstrings* makes it possible to reference headings in other Markdown files with the classic Markdown linking syntax: `[identifier][]` or `[title][identifier]` -- and you don't need to remember which exact page this object was on. This works for any heading that's produced by a *mkdocstrings* language handler, and you can opt to include *any* Markdown heading into the global referencing scheme.
**Note**: in versions prior to 0.15 *all* Markdown headers were included, but now you need to [opt in](https://mkdocstrings.github.io/usage/#cross-references-to-any-markdown-heading).
- [**Cross-references across sites:**](https://mkdocstrings.github.io/usage/#cross-references-to-other-projects-inventories) similarly to [Sphinx's intersphinx extension](https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html), *mkdocstrings* can reference API items from other libraries, given they provide an inventory and you load that inventory in your MkDocs configuration.
- [**Inline injection in Markdown:**](https://mkdocstrings.github.io/usage/) instead of generating Markdown files, *mkdocstrings* allows you to inject documentation anywhere in your Markdown contents. The syntax is simple: `::: identifier` followed by a 4-spaces indented YAML block. The identifier and YAML configuration will be passed to the appropriate handler to collect and render documentation.
- [**Global and local configuration:**](https://mkdocstrings.github.io/usage/#global-options) each handler can be configured globally in `mkdocs.yml`, and locally for each "autodoc" instruction.
- **Reasonable defaults:** you should be able to just drop the plugin in your configuration and enjoy your auto-generated docs.
## Used by
*mkdocstrings* is used by well-known companies, projects and scientific teams: [Ansible](https://molecule.readthedocs.io/configuration/), [Apache](https://streampipes.apache.org/docs/docs/python/latest/reference/client/client/), [FastAPI](https://fastapi.tiangolo.com/reference/fastapi/), [Google](https://docs.kidger.site/jaxtyping/api/runtime-type-checking/), [IBM](https://ds4sd.github.io/docling/api_reference/document_converter/), [Jitsi](https://jitsi.github.io/jiwer/reference/alignment/), [Microsoft](https://microsoft.github.io/presidio/api/analyzer_python/), [NVIDIA](https://nvidia.github.io/bionemo-framework/API_reference/bionemo/core/api/), [Prefect](https://docs.prefect.io/2.10.12/api-ref/prefect/agent/), [Pydantic](https://docs.pydantic.dev/dev-v2/api/main/), [Textual](https://textual.textualize.io/api/app/), [and more...](https://github.com/mkdocstrings/mkdocstrings/network/dependents)
## Installation
The `mkdocstrings` package doesn't provide support for any language: it's just a common base for language handlers. It means you likely want to install it with one or more official handlers, using [extras](https://packaging.python.org/en/latest/specifications/dependency-specifiers/#extras). For example, to install it with Python support:
```bash
pip install 'mkdocstrings[python]'
```
Alternatively, you can directly install the language handlers themselves, which depend on `mkdocstrings` anyway:
```bash
pip install mkdocstrings-python
```
This will give you more control over the accepted range of versions for the handlers themselves.
See the [official language handlers](https://mkdocstrings.github.io/handlers/overview/).
______________________________________________________________________
With `conda`:
```bash
conda install -c conda-forge mkdocstrings mkdocstrings-python
```
## Quick usage
In `mkdocs.yml`:
```yaml
site_name: "My Library"
theme:
name: "material"
plugins:
- search
- mkdocstrings
```
In one of your markdown files:
```markdown
# Reference
::: my_library.my_module.my_class
```
See the [Usage](https://mkdocstrings.github.io/usage) section of the docs for more examples!
# Usage
## Autodoc syntax
*mkdocstrings* works by processing special expressions in your Markdown files.
The syntax is as follows:
```md
::: identifier
YAML block
```
Resources on YAML.
YAML can sometimes be a bit tricky, particularly on indentation. Here are some resources that other users found useful to better understand YAML's peculiarities.
- [YAML idiosyncrasies](https://salt-zh.readthedocs.io/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html)
- [YAML multiline](https://yaml-multiline.info/)
The `identifier` is a string identifying the object you want to document. The format of an identifier can vary from one handler to another. For example, the Python handler expects the full dotted-path to a Python object: `my_package.my_module.MyClass.my_method`.
The YAML block is optional, and contains some configuration options:
- `handler`: the name of the handler to use to collect and render this object. By default, it will use the value defined in the [Global options](#global-options)'s `default_handler` key, or `"python"`.
- `options`: a dictionary of options passed to the handler's methods responsible both for collecting and rendering the documentation. These options can be defined globally (in `mkdocs.yml`, see [Global options](#global-options)), locally (as described here), or both.
Example with the Python handler
```md
# Documentation for `MyClass`
::: my_package.my_module.MyClass
handler: python
options:
members:
- method_a
- method_b
show_root_heading: false
show_source: false
```
```yaml
nav:
- "My page": my_page.md
```
```python
class MyClass:
"""Print print print!"""
def method_a(self):
"""Print A!"""
print("A!")
def method_b(self):
"""Print B!"""
print("B!")
def method_c(self):
"""Print C!"""
print("C!")
```
### Documentation for `MyClass`
Print print print!
#### `method_a(self)`
Print A!
#### `method_b(self)`
Print B!
It is also possible to integrate a mkdocstrings identifier into a Markdown header:
```md
## ::: my_package.my_module.MyClass
options:
show_source: false
```
The above is equivalent to:
```md
::: my_package.my_module.MyClass
options:
show_source: false
heading_level: 2
```
## Global options
*mkdocstrings* accepts a few top-level configuration options in `mkdocs.yml`:
- `default_handler`: The handler that is used by default when no handler is specified.
- `custom_templates`: The path to a directory containing custom templates. The path is relative to the MkDocs configuration file. See [Theming](theming/).
- `handlers`: The handlers' global configuration.
- `enable_inventory`: Whether to enable inventory file generation. See [Cross-references to other projects / inventories](#cross-references-to-other-projects-inventories)
- `enabled` **(New in version 0.20)**: Whether to enable the plugin. Defaults to `true`. Can be used to reduce build times when doing local development. Especially useful when used with environment variables (see example below).
Example
mkdocs.yml
```yaml
plugins:
- mkdocstrings:
enabled: !ENV [ENABLE_MKDOCSTRINGS, true]
custom_templates: templates
default_handler: python
handlers:
python:
options:
show_source: false
```
The handlers global configuration can then be overridden by local configurations:
docs/some_page.md
```yaml
::: my_package.my_module.MyClass
options:
show_source: true
```
Some handlers accept additional global configuration. Check the documentation for your handler of interest in [Handlers](handlers/).
## Cross-references
Cross-references are written as Markdown *reference-style* links:
```md
With a custom title:
[`Object 1`][full.path.object1]
With the identifier as title:
[full.path.object2][]
```
```html
<p>With a custom title:
<a href="https://example.com/page1#full.path.object1"><code>Object 1</code></a><p>
<p>With the identifier as title:
<a href="https://example.com/page2#full.path.object2">full.path.object2</a></p>
```
Any item that was inserted using the [autodoc syntax](#autodoc-syntax) (e.g. `::: full.path.object1`) is possible to link to by using the same identifier with the cross-reference syntax (`[example][full.path.object1]`). But the cross-references are also applicable to the items' children that get pulled in.
### Finding out the anchor
If you're not sure which exact identifier a doc item uses, you can look at its "anchor", which your Web browser will show in the URL bar when clicking an item's entry in the table of contents. If the URL is `https://example.com/some/page.html#full.path.object1` then you know that this item is possible to link to with `[example][full.path.object1]`, regardless of the current page.
### Cross-references to any Markdown heading
Changed in version 0.15.
Linking to any Markdown heading used to be the default, but now opt-in is required.
If you want to link to *any* Markdown heading, not just *mkdocstrings*-inserted items, please enable the [*autorefs* plugin for *MkDocs*](https://github.com/mkdocstrings/autorefs) by adding `autorefs` to `plugins`:
mkdocs.yml
```yaml
plugins:
- search
- autorefs
- mkdocstrings:
[...]
```
Note that you don't need to (`pip`) install anything more; this plugin is guaranteed to be pulled in with *mkdocstrings*.
Example
```md
## Hello, world!
Testing
```
```md
## Something else
Please see the [Hello, World!][hello-world] section.
```
```html
<p>Please see the <a href="doc1.html#hello-world">Hello, World!</a> section.</p>
```
### Cross-references to a sub-heading in a docstring
New in version 0.14.
If you have a Markdown heading *inside* your docstring, you can also link directly to it. In the example below you see the identifier to be linked is `foo.bar--tips`, because it's the "Tips" heading that's part of the `foo.bar` object, joined with "`--`".
Example
```python
def bar():
"""Hello, world!
# Tips
- Stay hydrated.
"""
```
```md
::: foo.bar
```
```md
Check out the [tips][foo.bar--tips]
```
```html
<p>Check out the <a href="doc1.html#foo.bar--tips">tips</a></p>
```
The above tip about [Finding out the anchor](#finding-out-the-anchor) also applies the same way here.
You may also notice that such a heading does not get rendered as a `<h1>` element directly, but rather the level gets shifted to fit the encompassing document structure. If you're curious about the implementation, check out mkdocstrings.HeadingShiftingTreeprocessor and others.
### Cross-references to other projects / inventories
New in version 0.16.
Python developers coming from Sphinx might know about its `intersphinx` extension, that allows to cross-reference items between several projects. *mkdocstrings* has a similar feature.
To reference an item from another project, you must first tell *mkdocstrings* to load the inventory it provides. Each handler will be responsible of loading inventories specific to its language. For example, the Python handler can load Sphinx-generated inventories (`objects.inv`).
In the following snippet, we load the inventory provided by `installer`:
mkdocs.yml
```yaml
plugins:
- mkdocstrings:
handlers:
python:
inventories:
- https://installer.readthedocs.io/en/stable/objects.inv
```
Now it is possible to cross-reference `installer`'s items. For example:
```md
See [installer.records][] to learn about records.
```
```html
<p>See <a href="https://installer.readthedocs.io/en/stable/api/records/#module-installer.records">installer.records</a>
to learn about records.</p>
```
See installer.records to learn about records.
You can of course select another version of the inventory, for example:
```yaml
plugins:
- mkdocstrings:
handlers:
python:
inventories:
# latest instead of stable
- https://installer.readthedocs.io/en/latest/objects.inv
```
In case the inventory file is not served under the base documentation URL, you can explicitly specify both URLs:
```yaml
plugins:
- mkdocstrings:
handlers:
python:
inventories:
- url: https://cdn.example.com/version/objects.inv
base_url: https://docs.example.com/version
```
Absolute URLs to cross-referenced items will then be based on `https://docs.example.com/version/` instead of `https://cdn.example.com/version/`.
If you need authentication to access the inventory file, you can provide the credentials in the URL, either as `username:password`:
```yaml
- url: https://username:[email protected]/version/objects.inv
```
...or with token authentication:
```yaml
- url: https://[email protected]/version/objects.inv
```
The credentials can also be specified using environment variables in the form `${ENV_VAR}`:
```yaml
- url: https://${USERNAME}:${PASSWORD}@private.example.com/version/objects.inv
```
Reciprocally, *mkdocstrings* also allows to *generate* an inventory file in the Sphinx format. It will be enabled by default if the Python handler is used, and generated as `objects.inv` in the final site directory. Other projects will be able to cross-reference items from your project.
To explicitly enable or disable the generation of the inventory file, use the global `enable_inventory` option:
```yaml
plugins:
- mkdocstrings:
enable_inventory: false
```
# Handlers
A handler is what makes it possible to collect and render documentation for a particular language.
## Available handlers
- [C](https://mkdocstrings.github.io/c/)
- [Crystal](https://mkdocstrings.github.io/crystal/)
- [Python](https://mkdocstrings.github.io/python/)
- [Python (Legacy)](https://mkdocstrings.github.io/python-legacy/)
- [Shell](https://mkdocstrings.github.io/shell/)
- [TypeScript](https://mkdocstrings.github.io/typescript/)
- [VBA](https://pypi.org/project/mkdocstrings-vba/)
## About the Python handlers
Since version 0.18, a new Python handler is available. It is based on [Griffe](https://github.com/mkdocstrings/griffe), which is an improved version of [pytkdocs](https://github.com/mkdocstrings/pytkdocs).
If you want to keep using the legacy handler as long as possible, you can depend on `mkdocstrings-python-legacy` directly, or specify the `python-legacy` extra when depending on *mkdocstrings*:
pyproject.toml
```toml
# PEP 621 dependencies declaration
# adapt to your dependencies manager
[project]
dependencies = [
"mkdocstrings[python-legacy]>=0.18",
]
```
The legacy handler will continue to "work" for many releases, as long as the new handler does not cover all previous use-cases.
### Migrate to the new Python handler
To use the new Python handler, you can depend on `mkdocstrings-python` directly, or specify the `python` extra when depending on *mkdocstrings*:
pyproject.toml
```toml
# PEP 621 dependencies declaration
# adapt to your dependencies manager
[project]
dependencies = [
"mkdocstrings[python]>=0.18",
]
```
#### Selection options
Warning
Since *mkdocstrings* 0.19, the YAML `selection` key is merged into the `options` key.
- `filters` is implemented, and used as before.
- `members` is implemented, and used as before.
- `inherited_members` is implemented.
- `docstring_style` is implemented, and used as before, except for the `restructured-text` style which is renamed `sphinx`. Numpy-style is now built-in, so you can stop depending on `pytkdocs[numpy-style]` or `docstring_parser`.
- `docstring_options` is implemented, and used as before. Refer to the [`griffe` documentation](https://mkdocstrings.github.io/griffe/docstrings/#parsing-options) for the updated list of supported docstring options.
- `new_path_syntax` is irrelevant now. If you were setting it to True, remove the option and replace every colon (`:`) in your autodoc identifiers by dots (`.`).
See [all the handler's options](https://mkdocstrings.github.io/python/usage/).
#### Rendering options
Warning
Since *mkdocstrings* 0.19, the YAML `rendering` key is merged into the `options` key.
Every previous option is supported. Additional options are available:
- `separate_signature`: Render the signature (or attribute value) in a code block below the heading, instead as inline code. Useful for long signatures. If Black is installed, the signature is formatted. Default: `False`.
- `line_length`: The maximum line length to use when formatting signatures. Default: `60`.
- `show_submodules`: Whether to render submodules of a module when iterating on children. Default: `False`.
- `docstring_section_style`: The style to use to render docstring sections such as attributes, parameters, etc. Available styles: `"table"` (default), `"list"` and `"spacy"`. The SpaCy style is a poor implementation of their [table style](https://spacy.io/api/doc/#init). We are open to improvements through PRs!
See [all the handler's options](https://mkdocstrings.github.io/python/usage/).
#### Templates
Templates are mostly the same as before, but the file layout has changed, as well as some file names. See [the documentation about the Python handler templates](https://mkdocstrings.github.io/python/usage/customization/#templates).
## Custom handlers
Since version 0.14, you can create and use custom handlers thanks to namespace packages. For more information about namespace packages, [see their documentation](https://packaging.python.org/guides/packaging-namespace-packages/).
TL;DR - Project template for handlers.
*mkdocstrings* provides a [Copier](https://github.com/copier-org/copier) template to kickstart new handlers: <https://github.com/mkdocstrings/handler-template>. To use it, install Copier (`pipx install copier`), then run `copier gh:mkdocstrings/handler-template my_handler` to generate a new project. See [its upstream documentation](https://pawamoy.github.io/copier-pdm/) to learn how to work on the generated project.
### Packaging
For *mkdocstrings*, a custom handler package would have the following structure:
```text
π your_repository
βββ΄π mkdocstrings_handlers
βββ΄π custom_handler
βββ΄π templates
βΒ βββ΄π material
β βββ΄π mkdocs
β βββ΄π readthedocs
βββ΄π __init__.py
```
Note the absence of `__init__.py` module in `mkdocstrings_handlers`!
### Code
A handler is a subclass of the base handler provided by *mkdocstrings*. See the documentation for the BaseHandler.
Subclasses of the base handler must declare a `name` and `domain` as class attributes, as well as implement the following methods:
- `collect(identifier, options)` (**required**): method responsible for collecting and returning data (extracting documentation from source code, loading introspecting objects in memory, other sources? etc.)
- `render(identifier, options)` (**required**): method responsible for actually rendering the data to HTML, using the Jinja templates provided by your package.
- `get_options(local_options)` (**required**): method responsible for combining global options with local ones.
- `get_aliases(identifier)` (**recommended**): method responsible for returning known aliases of object identifiers, in order to register cross-references in the autorefs plugin.
- `get_inventory_urls()` (optional): method responsible for returning a list of URLs to download (object inventories) along with configuration options (for loading the inventory with `load_inventory`).
- `load_inventory(in_file, url, **options)` (optional): method responsible for loading an inventory (binary file-handle) and yielding tuples of identifiers and URLs.
- `update_env(config)` (optional): Gives you a chance to customize the Jinja environment used to render templates, for examples by adding/removing Jinja filters and global context variables.
- `teardown()` (optional): Clean up / teardown anything that needs it at the end of the build.
You must implement a `get_handler` method at the module level, which returns an instance of your handler. This function takes the following parameters:
- `theme` (string, theme name)
- `custom_templates` (optional string, path to custom templates directory)
- `mdx` (list, Markdown extensions)
- `mdx_config` (dict, extensions configuration)
- `handler_config` (dict, handle configuration)
- `tool_config` (dict, the whole MkDocs configuration)
These arguments are all passed as keyword arguments, so you can ignore them by adding `**kwargs` or similar to your signature.
You should not modify the MkDocs config but can use it to get information about the MkDocs instance such as where the current `site_dir` lives. See the [Mkdocs Configuration](https://www.mkdocs.org/user-guide/configuration/) for more info about what is accessible from it.
Check out how the [Python handler](https://github.com/mkdocstrings/python/blob/master/src/mkdocstrings_handlers/python) is written for inspiration.
### Templates
Your handler's implementation should normally be backed by templates, which go to the directory `mkdocstrings_handlers/custom_handler/templates/some_theme` (`custom_handler` here should be replaced with the actual name of your handler, and `some_theme` should be the name of an actual MkDocs theme that you support, e.g. `material`).
With that structure, you can use `self.env.get_template("foo.html")` inside your `render` method. This already chooses the subdirectory based on the current MkDocs theme.
If you wish to support *any* MkDocs theme, rather than a few specifically selected ones, you can pick one theme's subdirectory to be the fallback for when an unknown theme is encountered. Then you just need to set the `fallback_theme` variable on your handler subclass. The fallback directory can be used even for themes you explicitly support: you can omit some template from one of the other theme directories in case they're exactly the same as in the fallback theme.
If your theme's HTML requires CSS to go along with it, put it into a file named `mkdocstrings_handlers/custom_handler/templates/some_theme/style.css`, then this will be included into the final site automatically if this handler is ever used. Alternatively, you can put the CSS as a string into the `extra_css` variable of your handler.
Finally, it's possible to entirely omit templates, and tell *mkdocstrings* to use the templates of another handler. In you handler, override the `get_templates_dir()` method to return the other handlers templates path:
```python
from pathlib import Path
from mkdocstrings.handlers.base import BaseHandler
class CobraHandler(BaseHandler):
def get_templates_dir(self, handler: str | None = None) -> Path:
# use the python handler templates
# (it assumes the python handler is installed)
return super().get_templates_dir("python")
```
### Usage
When a custom handler is installed, it is then available to *mkdocstrings*. You can configure it as usual:
mkdocs.yml
```yaml
plugins:
- mkdocstrings:
handlers:
custom_handler:
handler_config_option: yes
options:
some_config_option: "a"
other_config_option: 0
```
...and use it in your autodoc instructions:
docs/some_page.md
```md
# Documentation for an object
::: some.objects.path
handler: custom_handler
options:
some_config_option: "b"
other_config_option: 1
```
## Handler extensions
*mkdocstrings* provides a way for third-party packages to extend or alter the behavior of handlers. For example, an extension of the Python handler could add specific support for another Python library.
Note
This feature is intended for developers. If you are a user and want to customize how objects are rendered, see [Theming / Customization](../theming/#customization).
Such extensions can register additional template folders that will be used when rendering collected data. Extensions are responsible for synchronizing with the handler itself so that it uses the additional templates.
An extension is a Python package that defines an entry-point for a specific handler:
pyproject.toml
```toml
[project.entry-points."mkdocstrings.python.templates"] # (1)!
extension-name = "extension_package:get_templates_path" # (2)!
```
1. Replace `python` by the name of the handler you want to add templates to.
1. Replace `extension-name` by any name you want, and replace `extension_package:get_templates_path` by the actual module path and function name in your package.
This entry-point assumes that the extension provides a `get_templates_path` function directly under the `extension_package` package:
```bash
pyproject.toml
π extension_package/
βββ __init__.py
βββ π templates/
```
extension_package/__init__.py
```python
from pathlib import Path
def get_templates_path() -> Path:
return Path(__file__).parent / "templates"
```
This function doesn't accept any argument and returns the path (pathlib.Path or str) to a directory containing templates. The directory must contain one subfolder for each supported theme, even if empty (see "fallback theme" in [custom handlers templates](#templates_1)). For example:
```bash
pyproject.toml
π extension_package/
βββ __init__.py
βββ π templates/
βββ π material/
βββ π readthedocs/
βββ π mkdocs/
```
*mkdocstrings* will add the folders corresponding to the user-selected theme, and to the handler's defined fallback theme, as usual.
The names of the extension templates must not overlap with the handler's original templates.
The extension is then responsible, in collaboration with its target handler, for mutating the collected data in order to instruct the handler to use one of the extension template when rendering particular objects. See each handler's docs to see if they support extensions, and how.
# Themes
*mkdocstrings* can support multiple MkDocs themes. It currently supports the *[Material for MkDocs](https://squidfunk.github.io/mkdocs-material/)* theme and, partially, the built-in MkDocs and ReadTheDocs themes.
Each handler can fallback to a particular theme when the user selected theme is not supported. For example, the Python handler will fallback to the *Material for MkDocs* templates.
## Customization
There is some degree of customization possible in *mkdocstrings*. First, you can write custom templates to override the theme templates. Second, the provided templates make use of CSS classes, so you can tweak the look and feel with extra CSS rules.
### Templates
To use custom templates and override the theme ones, specify the relative path from your configuration file to your templates directory with the `custom_templates` global configuration option:
mkdocs.yml
```yaml
plugins:
- mkdocstrings:
custom_templates: templates
```
Your directory structure must be identical to the provided templates one:
```text
π templates/
βββ΄π <HANDLER 1>/
β βββ π <THEME 1>/
β βββ π <THEME 2>/
βββ π <HANDLER 2>/
βββ π <THEME 1>/
βββ π <THEME 2>/
```
For example, check out the Python [template tree](https://github.com/mkdocstrings/python/tree/master/src/mkdocstrings_handlers/python/templates/) on GitHub.
You don't have to replicate the whole tree, only the handlers, themes or templates you want to override. For example, to override some templates of the *Material* theme for Python:
```text
π templates/
βββ π python/
βββ π material/
βββ π parameters.html
βββ π exceptions.html
```
In the HTML files, replace the original contents with your modified version. In the future, the templates will use Jinja blocks, so it will be easier to modify small part of the templates without copy-pasting the whole files.
See the documentation about templates for:
- the Crystal handler: <https://mkdocstrings.github.io/crystal/styling.html>
- the Python handler: <https://mkdocstrings.github.io/python/usage/customization/#templates>
#### Debugging
Every template has access to a `log` function, allowing to log messages as usual:
```jinja
{{ log.debug("A DEBUG message.") }}
{{ log.info("An INFO message.") }}
{{ log.warning("A WARNING message.") }}
{{ log.error("An ERROR message.") }}
{{ log.critical("A CRITICAL message.") }}
```
### CSS classes
Since each handler provides its own set of templates, with their own CSS classes, we cannot list them all here. See the documentation about CSS classes for:
- the Crystal handler: <https://mkdocstrings.github.io/crystal/styling.html#custom-styles>
- the Python handler: <https://mkdocstrings.github.io/python/usage/customization/#css-classes>
### Syntax highlighting
Code blocks that occur in the docstring of an item inserted with *mkdocstrings*, as well as code blocks (such as *Source code*) that *mkdocstrings* inserts itself, are syntax-highlighted according to the same rules as other normal code blocks in your document. See more details in mkdocstrings.Highlighter.
As for the CSS class used for code blocks -- it will also match the "normal" config, so the default (`.codehilite` or `.highlight`) will match your chosen Markdown extension for highlighting.
Changed in version 0.15.
The CSS class used to always be `.highlight`, but now it depends on the configuration.
Long story short, you probably should add `pymdownx.highlight` to your `markdown_extensions`, and then use `.doc-contents .highlight` as the CSS selector in case you want to change something about *mkdocstrings'* code blocks specifically.
On this page you will find various recipes, tips and tricks for *mkdocstrings* and more generally Markdown documentation.
## Automatic code reference pages
[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.
*mkdocstrings* allows to inject documentation for any object into Markdown pages. But as the project grows, it quickly becomes quite tedious to keep the autodoc instructions, or even the dedicated Markdown files in sync with all your source files and objects.
In this recipe, we will iteratively automate the process of generating these pages at each build of the documentation.
______________________________________________________________________
Let say you have a project called `project`. This project has a lot of source files, or modules, which live in the `src` folder:
```bash
π repo/
βββ π src/
βββ π project/
βββ lorem
βββ ipsum
βββ dolor
βββ sit
βββ amet
```
Without an automatic process, you will have to manually create a Markdown page for each one of these modules, with the corresponding autodoc instruction, for example `::: project.lorem`, and also add entry in MkDocs' navigation option (`nav` in `mkdocs.yml`). With a lot of modules, this is quickly getting cumbersome.
Lets fix that.
### Generate pages on-the-fly
In this recipe, we suggest to use the [mkdocs-gen-files plugin](https://github.com/oprypin/mkdocs-gen-files). This plugin exposes utilities to generate files at build time. These files won't be written to the docs directory: you don't have to track and version them. They are transparently generated each time you build your docs. This is perfect for our use-case!
Add `mkdocs-gen-files` to your project's docs dependencies, and configure it like so:
mkdocs.yml
```yaml
plugins:
- search # (1)!
- gen-files:
scripts:
- scripts/gen_ref_pages.py # (2)!
- mkdocstrings
```
1. Don't forget to load the `search` plugin when redefining the `plugins` item.
1. The magic happens here, see below how it works.
mkdocs-gen-files is able to run Python scripts at build time. The Python script that we will execute lives in a scripts folder, and is named `gen_ref_pages.py`, like "generate code reference pages".
```bash
π repo/
βββ π docs/
β βββ index.md
βββ π scripts/
β βββ gen_ref_pages.py
βββ π src/
β βββ π project/
βββ mkdocs.yml
```
scripts/gen_ref_pages.py
```python
"""Generate the code reference pages."""
from pathlib import Path
import mkdocs_gen_files
root = Path(__file__).parent.parent
src = root / "src" # (1)!
for path in sorted(src.rglob("*.py")): # (2)!
module_path = path.relative_to(src).with_suffix("") # (3)!
doc_path = path.relative_to(src).with_suffix(".md") # (4)!
full_doc_path = Path("reference", doc_path) # (5)!
parts = tuple(module_path.parts)
if parts[-1] == "__init__": # (6)!
parts = parts[:-1]
elif parts[-1] == "__main__":
continue
with mkdocs_gen_files.open(full_doc_path, "w") as fd: # (7)!
identifier = ".".join(parts) # (8)!
print("::: " + identifier, file=fd) # (9)!
mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root)) # (10)!
```
1. It's important to build a path relative to the script itself, to make it possible to build the docs with MkDocs' [`-f` option](https://www.mkdocs.org/user-guide/cli/#mkdocs-build).
1. Here we recursively list all `.py` files, but you can adapt the code to list files with other extensions of course, supporting other languages than Python.
1. The module path will look like `project/lorem`. It will be used to build the *mkdocstrings* autodoc identifier.
1. This is the partial path of the Markdown page for the module.
1. This is the full path of the Markdown page within the docs. Here we put all reference pages into a `reference` folder.
1. This part is only relevant for Python modules. We skip `__main__` modules and remove `__init__` from the module parts as it's implicit during imports.
1. Magic! Add the file to MkDocs pages, without actually writing it in the docs folder.
1. Build the autodoc identifier. Here we document Python modules, so the identifier is a dot-separated path, like `project.lorem`.
1. Actually write to the magic file.
1. We can even set the `edit_uri` on the pages.
Note
It is important to look out for correct edit page behaviour when using generated pages. For example, if we have `edit_uri` set to `blob/master/docs/` and the following file structure:
```bash
π repo/
βββ mkdocs.yml
βββ π docs/
β βββ index.md
βββ π scripts/
β βββ gen_ref_pages.py
βββ π src/
βββ π project/
βββ lorem.py
βββ ipsum.py
βββ dolor.py
βββ sit.py
βββ amet.py
```
Then we will have to change our `set_edit_path` call to:
```python
mkdocs_gen_files.set_edit_path(full_doc_path, Path("../") / path) # (1)!
```
1. Path can be used to traverse the structure in any way you may need, but remember to use relative paths!
...so that it correctly sets the edit path of (for example) `lorem.py` to `<repo_url>/blob/master/src/project/lorem.py` instead of `<repo_url>/blob/master/docs/src/project/lorem.py`.
With this script, a `reference` folder is automatically created each time we build our docs. This folder contains a Markdown page for each of our source modules, and each of these pages contains a single line of the form `::: project.module` (module being `lorem`, `ipsum`, etc.). Great! But, we still have to actually add those pages into our MkDocs navigation:
mkdocs.yml
```yaml
nav:
# rest of the navigation...
- Code Reference:
- project:
- lorem: reference/project/lorem.md
- ipsum: reference/project/ipsum.md
- dolor: reference/project/dolor.md
- sit: reference/project/sit.md
- amet: reference/project/amet.md
# rest of the navigation...
```
Err... so this process is only semi-automatic? Yes, but don't worry, we can fully automate it.
### Generate a literate navigation file
mkdocs-gen-files is able to generate a literate navigation file. But to make use of it, we will need an additional plugin: [mkdocs-literate-nav](https://github.com/oprypin/mkdocs-literate-nav). This plugin allows to specify the whole navigation, or parts of it, into Markdown pages, as plain Markdown lists. We use it here to specify the navigation for the code reference pages.
First, add `mkdocs-literate-nav` to your project's docs dependencies, and configure the plugin in your MkDocs configuration:
mkdocs.yml
```yaml
plugins:
- search
- gen-files:
scripts:
- scripts/gen_ref_pages.py
- literate-nav:
nav_file: SUMMARY.md
- mkdocstrings
```
Then, the previous script is updated like so:
scripts/gen_ref_pages.py
```python
"""Generate the code reference pages and navigation."""
from pathlib import Path
import mkdocs_gen_files
nav = mkdocs_gen_files.Nav()
root = Path(__file__).parent.parent
src = root / "src"
for path in sorted(src.rglob("*.py")):
module_path = path.relative_to(src).with_suffix("")
doc_path = path.relative_to(src).with_suffix(".md")
full_doc_path = Path("reference", doc_path)
parts = tuple(module_path.parts)
if parts[-1] == "__init__":
parts = parts[:-1]
elif parts[-1] == "__main__":
continue
nav[parts] = doc_path.as_posix() # (1)!
with mkdocs_gen_files.open(full_doc_path, "w") as fd:
ident = ".".join(parts)
fd.write(f"::: {ident}")
mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root))
with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file: # (2)!
nav_file.writelines(nav.build_literate_nav()) # (3)!
```
1. Progressively build the navigation object.