Skip to content

MkDocs Material Plugin Guide

Welcome to the comprehensive guide for using MkDocs with Material theme and all the powerful plugins configured in this documentation system.

Quick Start

This documentation site is built using the mkdocsgen.py generator which creates a feature-rich MkDocs configuration. To generate the configuration:

Bash
python3 mkdocsgen.py --name "Docs" docs/

This will create a mkdocs.yml file with all plugins pre-configured.

Installed Plugins

This documentation uses the following plugins to provide a rich documentation experience:

  1. Mermaid2 - Create diagrams and flowcharts
  2. MkDocstrings - Auto-generate API documentation from Python code
  3. Awesome Nav - Automatic navigation from folder structure
  4. Section Index - Index pages for sections
  5. PyMdown Extensions - Extended Markdown features
  6. Swagger UI Tag - Interactive API documentation
  7. MkDocs Jupyter - Render Jupyter notebooks
  8. Macros - Jinja2 templating in Markdown

Mermaid2 Plugin

Purpose: Create diagrams and visualizations directly in Markdown using the Mermaid syntax.

What it does

Mermaid allows you to create flowcharts, sequence diagrams, gantt charts, class diagrams, and more using simple text-based syntax. The diagrams are rendered as SVG in your documentation.

How to use

Simply use a code fence with the mermaid language identifier:

Markdown
```mermaid
graph TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B
```

Example

graph TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B

Advanced Examples

Sequence Diagram:

sequenceDiagram
    participant User
    participant API
    participant Database
    User->>API: Request data
    API->>Database: Query
    Database-->>API: Results
    API-->>User: Response

Class Diagram:

classDiagram
    class Animal {
        +String name
        +int age
        +makeSound()
    }
    class Dog {
        +String breed
        +bark()
    }
    class Cat {
        +String color
        +meow()
    }
    Animal <|-- Dog
    Animal <|-- Cat

Configuration Options

  • version: Mermaid library version
  • theme: Color theme (base, dark, forest, neutral)
  • themeVariables: Custom theme colors

MkDocstrings Plugin

Purpose: Automatically generate API documentation from Python docstrings.

What it does

MkDocstrings parses your Python code and extracts docstrings to create formatted API documentation. It supports Google, NumPy, and Sphinx docstring styles.

How to use

Use the special syntax to include documentation for a Python module, class, or function:

Markdown
::: mymodule.MyClass
    options:
      show_source: true
      show_root_heading: true

Example

If you have a Python file utils.py:

Python
def calculate_total(items: list, tax_rate: float = 0.1) -> float:
    """
    Calculate the total price including tax.

    Args:
        items: List of item prices
        tax_rate: Tax rate as decimal (default: 0.1 for 10%)

    Returns:
        Total price including tax

    Examples:
        >>> calculate_total([10.0, 20.0, 30.0])
        66.0
    """
    subtotal = sum(items)
    return subtotal * (1 + tax_rate)

You can document it with:

Markdown
::: utils.calculate_total

Configuration Options

  • show_source: Display source code
  • show_root_heading: Show module/class name as heading
  • docstring_style: google, numpy, or sphinx
  • members_order: source, alphabetical
  • show_signature: Display function signatures
  • merge_init_into_class: Merge __init__ docstring into class docs

Awesome Nav Plugin

Purpose: Automatically generate navigation from your folder structure.

What it does

Instead of manually defining navigation in mkdocs.yml, Awesome Nav creates it automatically based on your file and folder organization. It supports section titles, custom ordering, and index pages.

How to use

Simply organize your docs in folders:

Text Only
docs/
├── index.md
├── guides/
│   ├── getting-started/
│   │   ├── index.md
│   │   └── installation.md
│   └── advanced/
│       └── configuration.md
└── api/
    └── reference.md

The navigation is created automatically based on this structure.

Advanced Usage

You can customize section titles by creating a .pages file:

YAML
title: User Guides
nav:
  - Getting Started: getting-started
  - Advanced Topics: advanced
  - ...

Or use special naming:

  • Files starting with numbers are ordered: 01-intro.md, 02-setup.md
  • index.md files become section index pages
  • Folder names are converted to titles automatically

Configuration Options

  • strict: Fail build on errors
  • show_nav_section_titles: Display section titles in navigation
  • collapse_single_pages: Collapse sections with only one page

Section Index Plugin

Purpose: Create index pages for documentation sections.

What it does

When a folder contains an index.md file, Section Index allows that page to represent the entire section in navigation. This creates a cleaner navigation structure where sections can have both an overview page and sub-pages.

