---
obj: application
website: https://rust-lang.github.io/mdBook/
repo: https://github.com/rust-lang/mdBook
rev: 2025-05-21
---

# mdbook
`mdBook` is a command-line tool for creating books from Markdown files. It is designed to generate a static website based on Markdown content, perfect for creating online documentation, tutorials, and books. It is similar to GitBook but is written in Rust and is fully open-source.

## Usage
The basic command for `mdBook` is as follows:

```bash
mdbook <command> [options]
```

### Available Commands

* `init`: Creates a new book in the current directory.
* `build`: Builds the book (default).
* `serve`: Serves the book locally with hot reloading.
* `test`: Runs tests on the book.
* `clean`: Cleans the book’s build artifacts.
* `watch`: Watches for file changes and rebuilds the book.

### Examples

1. **Building the book**:

   ```bash
   mdbook build
   ```

2. **Serving the book locally**:

   ```bash
   mdbook serve
   ```

3. **Initializing a new book**:

   ```bash
   mdbook init my-book
   ```

   This creates a new directory called `my-book` and sets up a template for your book.

## Book Format
The structure of the book’s source directory typically looks like this:

```
my-book/
├── src/
│   ├── SUMMARY.md
│   ├── chapter_1.md
│   ├── chapter_2.md
│   └── ...
├── book.toml
└── README.md
```

### Key Files and Directories
* `src/`: Contains the Markdown files for your book. This is where the content resides.
  * `SUMMARY.md`: This file defines the table of contents and chapter structure of your book. It lists all of the sections and their hierarchical order.
  * Other `.md` files: The content for each chapter or section of the book.
* `book.toml`: The configuration file that defines the metadata and settings for the book (e.g., title, author, theme).
* `README.md`: This file is optional and provides a description of your book.

### Configuration File (`book.toml`)
The `book.toml` file contains configuration settings for the book. Below is an example configuration:

```toml
[book]
title = "Example book"
authors = ["John Doe"]
description = "The example book covers examples."

[rust]
edition = "2018"

[build]
build-dir = "my-example-book"
create-missing = false

[preprocessor.index]

[preprocessor.links]

[output.html]
additional-css = ["custom.css"]

[output.html.search]
limit-results = 15
```

### `SUMMARY.md` file
The summary file is used by mdBook to know what chapters to include, in what order they should appear, what their hierarchy is and where the source files are. Without this file, there is no book.

This markdown file must be named `SUMMARY.md`. Its formatting is very strict and must follow the structure outlined below to allow for easy parsing. Any element not specified below, be it formatting or textual, is likely to be ignored at best, or may cause an error when attempting to build the book.

#### Structure
- `Title` - While optional, it’s common practice to begin with a title, generally `# Summary`. This is ignored by the parser however, and can be omitted.
```md
# Summary
```

- `Prefix Chapter` - Before the main numbered chapters, prefix chapters can be added that will not be numbered. This is useful for forewords, introductions, etc. There are, however, some constraints. Prefix chapters cannot be nested; they should all be on the root level. And you cannot add prefix chapters once you have added numbered chapters.
```md
[A Prefix Chapter](relative/path/to/markdown.md)

- [First Chapter](relative/path/to/markdown2.md)
```

- `Part Title` - Level 1 headers can be used as a title for the following numbered chapters. This can be used to logically separate different sections of the book. The title is rendered as unclickable text. Titles are optional, and the numbered chapters can be broken into as many parts as desired. Part titles must be h1 headers (one `#`), other heading levels are ignored.
```md
# My Part Title

- [First Chapter](relative/path/to/markdown.md)
```

- `Numbered Chapter` - Numbered chapters outline the main content of the book and can be nested, resulting in a nice hierarchy (chapters, sub-chapters, etc.).
```md
# Title of Part

- [First Chapter](relative/path/to/markdown.md)
- [Second Chapter](relative/path/to/markdown2.md)
   - [Sub Chapter](relative/path/to/markdown3.md)

# Title of Another Part

- [Another Chapter](relative/path/to/markdown4.md)
```

Numbered chapters can be denoted with either - or * (do not mix delimiters).

