2222from typing import TYPE_CHECKING , Any , BinaryIO , Callable , Iterable , List , Mapping , Tuple , TypeVar
2323from urllib import request
2424
25- from mkdocs .config . config_options import Type as MkType
26- from mkdocs .config . config_options import Dir , Optional
25+ from mkdocs .config import Config
26+ from mkdocs .config import config_options as opt
2727from mkdocs .plugins import BasePlugin
2828from mkdocs .utils import write_file
2929from mkdocs_autorefs .plugin import AutorefsPlugin
3434
3535if TYPE_CHECKING :
3636 from jinja2 .environment import Environment
37- from mkdocs .config import Config
3837 from mkdocs .config .defaults import MkDocsConfig
3938
4039if sys .version_info < (3 , 10 ):
@@ -63,38 +62,15 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
6362 return wrapper
6463
6564
66- class MkdocstringsPlugin (BasePlugin ):
67- """An `mkdocs` plugin.
68-
69- This plugin defines the following event hooks:
70-
71- - `on_config`
72- - `on_env`
73- - `on_post_build`
65+ class PluginConfig (Config ):
66+ """The configuration options of `mkdocstrings`, written in `mkdocs.yml`."""
7467
75- Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
76- for more information about its plugin system.
77- """
78-
79- config_scheme : tuple [tuple [str , MkType ]] = ( # type: ignore[assignment]
80- ("handlers" , MkType (dict , default = {})),
81- ("default_handler" , MkType (str , default = "python" )),
82- ("custom_templates" , Optional (Dir (exists = True ))),
83- ("enable_inventory" , MkType (bool , default = None )),
84- ("enabled" , MkType (bool , default = True )),
85- )
68+ handlers = opt .Type (dict , default = {})
8669 """
87- The configuration options of `mkdocstrings`, written in `mkdocs.yml` .
70+ Global configuration of handlers .
8871
89- Available options are:
90-
91- - **`handlers`**: Global configuration of handlers. You can set global configuration per handler, applied everywhere,
92- but overridable in each "autodoc" instruction. Example:
93- - **`default_handler`**: The default handler to use. The value is the name of the handler module. Default is "python".
94- - **`custom_templates`**: Location of custom templates to use when rendering API objects. Value should be the path of
95- a directory relative to the MkDocs configuration file.
96- - **`enable_inventory`**: Whether to enable object inventory creation.
97- - **`enabled`**: Whether to enable the plugin. Default is true. If false, *mkdocstrings* will not collect or render anything.
72+ You can set global configuration per handler, applied everywhere,
73+ but overridable in each "autodoc" instruction. Example:
9874
9975 ```yaml
10076 plugins:
@@ -110,6 +86,32 @@ class MkdocstringsPlugin(BasePlugin):
11086 ```
11187 """
11288
89+ default_handler = opt .Type (str , default = "python" )
90+ """The default handler to use. The value is the name of the handler module. Default is "python"."""
91+ custom_templates = opt .Optional (opt .Dir (exists = True )),
92+ """Location of custom templates to use when rendering API objects.
93+
94+ Value should be the path of a directory relative to the MkDocs configuration file.
95+ """
96+ enable_inventory = opt .Optional (opt .Type (bool ))
97+ """Whether to enable object inventory creation."""
98+ enabled = opt .Type (bool , default = True )
99+ """Whether to enable the plugin. Default is true. If false, *mkdocstrings* will not collect or render anything."""
100+
101+
102+ class MkdocstringsPlugin (BasePlugin [PluginConfig ]):
103+ """An `mkdocs` plugin.
104+
105+ This plugin defines the following event hooks:
106+
107+ - `on_config`
108+ - `on_env`
109+ - `on_post_build`
110+
111+ Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
112+ for more information about its plugin system.
113+ """
114+
113115 css_filename = "assets/_mkdocstrings.css"
114116
115117 def __init__ (self ) -> None :
@@ -152,41 +154,41 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
152154 return config
153155 log .debug ("Adding extension to the list" )
154156
155- theme_name = config [ " theme" ] .name or os .path .dirname (config [ " theme" ] .dirs [0 ])
157+ theme_name = config . theme .name or os .path .dirname (config . theme .dirs [0 ])
156158
157159 to_import : InventoryImportType = []
158- for handler_name , conf in self .config [ " handlers" ] .items ():
160+ for handler_name , conf in self .config . handlers .items ():
159161 for import_item in conf .pop ("import" , ()):
160162 if isinstance (import_item , str ):
161163 import_item = {"url" : import_item } # noqa: PLW2901
162164 to_import .append ((handler_name , import_item ))
163165
164166 extension_config = {
165167 "theme_name" : theme_name ,
166- "mdx" : config [ " markdown_extensions" ] ,
167- "mdx_configs" : config [ " mdx_configs" ] ,
168+ "mdx" : config . markdown_extensions ,
169+ "mdx_configs" : config . mdx_configs ,
168170 "mkdocstrings" : self .config ,
169171 "mkdocs" : config ,
170172 }
171173 self ._handlers = Handlers (extension_config )
172174
173175 try :
174176 # If autorefs plugin is explicitly enabled, just use it.
175- autorefs = config [ " plugins" ] ["autorefs" ]
177+ autorefs = config . plugins ["autorefs" ]
176178 log .debug (f"Picked up existing autorefs instance { autorefs !r} " )
177179 except KeyError :
178180 # Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
179181 autorefs = AutorefsPlugin ()
180182 autorefs .scan_toc = False
181- config [ " plugins" ] ["autorefs" ] = autorefs
183+ config . plugins ["autorefs" ] = autorefs
182184 log .debug (f"Added a subdued autorefs instance { autorefs !r} " )
183185 # Add collector-based fallback in either case.
184186 autorefs .get_fallback_anchor = self .handlers .get_anchors
185187
186188 mkdocstrings_extension = MkdocstringsExtension (extension_config , self .handlers , autorefs )
187- config [ " markdown_extensions" ] .append (mkdocstrings_extension )
189+ config . markdown_extensions .append (mkdocstrings_extension )
188190
189- config [ " extra_css" ] .insert (0 , self .css_filename ) # So that it has lower priority than user files.
191+ config . extra_css .insert (0 , self .css_filename ) # So that it has lower priority than user files.
190192
191193 self ._inv_futures = {}
192194 if to_import :
@@ -210,7 +212,7 @@ def inventory_enabled(self) -> bool:
210212 Returns:
211213 Whether the inventory is enabled.
212214 """
213- inventory_enabled = self .config [ " enable_inventory" ]
215+ inventory_enabled = self .config . enable_inventory
214216 if inventory_enabled is None :
215217 inventory_enabled = any (handler .enable_inventory for handler in self .handlers .seen_handlers )
216218 return inventory_enabled
@@ -222,9 +224,9 @@ def plugin_enabled(self) -> bool:
222224 Returns:
223225 Whether the plugin is enabled.
224226 """
225- return self .config [ " enabled" ]
227+ return self .config . enabled
226228
227- def on_env (self , env : Environment , config : Config , * args : Any , ** kwargs : Any ) -> None : # noqa: ARG002
229+ def on_env (self , env : Environment , config : MkDocsConfig , * args : Any , ** kwargs : Any ) -> None : # noqa: ARG002
228230 """Extra actions that need to happen after all Markdown rendering and before HTML rendering.
229231
230232 Hook for the [`on_env` event](https://www.mkdocs.org/user-guide/plugins/#on_env).
@@ -236,12 +238,12 @@ def on_env(self, env: Environment, config: Config, *args: Any, **kwargs: Any) ->
236238 return
237239 if self ._handlers :
238240 css_content = "\n " .join (handler .extra_css for handler in self .handlers .seen_handlers )
239- write_file (css_content .encode ("utf-8" ), os .path .join (config [ " site_dir" ] , self .css_filename ))
241+ write_file (css_content .encode ("utf-8" ), os .path .join (config . site_dir , self .css_filename ))
240242
241243 if self .inventory_enabled :
242244 log .debug ("Creating inventory file objects.inv" )
243245 inv_contents = self .handlers .inventory .format_sphinx ()
244- write_file (inv_contents , os .path .join (config [ " site_dir" ] , "objects.inv" ))
246+ write_file (inv_contents , os .path .join (config . site_dir , "objects.inv" ))
245247
246248 if self ._inv_futures :
247249 log .debug (f"Waiting for { len (self ._inv_futures )} inventory download(s)" )
@@ -256,12 +258,12 @@ def on_env(self, env: Environment, config: Config, *args: Any, **kwargs: Any) ->
256258 loader_name = loader .__func__ .__qualname__
257259 log .error (f"Couldn't load inventory { import_item } through { loader_name } : { error } " ) # noqa: TRY400
258260 for page , identifier in results .items ():
259- config [ " plugins" ] ["autorefs" ].register_url (page , identifier )
261+ config . plugins ["autorefs" ].register_url (page , identifier )
260262 self ._inv_futures = {}
261263
262264 def on_post_build (
263265 self ,
264- config : Config , # noqa: ARG002
266+ config : MkDocsConfig , # noqa: ARG002
265267 ** kwargs : Any , # noqa: ARG002
266268 ) -> None :
267269 """Teardown the handlers.
0 commit comments