The Plugin Ecosystem

MkDocs’ core is small, and most of what a documentation site needs beyond “render these Markdown files” is supplied by plugins. A plugin is a Python package that hooks into the build at a named point and does one thing: rewrite a Markdown file, inspect the generated HTML, add a page, generate a file, or watch the project for changes. The theme supplies the appearance and the plugin system supplies the behaviour, and the two are independent — a plugin does not care which theme is installed.

Enabling plugins

Plugins are listed in the configuration file. The search plugin is enabled by default, because a documentation site without search is nearly useless:

plugins:
  - search

To add a plugin, install its package and name it in the list:

python -m pip install mkdocs-minify-plugin mkdocs-git-revision-date-localized-plugin
plugins:
  - search
  - minify
  - git-revision-date-localized:
      type: date
      locale: en
      enable_creation_date: false

A plugin that takes options is configured by turning its list entry into a mapping, where the keys are the option names and the values are their settings. A plugin with no options stays a plain string, which is why the list above mixes a string and a mapping.

One detail catches almost everybody once: if you write a plugins section at all, you have replaced the default list rather than extended it. The search plugin has to be listed explicitly, as it is above, or the site will build without a search index.

The plugin API

A plugin is a class that inherits from BasePlugin and implements one or more event methods. The simplest useful version looks like this:

from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options


class ReplaceTermsPlugin(BasePlugin):
    config_scheme = (
        ("terms", config_options.Type(dict, default={})),
    )

    def on_page_markdown(self, markdown, page, config, files):
        for source, target in self.config["terms"].items():
            markdown = markdown.replace(source, target)
        return markdown

Three parts matter. The config_scheme tuple declares the options the plugin accepts and their defaults, so that MkDocs can validate the configuration and report a useful error when an option is misspelled. The event method names are fixed by MkDocs, and each one receives a specific set of arguments and may return a modified value. Returning None from a hook means “leave this unchanged”; returning a value replaces it.

The events are the build pipeline, in order. on_startup and on_config run before anything is read, on_files is where you add or remove files, on_nav is where you can rewrite the navigation tree, on_page_markdown receives each page’s Markdown before it is rendered, on_page_content receives the rendered HTML, on_post_page runs after a page is written, and on_post_build runs once at the end with the whole output directory.

on_page_markdown and on_page_content are the two you will use most, and the difference between them matters. Rewriting Markdown is the safe place to do most work, because you are working with the source and the result still goes through the normal rendering pipeline. Rewriting HTML is the right place for something that only exists after rendering, such as adding a wrapper element or injecting a script tag.

Hooks

Writing a full plugin means publishing a package. When the change is small and specific to one project, MkDocs offers a lighter mechanism: a hooks entry in the configuration file listing Python scripts, each of which may define functions named after the events.

hooks:
  - hooks/hooks.py
# hooks/hooks.py
def on_page_markdown(markdown, page, config, files):
    if "draft" in page.meta.get("tags", []):
        return None
    return markdown

A hook file is just a set of plain functions, so there is no class, no configuration scheme, and no packaging step. The trade-off is that a hook lives inside your repository and cannot be installed by someone else, which makes it the right tool for project-specific behaviour and the wrong one for anything you want to share. A hook can also declare a priority on an event, which is how two plugins that touch the same stage of the build are ordered against each other.

Plugins worth knowing

The ecosystem is large, but a handful covers most needs.

PluginWhat it does
searchBuilds the client-side search index; enabled by default
minifyRemoves whitespace and comments from the generated HTML and CSS
git-revision-date-localizedShows each page’s last commit date in the reader’s time zone
git-authorsLists the people who changed a page, at the end of the page
socialGenerates social-media cards for individual pages
mkdocs-redirectsGenerates redirect pages from old paths to new ones
mkdocs-section-indexTurns a section folder into a proper landing page
mkdocs-awesome-pagesDerives navigation from the file tree, with ordering rules in filenames
mkdocs-macrosExpands Jinja macros and includes inside Markdown
mkdocs-pdf-exportRenders the site to a PDF through a headless browser
mkdocs-excludeExcludes files and folders from the build
mkdocs-jupyterRenders Jupyter notebooks as pages

Install the ones you need and enable them by name. Option names are consistent within a plugin but not across plugins, so read each project’s README rather than assuming.

Choosing between a theme feature, a plugin, and a hook

The three mechanisms overlap, and it is worth having a rule. If the theme already offers the behaviour as a configuration flag, use the flag: it costs nothing and it survives an upgrade. If the behaviour is a well-defined transformation that other projects would want, write or install a plugin. If the behaviour is specific to one project and small, write a hook. Overriding a template is the last resort, because it couples you to the theme’s internal structure and it is the option most likely to break when the theme changes.

Wrapping up

The plugin system is what makes MkDocs more than a Markdown converter, and its shape is simple enough to reason about: a plugin declares its options, implements one or more named events, and may transform the value it is given. Install what exists, write a plugin when the transformation is worth publishing, and use a hook when it is not. From here, the useful habit is to keep transformations in Markdown rather than in HTML wherever possible, because the source-level hook is the one that composes with everything else in the pipeline.

Found an issue with this content?

Tell us what could be improved.