- `Suffix Chapter` - Like prefix chapters, suffix chapters are unnumbered, but they come after numbered chapters.
```md
- [Last Chapter](relative/path/to/markdown.md)

[Title of Suffix Chapter](relative/path/to/markdown2.md)
```

- `Draft chapters` - Draft chapters are chapters without a file and thus content. The purpose of a draft chapter is to signal future chapters still to be written. Or when still laying out the structure of the book to avoid creating the files while you are still changing the structure of the book a lot. Draft chapters will be rendered in the HTML renderer as disabled links in the table of contents, as you can see for the next chapter in the table of contents on the left. Draft chapters are written like normal chapters but without writing the path to the file.
```md
- [Draft Chapter]()
```

- `Separators` - Separators can be added before, in between, and after any other element. They result in an HTML rendered line in the built table of contents. A separator is a line containing exclusively dashes and at least three of them: ---.
```md
# My Part Title

[A Prefix Chapter](relative/path/to/markdown.md)

---

- [First Chapter](relative/path/to/markdown2.md)
```

#### Example
Below is a full example `SUMMARY.md`:

```md
# Summary

[Introduction](README.md)

# User Guide

- [Installation](guide/installation.md)
- [Reading Books](guide/reading.md)
- [Creating a Book](guide/creating.md)

# Reference Guide

- [Command Line Tool](cli/README.md)
    - [init](cli/init.md)
    - [build](cli/build.md)
    - [watch](cli/watch.md)
    - [serve](cli/serve.md)
    - [test](cli/test.md)
    - [clean](cli/clean.md)
    - [completions](cli/completions.md)
- [Format](format/README.md)
    - [SUMMARY.md](format/summary.md)
        - [Draft chapter]()
    - [Configuration](format/configuration/README.md)
        - [General](format/configuration/general.md)
        - [Preprocessors](format/configuration/preprocessors.md)
        - [Renderers](format/configuration/renderers.md)
        - [Environment Variables](format/configuration/environment-variables.md)
    - [Theme](format/theme/README.md)
        - [index.hbs](format/theme/index-hbs.md)
        - [Syntax highlighting](format/theme/syntax-highlighting.md)
        - [Editor](format/theme/editor.md)
    - [MathJax Support](format/mathjax.md)
    - [mdBook-specific features](format/mdbook.md)
    - [Markdown](format/markdown.md)
- [Continuous Integration](continuous-integration.md)
- [For Developers](for_developers/README.md)
    - [Preprocessors](for_developers/preprocessors.md)
    - [Alternative Backends](for_developers/backends.md)

-----------

[Contributors](misc/contributors.md)
```

### Preprocessors
Preprocessors are extensions that can modify the raw Markdown source before it gets sent to the renderer.

The following preprocessors are built-in and included by default:
- links: Expands the `{{ #playground }}`, `{{ #include }}`, and `{{ #rustdoc_include }}` handlebars helpers in a chapter to include the contents of a file.
- index: Convert all chapter files named `README.md` into `index.md`. That is to say, all `README.md` would be rendered to an index file `index.html` in the rendered book.

The built-in preprocessors can be disabled with the `build.use-default-preprocessors` config option.

