Skip to main content

mdBook Documentation

A comprehensive archetype for creating modern, searchable documentation sites using mdBook, the Rust-powered static site generator that transforms Markdown files into beautiful, interactive documentation.

Overview

This archetype provides a complete mdBook setup with best practices for technical documentation, including themes, plugins, automation, and deployment configurations. It's designed for teams that need professional documentation with minimal overhead.

Technology Stack

  • mdBook: Static site generator written in Rust
  • Markdown: Content authoring format
  • Mermaid: Diagram and flowchart integration
  • MathJax: Mathematical equation rendering
  • GitHub Actions: Automated builds and deployment
  • GitHub Pages: Static site hosting

Key Features

Content Authoring

  • Markdown Support: Write documentation in standard Markdown
  • Code Highlighting: Syntax highlighting for multiple languages
  • Mermaid Diagrams: Built-in support for flowcharts and diagrams
  • Mathematical Equations: LaTeX-style math rendering
  • Table of Contents: Automatic navigation generation

Interactive Features

  • Search: Full-text search across all content
  • Navigation: Sidebar navigation with collapsible sections
  • Print Support: Print-friendly CSS for offline documentation
  • Mobile Responsive: Optimized for mobile devices
  • Dark/Light Theme: Theme switching capability

Development Workflow

  • Live Reload: Instant preview during development
  • Git Integration: Version control for documentation
  • CI/CD: Automated building and deployment
  • Multi-format Output: HTML, PDF, and EPUB generation

Project Structure

mdbook-documentation/
├── book.toml # mdBook configuration
├── src/
│ ├── SUMMARY.md # Table of contents
│ ├── chapter_1/ # Content chapters
│ │ ├── README.md
│ │ ├── section_1.md
│ │ └── section_2.md
│ ├── chapter_2/
│ │ ├── README.md
│ │ └── advanced.md
│ ├── appendix/
│ │ ├── README.md
│ │ ├── glossary.md
│ │ └── references.md
│ └── assets/ # Images and static files
│ ├── images/
│ ├── diagrams/
│ └── downloads/
├── theme/ # Custom theme files
│ ├── index.hbs # HTML template
│ ├── head.hbs # Custom head content
│ ├── header.hbs # Custom header
│ ├── css/
│ │ ├── custom.css # Custom styles
│ │ └── variables.css # CSS variables
│ └── js/
│ └── custom.js # Custom JavaScript
├── .github/
│ └── workflows/
│ ├── deploy.yml # Deployment workflow
│ └── test.yml # Testing workflow
├── scripts/
│ ├── build.sh # Build script
│ ├── serve.sh # Development server
│ └── deploy.sh # Deployment script
├── .gitignore
├── README.md
└── LICENSE

Configuration

Book Configuration (book.toml)

[book]
authors = ["Your Name", "Team Members"]
language = "en"
multilingual = false
src = "src"
title = "Project Documentation"
description = "Comprehensive documentation for the project"

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

[preprocessor.katex]
command = "mdbook-katex"

[preprocessor.admonish]
command = "mdbook-admonish"
assets_version = "3.0.2"

[output.html]
additional-css = ["theme/css/custom.css"]
additional-js = ["theme/js/custom.js"]
default-theme = "light"
preferred-dark-theme = "navy"
curly-quotes = true
mathjax-support = true
copy-fonts = true
google-analytics = "GA-123456789"
edit-url-template = "https://github.com/your-org/docs/edit/main/{path}"
git-repository-url = "https://github.com/your-org/docs"
git-repository-icon = "fa-github"

[output.html.print]
enable = true

[output.html.search]
enable = true
limit-results = 30
teaser-word-count = 30
use-boolean-and = true
boost-title = 2
boost-hierarchy = 1
boost-paragraph = 1
expand = true
heading-split-level = 3

[output.html.redirect]
"/old-page.html" = "../new-page.html"