How to use

Create an index.md in any folder:

Text Only
docs/
└── user-guide/
    ├── index.md          # Overview of user guide
    ├── installation.md
    └── configuration.md

The index.md becomes the landing page for the "User Guide" section.

Example Structure

Markdown
# User Guide

This section contains comprehensive guides for using the application.

## Topics Covered

- [Installation](installation.md)
- [Configuration](configuration.md)
- [Usage Examples](examples.md)

PyMdown Extensions

Purpose: Add powerful Markdown extensions for enhanced formatting.

What it does

PyMdown Extensions is a collection of extensions that add features like syntax highlighting, admonitions, tabbed content, task lists, and much more.

Key Features

1. Admonitions

Create callout boxes for notes, warnings, tips, etc.

Markdown
!!! note "Custom Title"
    This is a note admonition.

!!! warning
    This is a warning!

!!! tip "Pro Tip"
    Use admonitions to highlight important information.

Result:

Custom Title

This is a note admonition.

Warning

This is a warning!

Pro Tip

Use admonitions to highlight important information.

2. Code Highlighting

Enhanced syntax highlighting with line numbers and highlighting:

Python
def hello_world():
    message = "Hello, World!"
    print(message)
    return message

3. Tabbed Content

Create tabbed sections:

Python
print("Hello from Python!")
JavaScript
console.log("Hello from JavaScript!");
Bash
echo "Hello from Bash!"

Markdown:

Markdown
=== "Python"
    ```python
    print("Hello from Python!")
    ```

=== "JavaScript"
    ```javascript
    console.log("Hello from JavaScript!");
    ```

4. Task Lists

Create interactive checklists:

Markdown
- [x] Completed task
- [ ] Pending task
- [ ] Another pending task

Result:

  • Completed task
  • Pending task
  • Another pending task

5. Keys and Keyboard Shortcuts

Display keyboard shortcuts: Ctrl+Alt+Del

Markdown
Press ++ctrl+c++ to copy and ++ctrl+v++ to paste.

6. Math Support

Inline math: \(E = mc^2\)

Block math:

\[ \frac{n!}{k!(n-k)!} = \binom{n}{k} \]
Markdown
Inline: $E = mc^2$

Block:
$$
\frac{n!}{k!(n-k)!} = \binom{n}{k}
$$

7. Highlighting and Formatting

  • Highlighted text
  • Inserted text
  • Deleted text
  • H2O (subscript)
  • X2 (superscript)
Markdown
- ==Highlighted text==
- ^^Inserted text^^
- ~~Deleted text~~
- H~2~O
- X^2^

8. Details/Summary

Create collapsible sections:

Click to expand

Hidden content that can be revealed.

Markdown
??? note "Click to expand"
    Hidden content that can be revealed.

Configuration Options

All PyMdown extensions are pre-configured for maximum functionality including: - arithmatex: Math support - highlight: Code highlighting - superfences: Advanced code fences - tabbed: Tabbed content - tasklist: Task lists - emoji: Emoji support - magiclink: Auto-link URLs


Swagger UI Tag Plugin

Purpose: Embed interactive API documentation using OpenAPI/Swagger specifications.

What it does

This plugin embeds the Swagger UI interface directly into your documentation, allowing users to interact with your API documentation, test endpoints, and see request/response examples.

How to use

First, place your OpenAPI specification file (JSON or YAML) in your docs folder. Then use the special tag:

Markdown
<swagger-ui src="./openapi.json" />

Example

Markdown
# API Reference

Explore our REST API using the interactive documentation below:

<swagger-ui src="./api-spec.yaml" />

Configuration Options

  • background: Background color (White, Black)
  • docExpansion: none, list, full
  • filter: Enable search filter (true/false)
  • syntaxHighlightTheme: agate, arta, monokai, nord, etc.

Best Practices

  1. Keep your OpenAPI spec up to date
  2. Use descriptive operation IDs
  3. Include examples in your spec
  4. Document all parameters and responses
  5. Use tags to organize endpoints

MkDocs Jupyter Plugin

Purpose: Render Jupyter notebooks as documentation pages.

What it does

This plugin converts Jupyter notebooks (.ipynb files) into documentation pages, preserving code, output, and visualizations. Notebooks are NOT executed by default - they display saved outputs.

How to use

Simply place .ipynb files in your docs directory:

Text Only
docs/
├── index.md
└── tutorials/
    ├── data-analysis.ipynb
    └── visualization.ipynb

The notebooks will be automatically rendered as documentation pages.

Example Notebook Structure

