Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

mdbook-mermaid-mmdr is an mdbook preprocessor that renders Mermaid diagrams to SVG at build time.

Unlike client-side approaches that rely on the Mermaid JavaScript library, or tools that shell out to Node.js / Puppeteer, this preprocessor uses mermaid-rs-renderer — a pure Rust Mermaid renderer. The result is static SVG embedded directly in your book’s HTML.

Key Features

  • Server-Side Rendering — Diagrams are rendered during mdbook build, not in the reader’s browser.
  • Zero Client-Side JavaScript — No heavy JS bundles or runtime rendering overhead.
  • Pure Rust — No Node.js, npm, or Puppeteer dependency. Just cargo install.
  • Configurable Themes — Choose between built-in themes or override individual theme variables.
  • Robust Error Handling — Invalid diagrams produce inline error messages instead of failing the build.

How It Works

  1. mdbook invokes the preprocessor before the HTML renderer.
  2. The preprocessor scans each chapter’s Markdown for fenced code blocks tagged mermaid.
  3. Each mermaid block is rendered to SVG via mermaid-rs-renderer.
  4. The SVG replaces the original code block, wrapped in <div class="mermaid-mmdr-svg">.
  5. mdbook continues with the modified Markdown as usual.

Because the SVG is inlined at build time, the resulting book works without any JavaScript and renders correctly even in environments where scripts are blocked.

Live Example

This very book uses mdbook-mermaid-mmdr to render its diagrams. Here is the preprocessor pipeline visualized:

Markdown withmermaid blocksmdbook-mermaid-mmdrMarkdown withinline SVGmdbook HTML rendererStatic HTML book

Getting Started

Installation

From source

cargo install --path .

From crates.io

cargo install mdbook-mermaid-mmdr

Make sure the installed binary is on your PATH.

Linux dependency

On Linux, the font/SVG rendering stack requires fontconfig development headers:

sudo apt-get install -y libfontconfig1-dev

Setup

Add the preprocessor to your book.toml:

[preprocessor.mermaid-mmdr]
command = "mdbook-mermaid-mmdr"

The command field is optional if the binary is already in your PATH and named mdbook-mermaid-mmdr.

Writing Mermaid Diagrams

Use standard fenced code blocks with the mermaid language tag:

```mermaid
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
```

When you run mdbook build, the code block is replaced with an inline SVG.

Running the Examples

The repository includes example books under examples/:

ExampleDescription
simpleA minimal book with a single flowchart
comprehensiveAll supported diagram types and customization
themedCustom theme variables via book.toml

To build an example:

cargo build
cd examples/simple
mdbook build
open book/index.html

Configuration

All configuration lives in your book.toml under the [preprocessor.mermaid-mmdr] table. Every field is optional.

Full Example

[preprocessor.mermaid-mmdr]
command = "mdbook-mermaid-mmdr"
theme = "modern"
background = "#ffffff"

[preprocessor.mermaid-mmdr.theme_variables]
primary_color = "#ffcccc"
line_color = "#ff0000"
secondary_color = "#ccffcc"

Reference

theme

The base theme for rendering. Accepted values:

ValueEffect
"default" or "mermaid"The classic Mermaid color scheme (Theme::mermaid_default())
"modern"A cleaner, modern palette (Theme::modern())
(any other string)Falls back to "modern"
(omitted)Uses mermaid-rs-renderer’s default

For fine-grained theme control beyond these two base themes, use theme_variables or inline %%{init: ...}%% directives in the diagram source.

background

A CSS color string for the diagram background (e.g., "#ffffff", "transparent"). Overrides the background from the selected theme.

theme_variables

A TOML table of key-value overrides merged into the resolved theme. This lets you tweak individual colors without replacing the entire theme.

[preprocessor.mermaid-mmdr.theme_variables]
primary_color = "#4a86c8"
primary_text_color = "#ffffff"
line_color = "#333333"

The keys correspond to fields on mermaid-rs-renderer’s Theme struct. Unknown keys are silently ignored.

Diagram Types

mdbook-mermaid-mmdr supports all diagram types provided by mermaid-rs-renderer. Below are examples of the most commonly used types. Each section shows the Markdown source followed by the live rendered result.

Flowchart

```mermaid
flowchart LR
    A[Start] --> B{Decision}
    B -->|Yes| C[OK]
    B -->|No| D[Not OK]
```
YesNoStartDecisionOKNot OK

Sequence Diagram