[output.html.playground]
runnable = true
copyable = true
copy-js = true
line-numbers = false
editable = false

# PDF output configuration
[output.pdf]
command = "mdbook-pdf"
optional = true

# EPUB output configuration
[output.epub]
command = "mdbook-epub"
optional = true

Table of Contents (src/SUMMARY.md)

# Summary

[Introduction](README.md)

# User Guide

- [Getting Started](getting-started/README.md)
- [Installation](getting-started/installation.md)
- [Quick Start](getting-started/quick-start.md)
- [Configuration](getting-started/configuration.md)

- [User Manual](user-manual/README.md)
- [Basic Usage](user-manual/basic-usage.md)
- [Advanced Features](user-manual/advanced-features.md)
- [Troubleshooting](user-manual/troubleshooting.md)

# Developer Guide

- [Development](development/README.md)
- [Architecture](development/architecture.md)
- [API Reference](development/api-reference.md)
- [Contributing](development/contributing.md)

- [Deployment](deployment/README.md)
- [Environment Setup](deployment/environment-setup.md)
- [Production Deployment](deployment/production.md)
- [Monitoring](deployment/monitoring.md)

# Reference

- [Appendix](appendix/README.md)
- [Glossary](appendix/glossary.md)
- [FAQ](appendix/faq.md)
- [References](appendix/references.md)

Content Examples

Basic Markdown with Code

# Getting Started

This guide will help you get started with the project quickly.

## Installation

Install the project using your preferred package manager:

```bash
# Using npm
npm install your-project

# Using yarn
yarn add your-project

# Using cargo
cargo install your-project
```

## Configuration

Create a configuration file:

```json
{
"name": "my-project",
"version": "1.0.0",
"settings": {
"debug": false,
"timeout": 5000
}
}
```

> **Note**: Make sure to update the configuration according to your environment.

Mermaid Diagrams

# System Architecture

The following diagram shows the system architecture:

```mermaid
graph TB
Client[Client Application]
API[API Gateway]
Auth[Authentication Service]
DB[(Database)]
Cache[(Redis Cache)]

Client --> API
API --> Auth
API --> DB
API --> Cache
Auth --> DB
```

## Sequence Diagram

Here's how the authentication flow works:

```mermaid
sequenceDiagram
participant C as Client
participant A as API
participant AS as Auth Service
participant DB as Database

C->>A: Login Request
A->>AS: Validate Credentials
AS->>DB: Check User
DB-->>AS: User Data
AS-->>A: JWT Token
A-->>C: Authentication Response
```

Mathematical Equations

# Mathematical Formulas

The quadratic formula is:

\\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \\]

For inline math, use single dollar signs: \\( E = mc^2 \\)

## Complex Equations

The Fourier transform:

\\[ F(\omega) = \int_{-\infty}^{\infty} f(t) e^{-i\omega t} dt \\]

Admonitions and Callouts

# Important Information

```admonish note
This is a note admonition. Use it for general information.
This is a warning. Use it to highlight potential issues.
This is a danger admonition. Use it for critical warnings.
This is a tip. Use it for helpful suggestions.
This is an example admonition with some sample code:

\`\`\`rust
fn main() {
println!("Hello, world!");
}
\`\`\`

## Custom Styling

### CSS Variables (theme/css/variables.css)
```css
:root {
/* Brand colors */
--primary-color: #0066cc;
--secondary-color: #004499;
--accent-color: #ff6b35;

/* Typography */
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
--code-font-family: 'JetBrains Mono', 'Fira Code', monospace;

/* Layout */
--sidebar-width: 280px;
--content-max-width: 800px;

/* Dark theme */
--dark-bg: #1a1a1a;
--dark-fg: #e6e6e6;
--dark-sidebar-bg: #2d2d2d;
}

Custom Styles (theme/css/custom.css)

/* Custom header styling */
.header-wrapper {
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
color: white;
padding: 1rem 2rem;
margin-bottom: 2rem;
}