A notebook with: - Markdown cells for documentation - Code cells with Python code - Output cells with results, tables, plots

Will be rendered with all content intact, including: - Interactive plots (if using Plotly) - DataFrames as formatted tables - Images and visualizations - Code with syntax highlighting

Configuration Options

  • include_source: Show code cells (true/false)
  • execute: Execute notebooks during build (false by default for safety)
  • allow_errors: Continue on errors when executing
  • ignore_h1_titles: Skip first heading
  • include_requirejs: Include RequireJS for interactive widgets

Best Practices

  1. Save all outputs before committing notebooks
  2. Keep notebooks focused on single topics
  3. Use markdown cells for explanations
  4. Clear unnecessary outputs to reduce file size
  5. Use descriptive cell outputs

Macros Plugin

Purpose: Use Jinja2 templating and variables in your Markdown files.

What it does

The Macros plugin allows you to define variables and macros that can be reused throughout your documentation. This is perfect for maintaining consistent values, generating dynamic content, and reducing repetition.

How to use

Variables

Create a docs/macros.py file:

Python
def define_env(env):
    """Define variables and macros"""
    env.variables['version'] = '2.0.0'
    env.variables['api_url'] = 'https://api.example.com'
    env.variables['company_name'] = 'Your Company'

Use in Markdown:

Markdown
The current version is {{ version }}.
API endpoint: {{ api_url }}

Macros (Functions)

In docs/macros.py:

Python
def define_env(env):
    @env.macro
    def button(text, link):
        return f'[{text}]({link}){{ .md-button }}'

    @env.macro
    def code_from_file(filename):
        with open(filename) as f:
            return f.read()

Use in Markdown:

Markdown
{{ button("Get Started", "/guides/getting-started/") }}

{{ code_from_file("examples/sample.py") }}

Includes

Use the include directive for reusable content:

Markdown
{% include 'includes/common-warning.md' %}

Configuration Options

  • module_name: Python module for macros
  • include_dir: Directory for include files
  • include_yaml: YAML files with variables
  • j2_block_start_string: Jinja2 block start (default: {%)
  • j2_variable_start_string: Jinja2 variable start (default: {{)

Use Cases

  1. Version numbers across documentation
  2. API endpoints and URLs
  3. Company/product names
  4. Reusable code snippets
  5. Dynamic tables and lists
  6. Conditional content

Material Theme Features

The Material theme provides additional features that enhance your documentation:

  • Instant loading: Fast page navigation without full reload
  • Navigation tabs: Top-level sections as tabs
  • Navigation sections: Collapsible sidebar sections
  • Table of contents: Sticky TOC on the right
  • Back to top: Button to scroll to top
  • Search suggestions: Auto-complete while typing
  • Search highlighting: Highlights search terms in results
  • Search sharing: Share search results via URL

Content Features

  • Code copy: One-click copy for code blocks
  • Code annotations: Add comments to specific lines
  • Content tabs: Tabbed content sections
  • Tooltips: Hover tooltips for abbreviations

Customization

The theme supports: - Light and dark mode toggle - Custom color schemes - Custom fonts - Custom CSS and JavaScript - Social links - Analytics integration


Tips for Maximum Effectiveness

1. Combine Plugins

Use multiple plugins together for powerful results:

Example combining diagrams and API docs:

Markdown
## Architecture

Here's our system architecture:

\`\`\`mermaid
graph LR
    A[Client] --> B[API Gateway]
    B --> C[Service Layer]
    C --> D[Database]
\`\`\`

And here's the implementation:

::: myapp.services.api_gateway

2. Use Admonitions for Important Info

Markdown
!!! warning "Breaking Change in v2.0"
    The API endpoint has changed from `/api/v1/` to `/api/v2/`

3. Organize with Folders

Use the folder structure for automatic navigation:

Text Only
docs/
├── index.md
├── guides/
│   ├── index.md
│   ├── beginner/
│   └── advanced/
├── api/
│   └── reference.md
└── examples/
    ├── python/
    └── javascript/

4. Leverage Macros for Consistency

Define common values once:

Python
env.variables['api_version'] = '2.0'
env.variables['base_url'] = 'https://api.example.com'

Use everywhere:

Markdown
Current API: v{{ api_version }}
Endpoint: {{ base_url }}/users

5. Document with Jupyter

Create interactive tutorials: - Load and analyze data - Show visualizations - Demonstrate API usage - Provide reproducible examples


Next Steps

Explore the detailed documentation for each plugin:

Or check out the Getting Started Guide for step-by-step instructions.