```mermaid
sequenceDiagram
    participant A as Alice
    participant B as Bob
    A->>B: Hello Bob
    B-->>A: Hi Alice
    A->>B: How are you?
    B-->>A: Great!
```
Hello BobHi AliceHow are you?Great!AliceBobAliceBob

Class Diagram

```mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound()
    }
    class Dog {
        +fetch()
    }
    Animal <|-- Dog
```
Animal+String name+int age+makeSound()Dog+fetch()

State Diagram

```mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : start
    Processing --> Done : complete
    Processing --> Error : fail
    Error --> Idle : reset
    Done --> [*]
```
startcompletefailresetDoneErrorIdleProcessing

Entity Relationship Diagram

```mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    PRODUCT ||--o{ LINE-ITEM : "is in"
```
placescontains"is in"CUSTOMERLINE-ITEMORDERPRODUCT

Gantt Chart

```mermaid
gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    section Phase 1
    Research       :a1, 2024-01-01, 30d
    Design         :a2, after a1, 20d
    section Phase 2
    Implementation :b1, after a2, 40d
    Testing        :b2, after b1, 15d
```
Project Timeline2024-01-012024-01-272024-02-232024-03-202024-04-15Phase 1Phase 2ResearchDesignImplementationTesting

Pie Chart

```mermaid
pie title Language Distribution
    "Rust" : 60
    "Python" : 25
    "Other" : 15
```
60%25%15%RustPythonOtherLanguage Distribution

Mindmap

```mermaid
mindmap
    root((Project))
        Frontend
            React
            CSS
        Backend
            Rust
            Database
        DevOps
            CI/CD
            Monitoring
```
BackendCI/CDCSSDatabaseDevOpsFrontendMonitoringReactRustProject

Inline Theme Directives

You can override the theme on a per-diagram basis using Mermaid’s %%{init: ...}%% directive:

```mermaid
%%{init: {"theme": "forest"}}%%
graph LR
    A --> B --> C
```
ABC

For the full list of supported diagram types, see the mermaid-rs-renderer documentation.

Theme Customization

There are three levels of theme control, from broadest to most specific.

1. Base Theme in book.toml

Set the theme field to choose the overall color scheme:

[preprocessor.mermaid-mmdr]
theme = "modern"

See the Configuration chapter for the full list of accepted values.

2. Theme Variable Overrides

Override individual theme properties while keeping the rest of the base theme:

[preprocessor.mermaid-mmdr]
theme = "modern"

[preprocessor.mermaid-mmdr.theme_variables]
primary_color = "#ffcccc"
line_color = "#ff0000"
secondary_color = "#ccffcc"

The override is applied by serializing the resolved theme to JSON, merging in your key-value pairs, and deserializing back. This means any field on the Theme struct is a valid key.

3. Per-Diagram Inline Directives

For one-off customization, use Mermaid’s native %%{init: ...}%% directive at the top of a diagram:

```mermaid
%%{init: {"theme": "forest", "themeVariables": {"primaryColor": "#ff0000"}}}%%
graph TD
    A --> B
```

This applies only to the single diagram and takes precedence over book.toml settings.

Here is a live example using the default theme configured for this book:

Theme from book.tomltheme_variables overridePer-diagram init directive

Background Color

The background color is independent of the theme and can be set separately:

[preprocessor.mermaid-mmdr]
background = "#ffffff"

Set it to "transparent" if you want the diagram to inherit the page background.

CSS Styling

Every rendered diagram is wrapped in a <div class="mermaid-mmdr-svg"> element. You can target this class in a custom mdbook theme to add margins, borders, or other styling:

.mermaid-mmdr-svg {
    text-align: center;
    margin: 1em 0;
}

.mermaid-mmdr-svg svg {
    max-width: 100%;
    height: auto;
}

Error Handling

mdbook-mermaid-mmdr is designed to never fail the build, even when a diagram is invalid.

Inline Error Messages

When a mermaid code block fails to render, the preprocessor replaces it with an HTML error block:

<pre class="mermaid-error">Error: &lt;error details&gt;</pre>

A warning is also logged to stderr. The rest of the book continues to build normally.

Styling Errors

You can style error blocks in a custom mdbook theme:

.mermaid-error {
    color: #cc0000;
    background: #fff0f0;
    border: 1px solid #cc0000;
    padding: 1em;
    border-radius: 4px;
}

Debugging

Set the RUST_LOG environment variable to see detailed output:

RUST_LOG=debug mdbook build

The preprocessor logs theme resolution, rendering attempts, and any SVG post-processing at the debug and warn levels.