.header-wrapper h1 {
margin: 0;
font-weight: 600;
}

/* Code block enhancements */
.hljs {
border-radius: 8px;
padding: 1.5rem;
position: relative;
}

.hljs::before {
content: attr(data-lang);
position: absolute;
top: 0.5rem;
right: 1rem;
font-size: 0.8rem;
color: #888;
text-transform: uppercase;
}

/* Responsive tables */
.table-wrapper {
overflow-x: auto;
margin: 1rem 0;
}

table {
border-collapse: collapse;
width: 100%;
min-width: 600px;
}

th, td {
border: 1px solid #ddd;
padding: 0.75rem;
text-align: left;
}

th {
background-color: var(--table-header-bg);
font-weight: 600;
}

/* Navigation improvements */
.chapter-item {
margin: 0.25rem 0;
}

.chapter-item > a {
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.2s;
}

.chapter-item > a:hover {
background-color: var(--sidebar-active);
}

/* Search enhancements */
#searchbar {
border-radius: 20px;
padding: 0.75rem 1rem;
border: 2px solid var(--searchbar-border-color);
}

#searchresults-outer {
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

Custom JavaScript (theme/js/custom.js)

// Add copy button to code blocks
document.addEventListener('DOMContentLoaded', function() {
const codeBlocks = document.querySelectorAll('pre code');

codeBlocks.forEach(function(codeBlock) {
const pre = codeBlock.parentNode;
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.textContent = 'Copy';

copyButton.addEventListener('click', function() {
navigator.clipboard.writeText(codeBlock.textContent);
copyButton.textContent = 'Copied!';
setTimeout(() => {
copyButton.textContent = 'Copy';
}, 2000);
});

pre.appendChild(copyButton);
});
});

// Add reading time estimation
document.addEventListener('DOMContentLoaded', function() {
const content = document.querySelector('#content main');
if (content) {
const text = content.textContent || content.innerText || '';
const wordsPerMinute = 200;
const words = text.trim().split(/\s+/).length;
const readingTime = Math.ceil(words / wordsPerMinute);

const readingTimeElement = document.createElement('div');
readingTimeElement.className = 'reading-time';
readingTimeElement.textContent = `${readingTime} min read`;

const titleElement = content.querySelector('h1');
if (titleElement) {
titleElement.parentNode.insertBefore(readingTimeElement, titleElement.nextSibling);
}
}
});

Automation and Deployment

GitHub Actions Workflow (.github/workflows/deploy.yml)

name: Deploy mdBook

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
with:
mdbook-version: 'latest'

- name: Install mdBook plugins
run: |
cargo install mdbook-mermaid
cargo install mdbook-katex
cargo install mdbook-admonish

- name: Test build
run: mdbook test

deploy:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main'

steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
with:
mdbook-version: 'latest'

- name: Install mdBook plugins
run: |
cargo install mdbook-mermaid
cargo install mdbook-katex
cargo install mdbook-admonish

- name: Build book
run: |
mdbook-admonish install
mdbook-mermaid install
mdbook build

- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book
cname: docs.your-domain.com

Build Scripts

Development Server (scripts/serve.sh)

#!/bin/bash

echo "Starting mdBook development server..."

# Install plugins if not already installed
if ! command -v mdbook-mermaid &> /dev/null; then
echo "Installing mdbook-mermaid..."
cargo install mdbook-mermaid
fi

if ! command -v mdbook-katex &> /dev/null; then
echo "Installing mdbook-katex..."
cargo install mdbook-katex
fi

if ! command -v mdbook-admonish &> /dev/null; then
echo "Installing mdbook-admonish..."
cargo install mdbook-admonish
fi

# Install admonish assets
mdbook-admonish install

# Start development server
mdbook serve --open --hostname 0.0.0.0 --port 3000

Production Build (scripts/build.sh)

#!/bin/bash

echo "Building mdBook for production..."

# Clean previous build
rm -rf book/

