name: mdbook path: book.toml description: Build documentation books with mdbook — SUMMARY.md structure, chapter organization, themes, search, preprocessors, static HTML generation, GitHub Pages deployment. license: MIT
mdbook Skill
mdbook is a Rust tool for creating modern books from Markdown files. It's used extensively in the Rust ecosystem (The Rust Book, Rust by Example) and is excellent for technical documentation.
Quick Reference: CLI Commands
| Command | Description |
|---|---|
mdbook init <dir> |
Initialize new book in directory |
mdbook build |
Build the book (outputs to book/ dir) |
mdbook serve |
Serve book locally with live reload |
mdbook watch |
Watch for changes and rebuild |
mdbook test |
Run tests in Rust code blocks |
mdbook clean |
Remove built book directory |
mdbook dump-ast |
Print AST of markdown files |
Common Flags
| Flag | Description |
|---|---|
-d, --dest-dir |
Output directory (default: book/) |
-o, --open |
Open browser after serving |
-p, --port |
Port for serve (default: 3000) |
-l, --language |
Language for search |
1. Quick Start
Installation
# Via cargo (recommended)
cargo install mdbook
# Via package managers
# macOS
brew install mdbook
# Arch Linux
pacman -S mdbook
# Debian/Ubuntu
apt install mdbook
# Windows (via cargo or releases)
cargo install mdbook
Initialize a New Book
# Create new book in my-book directory
mdbook init my-book
# With custom theme (creates theme/ directory)
mdbook init --theme my-book
# With ignore file
mdbook init --ignore my-book
This creates:
my-book/
├── book.toml # Book configuration
├── src/
│ └── SUMMARY.md # Chapter list
└── theme/
├── index.js # Custom JavaScript
├── index.css # Custom styles
└── book.js # Theme JavaScript
Development Server
# Serve with live reload (default port 3000)
mdbook serve
# Open in browser automatically
mdbook serve --open
# Custom port
mdbook serve -p 8080
# Watch only (no server, just rebuild on changes)
mdbook watch
Build for Production
# Build to book/ directory
mdbook build
# Custom output directory
mdbook build -d dist
2. Book Structure
Directory Layout
book/
├── book.toml # Configuration
├── src/
│ ├── SUMMARY.md # Required: chapter order
│ ├── chapter1.md
│ ├── chapter2.md
│ └── images/ # Local images
├── theme/ # Optional custom theme
│ ├── index.css
│ ├── index.js
│ ├── book.js
│ └── fonts/
└── book/ # Output directory
└── index.html
book.toml Configuration
[book]
title = "My Book Title"
authors = ["Author Name"]
description = "Book description"
src = "src"
language = "en"
[build]
build-dir = "book"
create-missing = true
[output.html]
additional-css = ["custom.css"]
additional-js = ["custom.js"]
google-analytics = "UA-XXXXX"
SUMMARY.md Format
The SUMMARY.md defines chapter order and structure:
# Summary
[Introduction](./intro.md)
- [Getting Started](./getting-started.md)
- [Installation](./getting-started/installation.md)
- [Configuration](./getting-started/config.md)
- [Chapter 1](./chapter1.md)
- [Section 1.1](./chapter1/section1.md)
[Appendix](./appendix.md)
[Conclusion](./conclusion.md)
Rules:
- Must start with
# Summaryheader - Links are relative to
src/directory - Indented items become subsections
- First link is often the intro (no requirement)
- Use
[Title](./path.md)format
Front Matter (Optional)
Add metadata at the top of markdown files:
---
title: Chapter Title
description: Chapter description for SEO
license: MIT
---
# Chapter Title
Content starts here...
3. Markdown Features
mdbook supports standard Markdown plus extensions:
Admonitions (Note Blocks)
> **Note**: This is a note.
> **Warning**: Be careful with this!
> **Tip**: Here's a helpful tip.
> **Danger**: Warning message.
Renders as styled boxes. Types: note, warning, tip, danger, info.
Task Lists
- [ ] Unchecked task
- [x] Completed task
Tables
| Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- |
| Cell 1 | Cell 2 | Cell 3 |
| Cell 4 | Cell 5 | Cell 6 |
Footnotes
Here is a footnote[^1].
[^1]: Here is the footnote content.
Smart Punctuation
Automatic conversion:
...→…(ellipsis)--→–(en dash)---→—(em dash)"quote"→ "curly quotes"
Code Blocks with Syntax Highlighting
```rust
fn main() {
println!("Hello, world!");
}
```
Supported languages: rust, python, javascript, typescript, go, java, c, cpp, bash, json, yaml, toml, sql, html, css, and many more.
Heading Anchors
Headings automatically get anchors for linking:
## My Heading {#custom-id}
Links
[Internal link](./chapter.md) [External link](https://example.com)
[Link with title](./chapter.md "Title")
4. Configuration (book.toml)
Essential Options
[book]
title = "Book Title"
authors = ["Author <email@example.com>"]
description = "Description for search engines"
src = "src"
language = "en"
[build]
build-dir = "book"
create-missing = true # Auto-create missing SUMMARY.md entries
HTML Output Options
[output.html]
# Custom CSS/JS
additional-css = ["custom.css"]
additional-js = ["custom.js"]
# Theme options
theme = "theme/" # Custom theme directory
theme-rtl = "theme-rtl/" # RTL theme
# Search
search.enable = true
search.separator = "\\s+"
search.preload = ["en"]
# GitHub editing
edit-url-base = "https://github.com/user/repo/edit/main/src"
# Navigation
disable-children-links = false
footnote-section = "Footnotes"
# Analytics
google-analytics = "UA-XXXXX"
# Static files
static-files = ["images/"]
# Custom favicon
favicon-path = "favicon.png"
# Copy fonts
copy-fonts = true
[output.html.index-route] # Custom home page
index = "intro.md"
[output.html.redirect] # URL redirects
"/old-page" = "/new-page"
Table of Contents
[output.html.toc]
# Levels shown in table of contents
included-level = 3
Playground (Interactive Code)
[output.html.playground]
editable = true # Allow editing
copyable = true # Show copy button
line-numbers = false # Show line numbers
5. CLI Commands Detail
mdbook build
# Build with custom config
mdbook build --config book.toml
# Build specific directory
mdbook build ./my-book
# Verbose output
mdbook build -v
mdbook serve
# Basic serve
mdbook serve
# Custom host/port
mdbook serve -p 3000 -h 127.0.0.1
# Open browser
mdbook serve -o
# Don't open (useful in containers)
mdbook serve --no-open
# Live reload port (websocket)
mdbook serve --livereload 3001
mdbook watch
# Watch for changes
mdbook watch
# With custom config
mdbook watch --config book.toml
# Watch specific dir
mdbook watch ./docs
mdbook test
Tests Rust code examples in code blocks. See Section 6.
mdbook clean
# Clean build directory
mdbook clean
# Clean specific dir
mdbook clean ./my-book
6. Testing Code (mdbook test)
mdbook can test Rust code examples in your book.
Basic Usage
mdbook test
This finds all rust code blocks and runs them as tests.
Ignored Code
```rust,ignore
// This won't be tested
let x = unimplemented!();
```
### No-Run Code
```markdown
```rust,no_run
// Compiles but doesn't run
// Useful for code that won't compile in tests
### Should Panic
```markdown
```rust,should_panic
#[should_panic]
fn test_panic() {
panic!("This test passes if it panics");
}
### Hidden Code
```markdown
```rust,hidden
// Not displayed in book but included in tests
use crate::helper;
### Multiple Attributes
```markdown
```rust,ignore,no_run
// Ignored and not run
### Dependencies
```toml
[output.html.playground]
rust-replacements = [
"fn main() => || {", main() for snippets # Replace fn
]
7. Preprocessors
Preprocessors extend mdbook functionality. Install via cargo, enable in book.toml.
mdbook-mermaid (Diagrams)
cargo install mdbook-mermaid
[preprocessor.mermaid]
renderers = ["html"]
```mermaid
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Do Something]
B -->|No| D[Do Something Else]
```
```text
```
mdbook-admonish (Enhanced Admonitions)
cargo install mdbook-admonish
[preprocessor.admonish]
renderers = ["html"]
:::note This is a note. :::
:::tip[Custom Title] This is a tip with custom title. :::
:::warning This is a warning. :::
:::danger This is a danger box. :::
mdbook-katex (Math)
cargo install mdbook-katex
[preprocessor.katex]
renderers = ["html"]
[katex]
# Optional: custom KaTeX options
Inline math: $E = mc^2$
Block math: $$
\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}
$$
mdbook-toc (Table of Contents)
cargo install mdbook-toc
[preprocessor.toc]
renderers = ["html"]
Adds inline TOC to chapters.
mdbook-d2 (D2 Diagrams)
cargo install mdbook-d2
[preprocessor.d2]
renderers = ["html"]
```d2
shape: schema
books: {
shape: sql_table
columns: {
id: int
title: string
author_id: int
}
}
authors: {
shape: sql_table
columns: {
id: int
name: string
}
}
books.author_id -> authors.id
```
### mdbook-plantuml
```bash
cargo install mdbook-plantuml
[preprocessor.plantuml]
plantuml = "plantuml" # Or path to plantuml jar
All Preprocessors
# Install all common ones
cargo install mdbook-mermaid mdbook-admonish mdbook-katex mdbook-d2 mdbook-toc mdbook-linkcheck
8. Theming
Custom CSS
Create theme/index.css:
/* Override theme colors */
:root {
--bg: #ffffff;
--fg: #333333;
--sidebar-bg: #f5f5f5;
--theme-anchors: #0066cc;
}
/* Custom page styling */
.page {
font-family: "Inter", system-ui, sans-serif;
}
/* Code blocks */
.highlight {
border-radius: 8px;
}
Custom JavaScript
Create theme/index.js:
// Custom JavaScript for interactivity
document.addEventListener("DOMContentLoaded", () => {
// Add custom functionality
console.log("Book loaded!");
});
Override Theme Files
theme/
├── index.css # Your CSS overrides
├── index.js # Your JS
├── book.js # Override default book.js
├── head.hbs # Custom HTML head content
├── header.hbs # Custom header
└── footer.hbs # Custom footer
fonts
@font-face {
font-family: "Custom Font";
src: url("fonts/custom.woff2") format("woff2");
}
9. Diagrams
Mermaid Diagrams
Install mdbook-mermaid, then:
```mermaid
sequenceDiagram
participant A as Alice
participant B as Bob
A->>B: Hello Bob!
B-->>A: Hi Alice!
```
```text
```
Supported diagram types:
- Flowcharts (graph, flowchart)
- Sequence diagrams
- Class diagrams
- State diagrams
- ER diagrams
- Gantt charts
- Pie charts
D2 Diagrams
Install mdbook-d2 for modern diagrams:
`````d2
input: shape circle
output: shape circle
input -> output: data flow
````text
`````
PlantUML
Install mdbook-plantuml:
@startuml
Alice -> Bob: Hello
Bob --> Alice: Hi!
@enduml
Images

