### Install Pip with get-pip.py Source: https://www.mkdocs.org/user-guide/installation If pip is not installed, use this command to download and install it using the get-pip.py script. ```bash python get-pip.py ``` -------------------------------- ### Install Manpages for MkDocs Source: https://www.mkdocs.org/user-guide/installation Optional: Install manpages for MkDocs using the click-man tool. This provides command-line help documentation. ```bash pip install click-man click-man --target path/to/man/pages mkdocs ``` -------------------------------- ### Install a Third-Party MkDocs Plugin Source: https://www.mkdocs.org/dev-guide/plugins Use pip to install a plugin package. Exercise caution as plugins execute Python code. ```bash pip install mkdocs-foo-plugin ``` -------------------------------- ### Primary Configuration Example (foo/mkdocs.yml) Source: https://www.mkdocs.org/user-guide/configuration Inherits from a parent configuration and defines site-specific settings like name and URL. ```yaml INHERIT: ../base.yml site_name: Foo Project site_url: https://example.com/foo ``` -------------------------------- ### Install MkDocs Source: https://www.mkdocs.org/user-guide/installation Install the MkDocs package using pip. This command makes the `mkdocs` command available on your system. ```bash pip install mkdocs ``` -------------------------------- ### Serve with Clean Build Source: https://www.mkdocs.org/about/release-notes Use the `--clean` flag with `mkdocs serve` to perform a clean build before starting the development server. ```bash mkdocs serve --clean ``` -------------------------------- ### Verify MkDocs Installation Source: https://www.mkdocs.org/user-guide/installation Check that MkDocs has been installed correctly by running the version command. ```bash $ mkdocs --version mkdocs, version 1.2.0 from /usr/local/lib/python3.8/site-packages/mkdocs (Python 3.8) ``` -------------------------------- ### Old Plugin Config Scheme Example Source: https://www.mkdocs.org/about/release-notes This is an example of the old way to define a plugin's configuration scheme using a tuple. ```python from mkdocs import plugins from mkdocs.config import base, config_options class MyPlugin(plugins.BasePlugin): config_scheme = ( ('foo', config_options.Type(int)), ('bar', config_options.Type(str, default='')), ) def on_page_markdown(self, markdown: str, *, config: base.Config, **kwargs): if self.config['foo'] < 5: if config['site_url'].startswith('http:'): return markdown + self.config['baz'] ``` -------------------------------- ### Install MkDocs with i18n Support Source: https://www.mkdocs.org/user-guide/localizing-your-theme Install MkDocs with internationalization support using pip. This is a prerequisite for theme localization. ```bash pip install 'mkdocs[i18n]' ``` -------------------------------- ### Serve MkDocs Project Locally Source: https://www.mkdocs.org/getting-started Start the MkDocs development server to preview your documentation site locally. The server watches for changes and reloads automatically. ```bash $ mkdocs serve INFO - Building documentation... INFO - Cleaning site directory INFO - Documentation built in 0.22 seconds INFO - [15:50:43] Watching paths for changes: 'docs', 'mkdocs.yml' INFO - [15:50:43] Serving on http://127.0.0.1:8000/ ``` -------------------------------- ### Install MkDocs on Windows using python -m Source: https://www.mkdocs.org/user-guide/installation A workaround for Windows users to install MkDocs by prefacing pip commands with `python -m`. ```bash python -m pip install mkdocs python -m mkdocs ``` -------------------------------- ### Parent Configuration Example (base.yml) Source: https://www.mkdocs.org/user-guide/configuration Defines common configuration options like theme and markdown extensions that can be inherited by other sites. ```yaml theme: name: mkdocs locale: en highlightjs: true markdown_extensions: toc: permalink: true admonition: {} ``` -------------------------------- ### Configure Read the Docs Theme Source: https://www.mkdocs.org/user-guide/choosing-your-theme Example configuration for the 'readthedocs' theme, enabling code highlighting and specifying additional languages. ```yaml theme: name: readthedocs highlightjs: true hljs_languages: - yaml - rust ``` -------------------------------- ### MANIFEST.in for Theme Packaging Source: https://www.mkdocs.org/dev-guide/themes Example MANIFEST.in file content for including theme assets. Remember to update 'theme_name' and add any extra file extensions. ```text recursive-include theme_name *.ico *.js *.css *.png *.html *.eot *.svg *.ttf *.woff recursive-exclude * __pycache__ recursive-exclude * *.py[co] ``` -------------------------------- ### Merged Configuration Example Source: https://www.mkdocs.org/user-guide/configuration Illustrates the result of deep merging the primary configuration with its parent, combining settings from both. ```yaml site_name: Foo Project site_url: https://example.com/foo theme: name: mkdocs locale: en highlightjs: true markdown_extensions: toc: permalink: true admonition: {} ``` -------------------------------- ### Check Python and Pip Versions Source: https://www.mkdocs.org/user-guide/installation Verify if Python and pip are installed and check their versions. This is a prerequisite for installing MkDocs. ```bash $ python --version Python 3.8.2 $ pip --version pip 20.0.2 from /usr/local/lib/python3.8/site-packages/pip (python 3.8) ``` -------------------------------- ### Install Development Version of MkDocs Source: https://www.mkdocs.org/about/contributing Install the latest development version of MkDocs directly from its GitHub repository. This is useful for testing new features or confirming bug fixes. It is strongly recommended to do this within a virtual environment. ```bash pip install git+https://github.com/mkdocs/mkdocs.git ``` -------------------------------- ### Install MkDocs Documentation Requirements Source: https://www.mkdocs.org/about/contributing Install the necessary requirements for working with MkDocs documentation. This can be done using exact or latest versions of dependencies, typically within a virtual environment. ```bash .venv/bin/pip install -r requirements/requirements-docs.txt ``` ```bash .venv/bin/pip install -r $(mkdocs get-deps) ``` -------------------------------- ### Upgrade Pip Source: https://www.mkdocs.org/user-guide/installation Ensure you have the latest version of pip installed, which is recommended for installing Python packages. ```bash pip install --upgrade pip ``` -------------------------------- ### Multi-Page Project File Layout Source: https://www.mkdocs.org/user-guide/writing-your-docs An example of a project with multiple Markdown files for different pages, demonstrating a simple multi-page structure. ```text mkdocs.yml docs/ index.md about.md license.md ``` -------------------------------- ### Example Plugin Configuration YAML Source: https://www.mkdocs.org/dev-guide/plugins This YAML structure shows how a user would provide values for the defined plugin configuration, including nested options and environment variable overrides. ```yaml my_plugin: definition_file: configs/test.ini # relative to mkdocs.yml validation: enabled: !ENV [CI, false] verbose: true skip_checks: - foo - baz ``` -------------------------------- ### Example Plugin Configuration with List of Objects YAML Source: https://www.mkdocs.org/dev-guide/plugins This YAML shows the user-provided configuration for a list of complex objects, where each object conforms to the `_Rectangle` schema. ```yaml my_plugin: add_rectangles: - width: 5 height: 7 - width: 12 height: 2 ``` -------------------------------- ### Install MkDocs Bootswatch Theme Source: https://www.mkdocs.org/about/release-notes Install the Bootswatch theme for MkDocs using pip. This theme was previously included with MkDocs but is now distributed as a separate package. ```bash pip install mkdocs-bootswatch ``` -------------------------------- ### Install MkDocs Dependencies Source: https://www.mkdocs.org/about/release-notes Use this command to automatically install the Python dependencies required for your MkDocs site. It scans your configuration file for themes, plugins, and extensions. ```bash pip install $(mkdocs get-deps) ``` -------------------------------- ### Basic Hook Script Example Source: https://www.mkdocs.org/user-guide/configuration Specify a Python script to be loaded as a plugin instance. The script should contain event handlers. ```yaml hooks: - my_hooks.py ``` -------------------------------- ### Install MkDocs Bootstrap Theme Source: https://www.mkdocs.org/about/release-notes Install the Bootstrap theme for MkDocs using pip. This theme was previously included with MkDocs but is now distributed as a separate package. ```bash pip install mkdocs-bootstrap ``` -------------------------------- ### Default Validation Settings (MkDocs 1.6) Source: https://www.mkdocs.org/user-guide/configuration This example shows the default validation configuration for MkDocs version 1.6. It's generally not recommended to copy this whole example, but rather to set only individual items that differ from your desired configuration. ```yaml validation: nav: omitted_files: info not_found: warn absolute_links: info links: not_found: warn anchors: info absolute_links: info unrecognized_links: info ``` -------------------------------- ### Opt-in Files with Default Exclusions Source: https://www.mkdocs.org/user-guide/configuration Example of re-including specific dot-files when default exclusions are active. ```yaml exclude_docs: | !.assets # Don't exclude '.assets' although all other '.*' are excluded ``` -------------------------------- ### Configure Theme with Key/Value Pairs Source: https://www.mkdocs.org/user-guide/configuration Use this snippet to set theme properties like name, locale, custom directories, and static templates. Ensure the theme is installed and any custom directories or templates are correctly specified. ```yaml theme: name: mkdocs locale: en custom_dir: my_theme_customizations/ static_templates: - sitemap.html include_sidebar: false ``` -------------------------------- ### Configure Repository URL and Edit URI Source: https://www.mkdocs.org/user-guide/configuration This example shows how to set both the repository URL and the edit URI, which MkDocs uses to construct links to the source files. ```yaml repo_url: https://example.com/project/repo edit_uri: blob/main/docs/ ``` -------------------------------- ### YAML Style Meta-Data Example Source: https://www.mkdocs.org/user-guide/writing-your-docs Demonstrates YAML style meta-data with various data types. Meta-data is enclosed by '---' delimiters and parsed as YAML. ```markdown --- title: My Document summary: A brief description of my document. authors: - Waylan Limberg - Tom Christie date: 2018-07-10 some_url: https://example.com --- This is the first paragraph of the document. ``` -------------------------------- ### Configure Google Analytics with Read the Docs Theme Source: https://www.mkdocs.org/user-guide/choosing-your-theme Example configuration for enabling Google Analytics (v4) within the 'readthedocs' theme. ```yaml theme: name: readthedocs analytics: gtag: G-ABC123 ``` -------------------------------- ### Configure mkdocs Theme Options Source: https://www.mkdocs.org/user-guide/choosing-your-theme Customize the 'mkdocs' theme by setting options like 'highlightjs', 'hljs_style', 'analytics', and 'shortcuts' in your `mkdocs.yml` file. This example enables highlighting.js and specifies additional languages. ```yaml theme: name: mkdocs highlightjs: true hljs_languages: - yaml - rust ``` -------------------------------- ### New Plugin Config Scheme with Type Annotations Source: https://www.mkdocs.org/about/release-notes This example demonstrates the new class-based configuration scheme for plugins, including type annotations and attribute-based access. It highlights potential errors that a static type checker like mypy would catch. ```python from mkdocs import plugins from mkdocs.config import base, config_options as c class MyPluginConfig(base.Config): foo = c.Optional(c.Type(int)) bar = c.Type(str, default='') class MyPlugin(plugins.BasePlugin[MyPluginConfig]): def on_page_markdown(self, markdown: str, *, config: defaults.MkDocsConfig, **kwargs): if self.config.foo < 5: # Error, `foo` might be `None`, need to check first. if config.site_url.startswith('http:'): # Error, MkDocs' `site_url` also might be `None`. return markdown + self.config.baz # Error, no such attribute `baz`! ``` -------------------------------- ### Set Theme in mkdocs.yml Source: https://www.mkdocs.org/user-guide/choosing-your-theme Configure the theme for your MkDocs project by setting the 'theme.name' option in your `mkdocs.yml` file. This example sets the theme to 'readthedocs'. ```yaml theme: name: readthedocs ``` -------------------------------- ### Standard Plugin Logging Source: https://www.mkdocs.org/dev-guide/plugins Use loggers under the 'mkdocs.plugins.' namespace for consistent log formatting and adherence to MkDocs flags like --verbose and --debug. This example shows various logging levels and conditional debugging. ```python import logging log = logging.getLogger(f"mkdocs.plugins.{__name__}") log.warning("File '%s' not found. Breaks the build if --strict is passed", my_file_name) log.info("Shown normally") log.debug("Shown only with `--verbose`") if log.getEffectiveLevel() <= logging.DEBUG: log.debug("Very expensive calculation only for debugging: %s", get_my_diagnostics()) ``` -------------------------------- ### Configuring Reserved Word Options Source: https://www.mkdocs.org/about/release-notes Example of adding an async boolean option that can be set by the user as `async: true` and read programmatically as `config.async_`. This avoids clashing with Python's reserved words. ```python from mkdocs.config.config_options import Config, Type class ExampleConfig(Config): async_ = Type(bool, default=False) ``` -------------------------------- ### Define Plugin Configuration Scheme (Tuple) Source: https://www.mkdocs.org/dev-guide/plugins Define configuration options for a custom plugin using a tuple of validation instances. This example shows string, integer, and boolean types with default values. ```python class MyPlugin(mkdocs.plugins.BasePlugin): config_scheme = ( ('foo', mkdocs.config.config_options.Type(str, default='a default value')), ('bar', mkdocs.config.config_options.Type(int, default=0)), ('baz', mkdocs.config.config_options.Type(bool, default=True)) ) ``` -------------------------------- ### Ignored Files in Theme Directory Source: https://www.mkdocs.org/dev-guide/themes Examples of files and directories that MkDocs themes will ignore. Files starting with a dot are explicitly ignored. ```ignore .ignored.txt .ignored/file.txt foo/.ignored.txt foo/.ignored/file.txt ``` -------------------------------- ### setup.py for Theme Packaging Source: https://www.mkdocs.org/dev-guide/themes A basic setup.py file for packaging an MkDocs theme. Key modifications include the package name, entry_points, and author details. ```python from setuptools import setup, find_packages VERSION = '0.0.1' setup( name="mkdocs-themename", version=VERSION, url='', license='', description='', author='', author_email='', packages=find_packages(), include_package_data=True, entry_points={ 'mkdocs.themes': [ 'themename = theme_name', ] }, zip_safe=False ) ``` -------------------------------- ### Configure Edit URI with Query String Source: https://www.mkdocs.org/user-guide/configuration The edit_uri setting specifies the path to the docs directory for linking to the source file. This example shows how to configure it with a query string. ```yaml edit_uri: "?query=root/path/docs/" ``` -------------------------------- ### Configure Edit URI with Hash Fragment Source: https://www.mkdocs.org/user-guide/configuration The edit_uri setting specifies the path to the docs directory for linking to the source file. This example shows how to configure it with a hash fragment. ```yaml edit_uri: "#root/path/docs/" ``` -------------------------------- ### Registering a Single Plugin via Setuptools Source: https://www.mkdocs.org/dev-guide/plugins Define a plugin's entry point in setup.py to register it for MkDocs. 'pluginname' is the user-facing name, and the value is the importable path to the plugin class. ```python entry_points={ 'mkdocs.plugins': [ 'pluginname = path.to.some_plugin:SomePluginClass', ] } ``` -------------------------------- ### Build and Deploy Documentation Source: https://www.mkdocs.org/user-guide/deploying-your-docs Build the MkDocs site and copy the generated files to the server root using SCP. Adjust user, host, and path as needed. ```bash mkdocs build scp -r ./site user@host:/path/to/server/root ``` -------------------------------- ### Example Anchor Validation Warning Source: https://www.mkdocs.org/about/release-notes This is an example of a warning produced when a link points to a non-existent anchor. ```text WARNING - Doc file 'foo/example.md' contains a link '../bar.md#some-heading', but the doc 'foo/bar.md' does not contain an anchor '#some-heading'. ``` -------------------------------- ### Display MkDocs Build Command Help Source: https://www.mkdocs.org/getting-started Shows help specific to the 'build' command, detailing its available options. ```bash mkdocs build --help ``` -------------------------------- ### Create a New MkDocs Project Source: https://www.mkdocs.org/getting-started Create a new MkDocs project and navigate into the project directory. This sets up the basic file structure for your documentation. ```bash mkdocs new my-project cd my-project ``` -------------------------------- ### Build MkDocs Documentation Source: https://www.mkdocs.org/getting-started Builds the documentation site, creating a 'site' directory with static files. ```bash mkdocs build ``` -------------------------------- ### Open Site in Browser with mkdocs serve Source: https://www.mkdocs.org/about/release-notes Use the `--open` flag with `mkdocs serve` to automatically open the local site in your default web browser after the initial build. ```bash mkdocs serve --open ``` -------------------------------- ### Registering Multiple Plugins via Setuptools Source: https://www.mkdocs.org/dev-guide/plugins A single module can contain multiple plugin classes, each registered as a separate entry point in setup.py. ```python entry_points={ 'mkdocs.plugins': [ 'featureA = path.to.my_plugins:PluginA', 'featureB = path.to.my_plugins:PluginB' ] } ``` -------------------------------- ### Registering Theme with PyPI Source: https://www.mkdocs.org/dev-guide/themes Use the `python setup.py register` command to register your theme package with the Python Package Index (PyPI) for distribution. ```bash python setup.py register ``` -------------------------------- ### Basic Project File Layout Source: https://www.mkdocs.org/user-guide/writing-your-docs A minimal MkDocs project structure with a configuration file and a single index Markdown file. ```text mkdocs.yml docs/ index.md ``` -------------------------------- ### Upgrade MkDocs Source: https://www.mkdocs.org/about/release-notes Use this command to upgrade MkDocs to the latest version via pip. Ensure you have pip installed and configured. ```bash pip install -U mkdocs ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://www.mkdocs.org/about/contributing Preview the MkDocs documentation site locally after making edits to files in the `docs/` directory. Any warnings should be resolved before submitting a contribution. Markdown files are also checked by markdownlint. ```bash hatch run docs:serve ``` -------------------------------- ### Simple Python Hook Handler Source: https://www.mkdocs.org/user-guide/configuration A basic example of a hook function within a Python script that modifies Markdown content. ```python def on_page_markdown(markdown, **kwargs): return markdown.replace('a', 'z') ``` -------------------------------- ### MkDocs New Command Source: https://www.mkdocs.org/user-guide/cli Creates a new MkDocs project in the specified directory. This command initializes the basic project structure. ```bash mkdocs new [OPTIONS] PROJECT_DIRECTORY ``` -------------------------------- ### Configure Theme Locale in mkdocs.yml Source: https://www.mkdocs.org/user-guide/localizing-your-theme Set the locale for your theme in the mkdocs.yml configuration file. This example sets the theme to French. ```yaml theme: name: mkdocs locale: fr ``` -------------------------------- ### Basic Fenced Code Block Source: https://www.mkdocs.org/user-guide/writing-your-docs A standard fenced code block defined by starting and ending lines of three or more backticks. ```markdown ``` Fenced code blocks are like Standard Markdown’s regular code blocks, except that they’re not indented and instead rely on start and end fence lines to delimit the code block. ``` ``` -------------------------------- ### Enable a Basic Plugin Source: https://www.mkdocs.org/dev-guide/plugins List the plugin name in the 'plugins' section of your mkdocs.yml configuration file to enable it. ```yaml plugins: - search ``` -------------------------------- ### Adding a Virtual File with File.generated() Source: https://www.mkdocs.org/about/release-notes Example of how to append a virtual file to the `files` collection using `File.generated()` within an `on_files` hook. ```python def on_files(files: Files, config: MkDocsConfig): files.append(File.generated(config, 'fake/path.md', content="Hello, world!")) ``` -------------------------------- ### Display MkDocs Help Source: https://www.mkdocs.org/getting-started Shows the main help message for MkDocs, listing available commands and global options. ```bash mkdocs --help ``` -------------------------------- ### MkDocs Serve Command Usage Source: https://www.mkdocs.org/user-guide/cli Basic usage of the `mkdocs serve` command. ```bash mkdocs serve [OPTIONS] ``` -------------------------------- ### Configure Search Plugin Separator Source: https://www.mkdocs.org/user-guide/configuration Customizes the search plugin by defining a regular expression for word separators. This example adds the dot (`.`) to the default separators. ```yaml plugins: - search: separator: '[\s\-\.]+' ``` -------------------------------- ### Recommended Theme Package Layout Source: https://www.mkdocs.org/dev-guide/themes A recommended directory structure for packaging MkDocs themes, including essential files like MANIFEST.in, setup.py, and theme-specific files within a theme directory. ```text . |-- MANIFEST.in |-- theme_name | |-- __init__.py | |-- mkdocs_theme.yml | |-- main.html | |-- styles.css `-- setup.py ``` -------------------------------- ### View Site Directory Contents Source: https://www.mkdocs.org/getting-started Lists the contents of the 'site' directory after a successful build. ```bash $ ls site about fonts index.html license search.html css img js mkdocs sitemap.xml ``` -------------------------------- ### Replacing mkdocs-simple-hooks with Native Hooks Source: https://www.mkdocs.org/user-guide/configuration Demonstrates how to switch from the mkdocs-simple-hooks plugin to the native hooks feature for simpler one-off usages. ```yaml -plugins: - - mkdocs-simple-hooks: - hooks: - on_page_markdown: 'my_hooks:on_page_markdown' +hooks: + - my_hooks.py ``` -------------------------------- ### Build with stdin config Source: https://www.mkdocs.org/about/release-notes Use this command to build MkDocs with configuration overrides from stdin. This is useful for on-the-fly configuration adjustments. ```bash mkdocs build -f - ``` -------------------------------- ### Define Multiple Handlers for One Event Source: https://www.mkdocs.org/dev-guide/plugins Use `CombinedEvent` to register multiple handlers for the same event at different priorities. Sub-methods must not start with `on_`. ```python from mkdocs.plugins import CombinedEvent, event_priority @event_priority(100) def _on_page_markdown_1(self, markdown: str, **kwargs): ... @event_priority(-50) def _on_page_markdown_2(self, markdown: str, **kwargs): ... on_page_markdown = CombinedEvent(_on_page_markdown_1, _on_page_markdown_2) ``` -------------------------------- ### Configure a Plugin with Options Source: https://www.mkdocs.org/dev-guide/plugins Provide configuration options for a plugin by nesting key-value pairs under the plugin name in mkdocs.yml. Each option must be on a new, indented line. ```yaml plugins: - search: lang: en foo: bar ``` -------------------------------- ### Configure Minimum Search Query Length Source: https://www.mkdocs.org/user-guide/configuration Adjusts the minimum character length for search queries. This example lowers the limit to 2, useful for queries like 'MQ'. ```yaml plugins: - search: min_search_length: 2 ``` -------------------------------- ### Configure Edit URI as Absolute URL Source: https://www.mkdocs.org/user-guide/configuration The edit_uri setting can be an absolute URL, providing flexibility in linking to the source file. This example demonstrates setting it as a full URL. ```yaml edit_uri: https://example.com/project/repo/blob/main/docs/ ``` -------------------------------- ### Define Plugin Configuration with List of SubConfigs Source: https://www.mkdocs.org/dev-guide/plugins Demonstrates defining a configuration that accepts a list of complex objects, each with its own schema, using `ListOfItems` and `SubConfig`. ```python import numbers from mkdocs.config import base, config_options as c class _Rectangle(base.Config): width = c.Type(numbers.Real) # required height = c.Type(numbers.Real) # required class MyPluginConfig(base.Config): add_rectangles = c.ListOfItems(c.SubConfig(_Rectangle)) # required ``` -------------------------------- ### Configure for Local File Viewing Source: https://www.mkdocs.org/user-guide/deploying-your-docs Set `site_url` to an empty string to enable building the site for the `file://` scheme. ```yaml site_url: "" ``` -------------------------------- ### Deploy Project Pages to GitHub Source: https://www.mkdocs.org/user-guide/deploying-your-docs Builds and deploys documentation to the `gh-pages` branch of the current repository. Use when hosting documentation within the same repository as your project. ```bash mkdocs gh-deploy ``` -------------------------------- ### MultiMarkdown Style Meta-Data Example Source: https://www.mkdocs.org/user-guide/writing-your-docs Illustrates MultiMarkdown style meta-data. Keywords are case-insensitive and values can span multiple indented lines. The first blank line terminates meta-data. ```markdown Title: My Document Summary: A brief description of my document. Authors: Waylan Limberg Tom Christie Date: January 23, 2018 blank-value: some_url: https://example.com This is the first paragraph of the document. ``` -------------------------------- ### Configure Edit URI with Relative Path Source: https://www.mkdocs.org/user-guide/configuration The edit_uri setting specifies the path to the docs directory for linking to the source file. This example shows a common configuration using a relative path. ```yaml edit_uri: root/path/docs/ ``` -------------------------------- ### Configure Plugin Options Source: https://www.mkdocs.org/user-guide/configuration Shows how to pass configuration options to a custom plugin. Nested key/value pairs are used for plugin-specific settings. ```yaml plugins: - search - your_other_plugin: option1: value option2: other value ``` -------------------------------- ### Display Table of Contents Source: https://www.mkdocs.org/dev-guide/themes Displays the top two levels of the Table of Contents for a page using the 'page.toc' object. This example iterates through TOC items and their children to create a nested list. ```html ``` -------------------------------- ### Enable Absolute Link Validation Source: https://www.mkdocs.org/about/release-notes Configure MkDocs to validate absolute Markdown links by setting 'validation.links.absolute_links' to 'relative_to_docs'. This allows links starting with '/' to be treated as relative to the docs directory. ```yaml validation: links: absolute_links: relative_to_docs ``` -------------------------------- ### Navigation with Relative and Absolute External Links Source: https://www.mkdocs.org/user-guide/configuration Demonstrates navigation configuration for a site hosted in a subdirectory, using relative and absolute external links. ```yaml site_url: https://example.com/foo/ nav: - Home: '../' - 'User Guide': 'user-guide.md' - 'Bug Tracker': '/bugs/' ``` -------------------------------- ### Corrected Plugin Config Scheme for Type Safety Source: https://www.mkdocs.org/about/release-notes This corrected example shows how to resolve type-checking errors in the new plugin configuration scheme, ensuring type safety and correct attribute access. ```python class MyPlugin(plugins.BasePlugin[MyPluginConfig]): def on_page_markdown(self, markdown: str, *, config: defaults.MkDocsConfig, **kwargs): if self.config.foo is not None and self.config.foo < 5: # OK, `int < int` is valid. if (config.site_url or '').startswith('http:'): # OK, `str.startswith(str)` is valid. return markdown + self.config.bar # OK, `str + str` is valid. ``` -------------------------------- ### Override Configuration via Stdin Source: https://www.mkdocs.org/user-guide/configuration Demonstrates overriding configuration keys on the command line by piping a JSON configuration object to `mkdocs build` using stdin. ```bash echo '{INHERIT: mkdocs.yml, site_name: "Renamed site"}' | mkdocs build -f - ``` -------------------------------- ### Specify Additional Directories to Watch Source: https://www.mkdocs.org/user-guide/configuration Configure 'watch' to include extra directories that 'mkdocs serve' should monitor for changes. Paths are relative to the configuration file. ```yaml watch: - directory_a - directory_b ``` -------------------------------- ### MkDocs Get-deps Command Source: https://www.mkdocs.org/user-guide/cli Shows required PyPI packages inferred from plugins in `mkdocs.yml`. You can specify an alternative registry file using the `--projects-file` option. ```bash mkdocs get-deps [OPTIONS] ``` -------------------------------- ### Set Event Priority with Decorator Source: https://www.mkdocs.org/dev-guide/plugins Use the `event_priority` decorator to control the execution order of plugin event handlers. Higher values execute earlier. This example sets a low priority to run after other plugins. ```python from mkdocs.plugins import event_priority @event_priority(-100) # Wishing to run this after all other plugins' `on_files` events. def on_files(self, files, config, **kwargs): ... ``` -------------------------------- ### Enable and Validate Absolute Links (MkDocs 1.6+) Source: https://www.mkdocs.org/user-guide/configuration Configure MkDocs to recognize absolute links starting with '/' as relative to the `docs_dir` root and validate them. This setting is new in MkDocs 1.6 and requires explicit enabling. ```yaml validation: links: absolute_links: relative_to_docs anchors: warn unrecognized_links: warn ``` -------------------------------- ### Enable Default and Custom Plugins Source: https://www.mkdocs.org/user-guide/configuration Lists the search plugin and a custom plugin, explicitly enabling both. Use this when you need to ensure default plugins are active alongside custom ones. ```yaml plugins: - search - your_other_plugin ``` -------------------------------- ### Nested Directory File Layout Source: https://www.mkdocs.org/user-guide/writing-your-docs Illustrates how to organize documentation into nested directories, which affects the generated URL structure. ```text docs/ index.md user-guide/getting-started.md user-guide/configuration-options.md license.md ``` -------------------------------- ### Deploy Organization/User Pages to GitHub Source: https://www.mkdocs.org/user-guide/deploying-your-docs Deploys documentation to the `master` branch of a dedicated GitHub Pages repository. Requires specifying the configuration file and remote branch when running from a separate project directory. ```bash cd ../orgname.github.io/ mkdocs gh-deploy --config-file ../my-project/mkdocs.yml --remote-branch master ``` -------------------------------- ### MkDocs Build Command Source: https://www.mkdocs.org/user-guide/cli Builds the MkDocs documentation. Use the `--clean` option to remove old files before building. Specify a configuration file with `--config-file`. ```bash mkdocs build [OPTIONS] ``` -------------------------------- ### Initialize Localization Catalog for MkDocs Theme Source: https://www.mkdocs.org/dev-guide/translations Initializes a new localization catalog for the 'mkdocs' theme in Spanish ('es'). This command generates the necessary Portable Object (`.po`) file structure for translating theme templates. ```bash pybabel init --input-file mkdocs/themes/mkdocs/messages.pot --output-dir mkdocs/themes/mkdocs/locales -l es ``` -------------------------------- ### Minimal Navigation Configuration Source: https://www.mkdocs.org/user-guide/writing-your-docs Defines a basic navigation with two top-level pages. Paths are relative to the `docs_dir`. ```yaml nav: - index.md - about.md ``` -------------------------------- ### Define Plugin Configuration with Validation Options Source: https://www.mkdocs.org/dev-guide/plugins Use `mkdocs.config.base.Config` and `config_options` to define a plugin's configuration schema, including nested validation rules. ```python from mkdocs.config import base, config_options as c class _ValidationOptions(base.Config): enabled = c.Type(bool, default=True) verbose = c.Type(bool, default=False) skip_checks = c.ListOfItems(c.Choice(('foo', 'bar', 'baz')), default=[]) class MyPluginConfig(base.Config): definition_file = c.File(exists=True) # required checksum_file = c.Optional(c.File(exists=True)) # can be None but must exist if specified validation = c.SubConfig(_ValidationOptions) ``` -------------------------------- ### Enable Dirty Build Mode for MkDocs Serve Source: https://www.mkdocs.org/about/release-notes Use the --dirtyreload flag with `mkdocs serve` to enable a faster build process during development by only rebuilding changed pages. ```bash mkdocs serve --dirtyreload ``` -------------------------------- ### Specify Theme Directory with MkDocs Serve Source: https://www.mkdocs.org/about/release-notes Use the -e or --theme-dir flag to specify a custom theme directory when serving your MkDocs site. ```bash mkdocs serve -e ``` -------------------------------- ### Add a New Page to Documentation Source: https://www.mkdocs.org/getting-started Fetch content for a new documentation page using curl and save it as docs/about.md. ```bash curl 'https://jaspervdj.be/lorem-markdownum/markdown.txt' > docs/about.md ```