# Install plugin assets
mdbook-admonish install
mdbook-mermaid install

# Build the book
mdbook build

# Optimize images (optional)
if command -v imageoptim &> /dev/null; then
echo "Optimizing images..."
imageoptim book/images/
fi

echo "Build completed successfully!"
echo "Output directory: ./book/"

Advanced Features

Custom Preprocessors

// src/preprocessor.rs
use mdbook::book::Book;
use mdbook::errors::Error;
use mdbook::preprocess::{Preprocessor, PreprocessorContext};

pub struct CustomPreprocessor;

impl Preprocessor for CustomPreprocessor {
fn name(&self) -> &str {
"custom-preprocessor"
}

fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book, Error> {
// Custom preprocessing logic
// For example, add automatic glossary links

book.for_each_mut(|item| {
if let mdbook::BookItem::Chapter(ref mut chapter) = item {
chapter.content = process_glossary_links(&chapter.content);
}
});

Ok(book)
}
}

fn process_glossary_links(content: &str) -> String {
// Implementation for automatic glossary linking
content.to_string()
}

Multi-language Support

# book.toml
[book]
multilingual = true

[book.language.en]
title = "Project Documentation"

[book.language.es]
title = "Documentación del Proyecto"

[book.language.fr]
title = "Documentation du Projet"

PDF Generation

# Install mdbook-pdf
cargo install mdbook-pdf

# Add to book.toml
[output.pdf]
command = "mdbook-pdf"
optional = true

Usage Examples

API Documentation

# API Reference

## Authentication

All API requests must include an authentication token in the header:

```http
GET /api/v1/users
Authorization: Bearer your-jwt-token
Content-Type: application/json
```

## Endpoints

### GET /api/v1/users

Retrieve a list of users.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | integer | No | Maximum number of users to return (default: 10) |
| `offset` | integer | No | Number of users to skip (default: 0) |
| `filter` | string | No | Filter users by name or email |

**Response:**

```json
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T00:00:00Z"
}
],
"total": 1,
"limit": 10,
"offset": 0
}
```

Tutorials with Step-by-Step Instructions

# Tutorial: Building Your First Application

## Step 1: Project Setup

Create a new project directory:

```bash
mkdir my-project
cd my-project
```

## Step 2: Initialize Configuration

Create the configuration file:

```bash
cat > config.json << EOF
{
"name": "my-project",
"version": "1.0.0"
}
EOF
```

```admonish tip
You can also copy the configuration from our [templates repository](https://github.com/org/templates).
```

## Step 3: Install Dependencies

```bash
npm install
# or
yarn install
```

## Step 4: Run the Application

```bash
npm start
```

Your application should now be running at `http://localhost:3000`.

Quick Start

  1. Generate the documentation project:

    archetect render git@github.com:p6m-archetypes/mdbook.archetype.git
  2. Install mdBook and plugins:

    cargo install mdbook
    cargo install mdbook-mermaid
    cargo install mdbook-katex
    cargo install mdbook-admonish
  3. Start development server:

    chmod +x scripts/serve.sh
    ./scripts/serve.sh
  4. Edit content:

    # Edit src/SUMMARY.md to add chapters
    # Add Markdown files in src/ directory
    # Customize theme in theme/ directory
  5. Build for production:

    chmod +x scripts/build.sh
    ./scripts/build.sh

Best Practices

Content Organization

  • Use descriptive file names and directory structure
  • Keep chapters focused on single topics
  • Include comprehensive table of contents
  • Add cross-references between related sections

Writing Style

  • Write clear, concise explanations
  • Include code examples for technical concepts
  • Use consistent terminology throughout
  • Add diagrams for complex processes

Maintenance

  • Set up automated builds and deployment
  • Use version control for all content
  • Regular review and updates
  • Collect feedback from users

Performance

  • Optimize images and assets
  • Use efficient search configuration
  • Minimize custom JavaScript
  • Consider CDN for static assets