<!-- With size -->
<img src="images/diagram.png" width="500" />
10. Deployment
GitHub Pages (Recommended)
Create .github/workflows/deploy.yml:
name: Deploy Book
on:
push:
branches: [main]
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install mdbook
uses: rust-lang/actions/setup@v2
with:
toolchain: stable
- run: cargo install mdbook
- name: Build book
run: mdbook build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book
Enable GitHub Pages in repo settings → Pages → Source: "Deploy from a branch" → branch: gh-pages
Netlify
Create netlify.toml:
[build]
command = "mdbook build"
publish = "book"
[build.environment]
MDBOOK_VERSION = "latest"
Vercel
Create vercel.json:
{
"buildCommand": "mdbook build",
"outputDirectory": "book",
"installCommand": "cargo install mdbook"
}
Docker
FROM rust:latest AS builder
RUN cargo install mdbook
COPY . /app
WORKDIR /app
RUN mdbook build
FROM nginx:alpine
COPY --from=builder /app/book /usr/share/nginx/html
EXPOSE 80
11. Best Practices
Directory Structure for Large Books
src/
├── SUMMARY.md
├── part1/
│ ├── SUMMARY.md
│ ├── chapter1.md
│ └── chapter2.md
├── part2/
│ ├── SUMMARY.md
│ ├── chapter3.md
│ └── chapter4.md
├── reference/
│ ├── SUMMARY.md
│ └── api.md
└── assets/
├── images/
└── diagrams/
Each part has its own SUMMARY.md for modularity.
Versioning
[output.html]
# Add version selector
git-repository-url = "https://github.com/user/repo"
git-repository-branch = "main"
Search Optimization
[output.html.search]
preload = ["en", "de"] # Languages to preload
Performance Tips
- Lazy load images: Use proper image formats (WebP)
- Minimize custom JS: Each script slows loading
- Use preprocessors sparingly: Each adds build time
- Enable cache headers: Configure in deployment
Common Issues
| Issue | Solution |
|---|---|
| Images not showing | Use relative paths from src/ |
| Code not tested | Add rust language tag to code blocks |
| Build fails | Check SUMMARY.md for broken links |
| Search not working | Verify language is set correctly |
12. Useful Tips & Tricks
Auto-generate SUMMARY from files
# Use a script to generate SUMMARY.md
ls -1 src/**/*.md | sed 's|^src/| - |' | sed 's|\.md$||'
Preview while editing
mdbook watch -p 3000 -o &
# Opens browser, rebuilds on file changes
Check links
Install mdbook-linkcheck:
cargo install mdbook-linkcheck
[preprocessor.linkcheck]
Multi-language books
[book]
title = "My Book"
[output.html.print]
enable = true # Generate print-friendly version
PDF Export
Use browser print to PDF, or:
mdbook build
# Then use tools likewkhtmltopdf
Related Skills
- rust: For writing Rust code examples in your book
- documentation: For writing effective documentation
- cli-design: For creating CLI tools that use mdbook output
(End of file)