The community has developed several preprocessors. See the [Third Party Plugins wiki page](https://github.com/rust-lang/mdBook/wiki/Third-party-plugins) for a list of available preprocessors.

#### Custom Preprocessor Configuration
Preprocessors can be added by including a `preprocessor` table in `book.toml` with the name of the preprocessor. For example, if you have a preprocessor called `mdbook-example`, then you can include it with:
```toml
[preprocessor.example]
```

With this table, mdBook will execute the mdbook-example preprocessor.

This table can include additional key-value pairs that are specific to the preprocessor. For example, if our example preprocessor needed some extra configuration options:
```toml
[preprocessor.example]
some-extra-feature = true
```

#### Locking a Preprocessor dependency to a renderer
You can explicitly specify that a preprocessor should run for a renderer by binding the two together.
```toml
[preprocessor.example]
renderers = ["html"]  # example preprocessor only runs with the HTML renderer
```

#### Provide Your Own Command
By default when you add a `[preprocessor.foo]` table to your `book.toml` file, mdbook will try to invoke the `mdbook-foo` executable. If you want to use a different program name or pass in command-line arguments, this behaviour can be overridden by adding a command field.
```toml
[preprocessor.random]
command = "python random.py"
```

#### Require A Certain Order
The order in which preprocessors are run can be controlled with the before and after fields. For example, suppose you want your linenos preprocessor to process lines that may have been `{{#include}}`d; then you want it to run after the built-in links preprocessor, which you can require using either the before or after field:
```toml
[preprocessor.linenos]
after = [ "links" ]
```

or

```
[preprocessor.links]
before = [ "linenos" ]
```

It would also be possible, though redundant, to specify both of the above in the same config file.

Preprocessors having the same priority specified through before and after are sorted by name. Any infinite loops will be detected and produce an error.

## Features
### Hiding code lines
There is a feature in mdBook that lets you hide code lines by prepending them with a specific prefix.

For the Rust language, you can prefix lines with `# ` (# followed by a space) to hide them like you would with Rustdoc. This prefix can be escaped with `##` to prevent the hiding of a line that should begin with the literal string `#` (see Rustdoc’s docs for more details)
```
# fn main() {
    let x = 5;
    let y = 6;

    println!("{}", x + y);
# }
```

Will render as
```
    let x = 5;
    let y = 6;

    println!("{}", x + y);
```

When you tap or hover the mouse over the code block, there will be an eyeball icon which will toggle the visibility of the hidden lines.

By default, this only works for code examples that are annotated with rust. However, you can define custom prefixes for other languages by adding a new line-hiding prefix in your `book.toml` with the language name and prefix character(s):

```toml
[output.html.code.hidelines]
python = "~"
```

The prefix will hide any lines that begin with the given prefix. With the python prefix shown above, this:

```
~hidden()
nothidden():
~    hidden()
    ~hidden()
    nothidden()
```

will render as
```python
nothidden():
    nothidden()
```

This behavior can be overridden locally with a different prefix. This has the same effect as above:

```
\```python,hidelines=!!!
!!!hidden()
nothidden():
!!!    hidden()
    !!!hidden()
    nothidden()
\```
```

### Rust Playground
Rust language code blocks will automatically get a play button which will execute the code and display the output just below the code block. This works by sending the code to the Rust Playground.

If there is no main function, then the code is automatically wrapped inside one.

If you wish to disable the play button for a code block, you can include the `noplayground` option on the code block like this:

```
\```rust,noplayground
let mut name = String::new();
std::io::stdin().read_line(&mut name).expect("failed to read line");
println!("Hello {}!", name);
\```
```

Or, if you wish to disable the play button for all code blocks in your book, you can write the config to the `book.toml` like this.

```toml
[output.html.playground]
runnable = false
```

### Rust code block attributes
Additional attributes can be included in Rust code blocks with comma, space, or tab-separated terms just after the language term. For example:

```
\```rust,ignore
# This example won't be tested.
panic!("oops!");
\```
```

These are particularly important when using mdbook test to test Rust examples. These use the same attributes as rustdoc attributes, with a few additions:

- `editable` — Enables the editor.
- `noplayground` — Removes the play button, but will still be tested.
- `mdbook-runnable` — Forces the play button to be displayed. This is intended to be combined with the ignore attribute for examples that should not be tested, but you want to allow the reader to run.
- `ignore` — Will not be tested and no play button is shown, but it is still highlighted as Rust syntax.
- `should_panic` — When executed, it should produce a panic.
- `no_run` — The code is compiled when tested, but it is not run. The play button is also not shown.
- `compile_fail` — The code should fail to compile.
- `edition2015`, `edition2018`, `edition2021` — Forces the use of a specific Rust edition. See rust.edition to set this globally.

### Including files
With the following syntax, you can include files into your book:
```
{{#include file.rs}}
```

The path to the file has to be relative from the current source file.

mdBook will interpret included files as Markdown. Since the include command is usually used for inserting code snippets and examples, you will often wrap the command with ``` to display the file contents without interpreting them.

```
\```
{{#include file.rs}}
\```
```

### Including portions of a file
Often you only need a specific part of the file, e.g. relevant lines for an example. We support four different modes of partial includes:

```
{{#include file.rs:2}}
{{#include file.rs::10}}
{{#include file.rs:2:}}
{{#include file.rs:2:10}}
```

The first command only includes the second line from file `file.rs`. The second command includes all lines up to line 10, i.e. the lines from 11 till the end of the file are omitted. The third command includes all lines from line 2, i.e. the first line is omitted. The last command includes the excerpt of `file.rs` consisting of lines 2 to 10.

To avoid breaking your book when modifying included files, you can also include a specific section using anchors instead of line numbers. An anchor is a pair of matching lines. The line beginning an anchor must match the regex `ANCHOR:\s*[\w_-]+` and similarly the ending line must match the regex `ANCHOR_END:\s*[\w_-]+`. This allows you to put anchors in any kind of commented line.

Consider the following file to include:

```
/* ANCHOR: all */

// ANCHOR: component
struct Paddle {
    hello: f32,
}
// ANCHOR_END: component

////////// ANCHOR: system
impl System for MySystem { ... }
////////// ANCHOR_END: system

/* ANCHOR_END: all */
```

Then in the book, all you have to do is:

```
Here is a component:
\```rust,no_run,noplayground
{{#include file.rs:component}}
\```

Here is a system:
\```rust,no_run,noplayground
{{#include file.rs:system}}
\```

This is the full file.
\```rust,no_run,noplayground
{{#include file.rs:all}}
\```
```

Lines containing anchor patterns inside the included anchor are ignored.

### Including a file but initially hiding all except specified lines
The `rustdoc_include` helper is for including code from external Rust files that contain complete examples, but only initially showing particular lines specified with line numbers or anchors in the same way as with include.

The lines not in the line number range or between the anchors will still be included, but they will be prefaced with `#`. This way, a reader can expand the snippet to see the complete example, and Rustdoc will use the complete example when you run mdbook test.

For example, consider a file named `file.rs` that contains this Rust program:

```rust
fn main() {
    let x = add_one(2);
    assert_eq!(x, 3);
}

fn add_one(num: i32) -> i32 {
    num + 1
}
```

We can include a snippet that initially shows only line 2 by using this syntax:

```
To call the `add_one` function, we pass it an `i32` and bind the returned value to `x`:

\```rust
{{#rustdoc_include file.rs:2}}
\```
```

This would have the same effect as if we had manually inserted the code and hidden all but line 2 using `#`:

### Inserting runnable Rust files
With the following syntax, you can insert runnable Rust files into your book:
```
{{#playground file.rs}}
```

The path to the Rust file has to be relative from the current source file.

When play is clicked, the code snippet will be sent to the Rust Playground to be compiled and run. The result is sent back and displayed directly underneath the code.

### Controlling page `<title>`
A chapter can set a `<title>` that is different from its entry in the table of contents (sidebar) by including a `{{#title ...}}` near the top of the page.

```
{{#title My Title}}
```

### HTML classes provided by mdBook
#### class="left" and "right"
These classes are provided by default, for inline HTML to float images.

```html
<img class="right" src="images/rust-logo-blk.svg" alt="The Rust logo">
```

#### class="hidden"
HTML tags with class hidden will not be shown.

```html
<div class="hidden">This will not be seen.</div>
```

#### class="warning"
To make a warning or similar note stand out, wrap it in a warning div.

```html
<div class="warning">
```

### Math Support
mdBook has optional support for math equations through MathJax.

To enable MathJax, you need to add the `mathjax-support` key to your `book.toml` under the `output.html` section.

```toml
[output.html]
mathjax-support = true
```

> **Note**: The usual delimiters MathJax uses are not yet supported. You can’t currently use `$$ ... $$` as delimiters and the `\[ ... \]` delimiters need an extra backslash to work.

#### Inline equations
Inline equations are delimited by `\\(` and `\\)`. So for example, to render the following inline equation you would write the following:

```
\\( \int x dx = \frac{x^2}{2} + C \\)
```

#### Block equations
Block equations are delimited by `\\[` and `\\]`. To render the following equation

```
\\[ \mu = \frac{1}{N} \sum_{i=0} x_i \\]
```
