Debian Codegraph @

docs/dev-guide/plugins.md

raw
1 # MkDocs Plugins
2
3 A Guide to installing, using and creating MkDocs Plugins
4
5 ---
6
7 ## Installing Plugins
8
9 Before a plugin can be used, it must be installed on the system. If you are
10 using a plugin which comes with MkDocs, then it was installed when you installed
11 MkDocs. However, to install third party plugins, you need to determine the
12 appropriate package name and install it using `pip`:
13
14 ```bash
15 pip install mkdocs-foo-plugin
16 ```
17
18 WARNING: Installing an MkDocs plugin means installing a Python package and executing any code that the author has put in there. So, exercise the usual caution; there's no attempt at sandboxing.
19
20 Once a plugin has been successfully installed, it is ready to use. It just needs
21 to be [enabled](#using-plugins) in the configuration file. The [Catalog]
22 repository has a large ranked list of plugins that you can install and use.
23
24 ## Using Plugins
25
26 The [`plugins`][config] configuration option should contain a list of plugins to
27 use when building the site. Each "plugin" must be a string name assigned to the
28 plugin (see the documentation for a given plugin to determine its "name"). A
29 plugin listed here must already be [installed](#installing-plugins).
30
31 ```yaml
32 plugins:
33 - search
34 ```
35
36 Some plugins may provide configuration options of their own. If you would like
37 to set any configuration options, then you can nest a key/value mapping
38 (`option_name: option value`) of any options that a given plugin supports. Note
39 that a colon (`:`) must follow the plugin name and then on a new line the option
40 name and value must be indented and separated by a colon. If you would like to
41 define multiple options for a single plugin, each option must be defined on a
42 separate line.
43
44 ```yaml
45 plugins:
46 - search:
47 lang: en
48 foo: bar
49 ```
50
51 For information regarding the configuration options available for a given plugin,
52 see that plugin's documentation.
53
54 For a list of default plugins and how to override them, see the
55 [configuration][config] documentation.
56
57 ## Developing Plugins
58
59 Like MkDocs, plugins must be written in Python. It is generally expected that
60 each plugin would be distributed as a separate Python module, although it is
61 possible to define multiple plugins in the same module. At a minimum, a MkDocs
62 Plugin must consist of a [BasePlugin] subclass and an [entry point] which
63 points to it.
64
65 ### BasePlugin
66
67 A subclass of `mkdocs.plugins.BasePlugin` should define the behavior of the plugin.
68 The class generally consists of actions to perform on specific events in the build
69 process as well as a configuration scheme for the plugin.
70
71 All `BasePlugin` subclasses contain the following attributes:
72
73 #### config_scheme
74
75 A tuple of configuration validation instances. Each item must consist of a
76 two item tuple in which the first item is the string name of the
77 configuration option and the second item is an instance of
78 `mkdocs.config.config_options.BaseConfigOption` or any of its subclasses.
79
80 For example, the following `config_scheme` defines three configuration options: `foo`, which accepts a string; `bar`, which accepts an integer; and `baz`, which accepts a boolean value.
81
82 ```python
83 class MyPlugin(mkdocs.plugins.BasePlugin):
84 config_scheme = (
85 ('foo', mkdocs.config.config_options.Type(str, default='a default value')),
86 ('bar', mkdocs.config.config_options.Type(int, default=0)),
87 ('baz', mkdocs.config.config_options.Type(bool, default=True))
88 )
89 ```
90
91 > NEW: **New in version 1.4.**
92 >
93 > ##### Subclassing `Config` to specify the config schema
94 >
95 > To get type safety benefits, if you're targeting only MkDocs 1.4+, define the config schema as a class instead:
96 >
97 > ```python
98 > class MyPluginConfig(mkdocs.config.base.Config):
99 > foo = mkdocs.config.config_options.Type(str, default='a default value')
100 > bar = mkdocs.config.config_options.Type(int, default=0)
101 > baz = mkdocs.config.config_options.Type(bool, default=True)
102 >
103 > class MyPlugin(mkdocs.plugins.BasePlugin[MyPluginConfig]):
104 > ...
105 > ```
106
107 ##### Examples of config definitions
108
109 >! EXAMPLE:
110 >
111 > ```python
112 > from mkdocs.config import base, config_options as c
113 >
114 > class _ValidationOptions(base.Config):
115 > enabled = c.Type(bool, default=True)
116 > verbose = c.Type(bool, default=False)
117 > skip_checks = c.ListOfItems(c.Choice(('foo', 'bar', 'baz')), default=[])
118 >
119 > class MyPluginConfig(base.Config):
120 > definition_file = c.File(exists=True) # required
121 > checksum_file = c.Optional(c.File(exists=True)) # can be None but must exist if specified
122 > validation = c.SubConfig(_ValidationOptions)
123 > ```
124 >
125 > From the user's point of view `SubConfig` is similar to `Type(dict)`, it's just that it also retains full ability for validation: you define all valid keys and what each value should adhere to.
126 >
127 > And `ListOfItems` is similar to `Type(list)`, but again, we define the constraint that each value must adhere to.
128 >
129 > This accepts a config as follows:
130 >
131 > ```yaml
132 > my_plugin:
133 > definition_file: configs/test.ini # relative to mkdocs.yml
134 > validation:
135 > enabled: !ENV [CI, false]
136 > verbose: true
137 > skip_checks:
138 > - foo
139 > - baz
140 > ```
141 <!-- -->
142 >? EXAMPLE:
143 >
144 > ```python
145 > import numbers
146 > from mkdocs.config import base, config_options as c
147 >
148 > class _Rectangle(base.Config):
149 > width = c.Type(numbers.Real) # required
150 > height = c.Type(numbers.Real) # required
151 >
152 > class MyPluginConfig(base.Config):
153 > add_rectangles = c.ListOfItems(c.SubConfig(_Rectangle)) # required
154 > ```
155 >
156 > In this example we define a list of complex items, and that's achieved by passing a concrete `SubConfig` to `ListOfItems`.
157 >
158 > This accepts a config as follows:
159 >
160 > ```yaml
161 > my_plugin:
162 > add_rectangles:
163 > - width: 5
164 > height: 7
165 > - width: 12
166 > height: 2
167 > ```
168
169 When the user's configuration is loaded, the above scheme will be used to
170 validate the configuration and fill in any defaults for settings not
171 provided by the user. The validation classes may be any of the classes
172 provided in `mkdocs.config.config_options` or a third party subclass defined
173 in the plugin.
174
175 Any settings provided by the user which fail validation or are not defined
176 in the `config_scheme` will raise a `mkdocs.config.base.ValidationError`.
177
178 #### config
179
180 A dictionary of configuration options for the plugin, which is populated by
181 the `load_config` method after configuration validation has completed. Use
182 this attribute to access options provided by the user.
183
184 ```python
185 def on_pre_build(self, config, **kwargs):
186 if self.config['baz']:
187 # implement "baz" functionality here...
188 ```
189
190 > NEW: **New in version 1.4.**
191 >
192 > ##### Safe attribute-based access
193 >
194 > To get type safety benefits, if you're targeting only MkDocs 1.4+, access options as attributes instead:
195 >
196 > ```python
197 > def on_pre_build(self, config, **kwargs):
198 > if self.config.baz:
199 > print(self.config.bar ** 2) # OK, `int ** 2` is valid.
200 > ```
201
202 All `BasePlugin` subclasses contain the following method(s):
203
204 #### load_config(options)
205
206 Loads configuration from a dictionary of options. Returns a tuple of
207 `(errors, warnings)`. This method is called by MkDocs during configuration
208 validation and should not need to be called by the plugin.
209
210 #### on_&lt;event_name&gt;()
211
212 Optional methods which define the behavior for specific [events]. The plugin
213 should define its behavior within these methods. Replace `<event_name>` with
214 the actual name of the event. For example, the `pre_build` event would be
215 defined in the `on_pre_build` method.
216
217 Most events accept one positional argument and various keyword arguments. It
218 is generally expected that the positional argument would be modified (or
219 replaced) by the plugin and returned. If nothing is returned (the method
220 returns `None`), then the original, unmodified object is used. The keyword
221 arguments are simply provided to give context and/or supply data which may
222 be used to determine how the positional argument should be modified. It is
223 good practice to accept keyword arguments as `**kwargs`. In the event that
224 additional keywords are provided to an event in a future version of MkDocs,
225 there will be no need to alter your plugin.
226
227 For example, the following event would add an additional static_template to
228 the theme config:
229
230 ```python
231 class MyPlugin(BasePlugin):
232 def on_config(self, config, **kwargs):
233 config['theme'].static_templates.add('my_template.html')
234 return config
235 ```
236
237 > NEW: **New in version 1.4.**
238 >
239 > To get type safety benefits, if you're targeting only MkDocs 1.4+, access config options as attributes instead:
240 >
241 > ```python
242 > def on_config(self, config: MkDocsConfig):
243 > config.theme.static_templates.add('my_template.html')
244 > return config
245 > ```
246
247 ### Events
248
249 There are three kinds of events: [Global Events], [Page Events] and
250 [Template Events].
251
252 <details class="card">
253 <summary>
254 See a diagram with relations between all the plugin events
255 </summary>
256 <div class="card-body">
257 <ul>
258 <li>The events themselves are shown in yellow, with their parameters.
259 <li>Arrows show the flow of arguments and outputs of each event.
260 Sometimes they're omitted.
261 <li>The events are chronologically ordered from top to bottom.
262 <li>Dotted lines appear at splits from global events to per-page events.
263 <li>Click the events' titles to jump to their description.
264 </ul>
265 --8<-- "docs/img/plugin-events.svg"
266 </div>
267 </details>
268 <br>
269
270 #### One-time Events
271
272 One-time events run once per `mkdocs` invocation. The only case where these tangibly differ from [global events](#global-events) is for `mkdocs serve`: global events, unlike these, will run multiple times -- once per *build*.
273
274 ##### on_startup
275
276 ::: mkdocs.plugins.BasePlugin.on_startup
277 options:
278 show_root_heading: false
279 show_root_toc_entry: false
280
281 ##### on_shutdown
282
283 ::: mkdocs.plugins.BasePlugin.on_shutdown
284 options:
285 show_root_heading: false
286 show_root_toc_entry: false
287
288 ##### on_serve
289
290 ::: mkdocs.plugins.BasePlugin.on_serve
291 options:
292 show_root_heading: false
293 show_root_toc_entry: false
294
295 #### Global Events
296
297 Global events are called once per build at either the beginning or end of the
298 build process. Any changes made in these events will have a global effect on the
299 entire site.
300
301 ##### on_config
302
303 ::: mkdocs.plugins.BasePlugin.on_config
304 options:
305 show_root_heading: false
306 show_root_toc_entry: false
307
308 ##### on_pre_build
309
310 ::: mkdocs.plugins.BasePlugin.on_pre_build
311 options:
312 show_root_heading: false
313 show_root_toc_entry: false
314
315 ##### on_files
316
317 ::: mkdocs.plugins.BasePlugin.on_files
318 options:
319 show_root_heading: false
320 show_root_toc_entry: false
321
322 ##### on_nav
323
324 ::: mkdocs.plugins.BasePlugin.on_nav
325 options:
326 show_root_heading: false
327 show_root_toc_entry: false
328
329 ##### on_env
330
331 ::: mkdocs.plugins.BasePlugin.on_env
332 options:
333 show_root_heading: false
334 show_root_toc_entry: false
335
336 ##### on_post_build
337
338 ::: mkdocs.plugins.BasePlugin.on_post_build
339 options:
340 show_root_heading: false
341 show_root_toc_entry: false
342
343 ##### on_build_error
344
345 ::: mkdocs.plugins.BasePlugin.on_build_error
346 options:
347 show_root_heading: false
348 show_root_toc_entry: false
349
350 #### Template Events
351
352 Template events are called once for each non-page template. Each template event
353 will be called for each template defined in the [extra_templates] config setting
354 as well as any [static_templates] defined in the theme. All template events are
355 called after the [env] event and before any [page events].
356
357 ##### on_pre_template
358
359 ::: mkdocs.plugins.BasePlugin.on_pre_template
360 options:
361 show_root_heading: false
362 show_root_toc_entry: false
363
364 ##### on_template_context
365
366 ::: mkdocs.plugins.BasePlugin.on_template_context
367 options:
368 show_root_heading: false
369 show_root_toc_entry: false
370
371 ##### on_post_template
372
373 ::: mkdocs.plugins.BasePlugin.on_post_template
374 options:
375 show_root_heading: false
376 show_root_toc_entry: false
377
378 #### Page Events
379
380 Page events are called once for each Markdown page included in the site. All
381 page events are called after the [post_template] event and before the
382 [post_build] event.
383
384 ##### on_pre_page
385
386 ::: mkdocs.plugins.BasePlugin.on_pre_page
387 options:
388 show_root_heading: false
389 show_root_toc_entry: false
390
391 ##### on_page_read_source
392
393 ::: mkdocs.plugins.BasePlugin.on_page_read_source
394 options:
395 show_root_heading: false
396 show_root_toc_entry: false
397
398 ##### on_page_markdown
399
400 ::: mkdocs.plugins.BasePlugin.on_page_markdown
401 options:
402 show_root_heading: false
403 show_root_toc_entry: false
404
405 ##### on_page_content
406
407 ::: mkdocs.plugins.BasePlugin.on_page_content
408 options:
409 show_root_heading: false
410 show_root_toc_entry: false
411
412 ##### on_page_context
413
414 ::: mkdocs.plugins.BasePlugin.on_page_context
415 options:
416 show_root_heading: false
417 show_root_toc_entry: false
418
419 ##### on_post_page
420
421 ::: mkdocs.plugins.BasePlugin.on_post_page
422 options:
423 show_root_heading: false
424 show_root_toc_entry: false
425
426 ### Event Priorities
427
428 For each event type, corresponding methods of plugins are called in the order that the plugins appear in the `plugins` [config][].
429
430 Since MkDocs 1.4, plugins can choose to set a priority value for their events. Events with higher priority are called first. Events without a chosen priority get a default of 0. Events that have the same priority are ordered as they appear in the config.
431
432 #### ::: mkdocs.plugins.event_priority
433
434 > NEW: **New in version 1.6**
435 >
436 > There may also arise a need to register a handler for the same event at multiple different priorities.
437 >
438 > `CombinedEvent` makes this possible.
439 >
440 > #### ::: mkdocs.plugins.CombinedEvent
441
442 ### Handling Errors
443
444 MkDocs defines four error types:
445
446 #### ::: mkdocs.exceptions.MkDocsException
447
448 #### ::: mkdocs.exceptions.ConfigurationError
449
450 #### ::: mkdocs.exceptions.BuildError
451
452 #### ::: mkdocs.exceptions.PluginError
453
454 Unexpected and uncaught exceptions will interrupt the build process and produce
455 typical Python tracebacks, which are useful for debugging your code. However,
456 users generally find tracebacks overwhelming and often miss the helpful error
457 message. Therefore, MkDocs will catch any of the errors listed above, retrieve
458 the error message, and exit immediately with only the helpful message displayed
459 to the user.
460
461 Therefore, you might want to catch any exceptions within your plugin and raise a
462 `PluginError`, passing in your own custom-crafted message, so that the build
463 process is aborted with a helpful message.
464
465 The [on_build_error] event will be triggered for any exception.
466
467 For example:
468
469 ```python
470 from mkdocs.exceptions import PluginError
471 from mkdocs.plugins import BasePlugin
472
473
474 class MyPlugin(BasePlugin):
475 def on_post_page(self, output, page, config, **kwargs):
476 try:
477 # some code that could throw a KeyError
478 ...
479 except KeyError as error:
480 raise PluginError(f"Failed to find the item by key: '{error}'")
481
482 def on_build_error(self, error, **kwargs):
483 # some code to clean things up
484 ...
485 ```
486
487 ### Logging in plugins
488
489 To ensure that your plugins' log messages adhere with MkDocs' formatting and `--verbose`/`--debug` flags, please write the logs to a logger under the `mkdocs.plugins.` namespace.
490
491 > EXAMPLE:
492 >
493 > ```python
494 > import logging
495 >
496 > log = logging.getLogger(f"mkdocs.plugins.{__name__}")
497 >
498 > log.warning("File '%s' not found. Breaks the build if --strict is passed", my_file_name)
499 > log.info("Shown normally")
500 > log.debug("Shown only with `--verbose`")
501 >
502 > if log.getEffectiveLevel() <= logging.DEBUG:
503 > log.debug("Very expensive calculation only for debugging: %s", get_my_diagnostics())
504 > ```
505
506 `log.error()` is another logging level that is differentiated by its look, but in all other ways it functions the same as `warning`, so it's strange to use it. If your plugin encounters an actual error, it is best to just interrupt the build by raising [`mkdocs.exceptions.PluginError`][] (which will also log an ERROR message).
507
508 <!-- -->
509 > NEW: **New in version 1.5**
510 >
511 > MkDocs now provides a `get_plugin_logger()` convenience function that returns a logger like the above that is also prefixed with the plugin's name.
512 >
513 > #### ::: mkdocs.plugins.get_plugin_logger
514
515 ### Entry Point
516
517 Plugins need to be packaged as Python libraries (distributed on PyPI separate
518 from MkDocs) and each must register as a Plugin via a setuptools `entry_points`.
519 Add the following to your `setup.py` script:
520
521 ```python
522 entry_points={
523 'mkdocs.plugins': [
524 'pluginname = path.to.some_plugin:SomePluginClass',
525 ]
526 }
527 ```
528
529 The `pluginname` would be the name used by users (in the config file) and
530 `path.to.some_plugin:SomePluginClass` would be the importable plugin itself
531 (`from path.to.some_plugin import SomePluginClass`) where `SomePluginClass` is a
532 subclass of [BasePlugin] which defines the plugin behavior. Naturally, multiple
533 Plugin classes could exist in the same module. Simply define each as a separate
534 entry point.
535
536 ```python
537 entry_points={
538 'mkdocs.plugins': [
539 'featureA = path.to.my_plugins:PluginA',
540 'featureB = path.to.my_plugins:PluginB'
541 ]
542 }
543 ```
544
545 Note that registering a plugin does not activate it. The user still needs to
546 tell MkDocs to use it via the config.
547
548 ### Publishing a Plugin
549
550 You should publish a package on [PyPI], then add it to the [Catalog] for discoverability. Plugins are strongly recommended to have a unique plugin name (entry point name) according to the catalog.
551
552 [BasePlugin]:#baseplugin
553 [config]: ../user-guide/configuration.md#plugins
554 [entry point]: #entry-point
555 [env]: #on_env
556 [events]: #events
557 [extra_templates]: ../user-guide/configuration.md#extra_templates
558 [Global Events]: #global-events
559 [Page Events]: #page-events
560 [post_build]: #on_post_build
561 [post_template]: #on_post_template
562 [static_templates]: ../user-guide/configuration.md#static_templates
563 [Template Events]: #template-events
564 [catalog]: https://github.com/mkdocs/catalog
565 [on_build_error]: #on_build_error
566 [PyPI]: https://pypi.org/