# mdBook

mdBook is a command line tool and Rust crate to create books using Markdown files. It's very similar to Gitbook but written in Rust.

What you are reading serves as an example of the output of mdBook and at the same time as a high-level documentation.

mdBook is free and open source, you can find the source code on Github. Issues and feature requests can be posted on the Github Issue tracker.

## API docs

Alongside this book you can also read the API docs generated by Rustdoc if you would like to use mdBook as a crate or write a new renderer and need a more low-level overview.

mdBook, all the source code, is released under the Mozilla Public License v2.0

# Command Line Tool

mdBook can be used either as a command line tool or a Rust crate. Let's focus on the command line tool capabilities first.

## Install

### Pre-requisite

mdBook is written in Rust and therefore needs to be compiled with Cargo, because we don't yet offer ready-to-go binaries. If you haven't already installed Rust, please go ahead and install it now.

### Install Crates.io version

Installing mdBook is relatively easy if you already have Rust and Cargo installed. You just have to type this snippet in your terminal:

cargo install mdbook


This will fetch the source code from Crates.io and compile it. You will have to add Cargo's bin directory to your PATH.

Run mdbook help in your terminal to verify if it works. Congratulations, you have installed mdBook!

### Install Git version

The git version contains all the latest bug-fixes and features, that will be released in the next version on Crates.io, if you can't wait until the next release. You can build the git version yourself. Open your terminal and navigate to the directory of you choice. We need to clone the git repository and then build it with Cargo.

git clone --depth=1 https://github.com/azerupi/mdBook.git
cd mdBook
cargo build --release


The executable mdbook will be in the ./target/release folder, this should be added to the path.

# The init command

There is some minimal boilerplate that is the same for every new book. It's for this purpose that mdBook includes an init command.

The init command is used like this:

mdbook init


When using the init command for the first time, a couple of files will be set up for you:

book-test/
├── book
└── src
├── chapter_1.md
└── SUMMARY.md

• The src directory is were you write your book in markdown. It contains all the source files, configuration files, etc.

• The book directory is where your book is rendered. All the output is ready to be uploaded to a server to be seen by your audience.

• The SUMMARY.md file is the most important file, it's the skeleton of your book and is discussed in more detail in another chapter.

#### Tip & Trick: Hidden Feature

When a SUMMARY.md file already exists, the init command will first parse it and generate the missing files according to the paths used in the SUMMARY.md. This allows you to think and create the whole structure of your book and then let mdBook generate it for you.

#### Specify a directory

When using the init command, you can also specify a directory, instead of using the current working directory, by appending a path to the command:

mdbook init path/to/book


## --theme

When you use the --theme argument, the default theme will be copied into a directory called theme in your source directory so that you can modify it.

The theme is selectively overwritten, this means that if you don't want to overwrite a specific file, just delete it and the default file will be used.

# The build command

Crates: rayon

The build command is used to render your book:

mdbook build


It will try to parse your SUMMARY.md file to understand the structure of your book and fetch the corresponding files.

The rendered output will maintain the same directory structure as the source for convenience. Large books will therefore remain structured when rendered.

#### Specify a directory

Like init, the build command can take a directory as argument to use instead of the current working directory.

mdbook build path/to/book


#### --open

When you use the --open (-o) option, mdbook will open the rendered book in your default web browser after building it.

#### --dest-dir

The --dest-dir (-d) option allows you to change the output directory for your book.

note: make sure to run the build command in the root directory and not in the source directory

# The watch command

The watch command is useful when you want your book to be rendered on every file change. You could repeatedly issue mdbook build every time a file is changed. But using mdbook watch once will watch your files and will trigger a build automatically whenever you modify a file.

#### Specify a directory

Like init and build, watch can take a directory as argument to use instead of the current working directory.

mdbook watch path/to/book


#### --open

When you use the --open (-o) option, mdbook will open the rendered book in your default web browser.

#### --dest-dir

The --dest-dir (-d) option allows you to change the output directory for your book.

note: the watch command has not gotten a lot of testing yet, there could be some rough edges. If you discover a problem, please report it on Github

# The serve command

The serve command is useful when you want to preview your book. It also does hot reloading of the webpage whenever a file changes. It achieves this by serving the books content over localhost:3000 (unless otherwise configured, see below) and runs a websocket server on localhost:3001 which triggers the reloads. This preferred by many for writing books with mdbook because it allows for you to see the result of your work instantly after every file change.

#### Specify a directory

Like watch, serve can take a directory as argument to use instead of the current working directory.

mdbook serve path/to/book


#### Server options

serve has four options: the http port, the websocket port, the interface to serve on, and the public address of the server so that the browser may reach the websocket server.

For example: suppose you had an nginx server for SSL termination which has a public address of 192.168.1.100 on port 80 and proxied that to 127.0.0.1 on port 8000. To run use the nginx proxy do:

mdbook server path/to/book -p 8000 -i 127.0.0.1 -a 192.168.1.100


If you were to want live reloading for this you would need to proxy the websocket calls through nginx as well from 192.168.1.100:<WS_PORT> to 127.0.0.1:<WS_PORT>. The -w flag allows for the websocket port to be configured.

#### --open

When you use the --open (-o) option, mdbook will open the book in your your default web browser after starting the server.

#### --dest-dir

The --dest-dir (-d) option allows you to change the output directory for your book.

note: the serve command has not gotten a lot of testing yet, there could be some rough edges. If you discover a problem, please report it on Github

# The test command

When writing a book, you sometimes need to automate some tests. For example, The Rust Programming Book uses a lot of code examples that could get outdated. Therefore it is very important for them to be able to automatically test these code examples.

mdBook supports a test command that will run all available tests in mdBook. At the moment, only one test is available: "Test Rust code examples using Rustdoc", but I hope this will be expanded in the future to include more tests like:

• checking for unused files
• ...

In the future I would like the user to be able to enable / disable test from the book.toml configuration file and support custom tests.

How to use it:

\$ mdbook test


# Format

In this section you will learn how to:

• Format your SUMMARY.md file
• Configure your book using book.toml

# SUMMARY.md

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.

Even though SUMMARY.md is a markdown file, the formatting is very strict to allow for easy parsing. Let's see how you should format your SUMMARY.md file.

#### Allowed elements

1. Title It's common practice to begin with a title, generally # Summary. But it is not mandatory, the parser just ignores it. So you can too if you feel like it.

2. Prefix Chapter Before the main numbered chapters you can add a couple of elements that will not be numbered. This is useful for forewords, introductions, etc. There are however some constraints. You can not nest prefix chapters, they should all be on the root level. And you can not add prefix chapters once you have added numbered chapters.

[Title of prefix element](relative/path/to/markdown.md)

3. Numbered Chapter Numbered chapters are the main content of the book, they will be numbered and can be nested, resulting in a nice hierarchy (chapters, sub-chapters, etc.)

- [Title of the Chapter](relative/path/to/markdown.md)


You can either use - or * to indicate a numbered chapter.

4. Suffix Chapter After the numbered chapters you can add a couple of non-numbered chapters. They are the same as prefix chapters but come after the numbered chapters instead of before.

All other elements are unsupported and will be ignored at best or result in an error.

# Configuration

You can configure the parameters for your book in the book.toml file.

Note:
JSON configuration files were previously supported but have been deprecated in favor of the TOML configuration file. If you are still using JSON we strongly encourage you to migrate to the TOML configuration because JSON support will be removed in the future.

Here is an example of what a book.toml file might look like:

title = "Example book"
author = "John Doe"
description = "The example book covers examples."

[output.html]
destination = "my-example-book"


## Supported configuration options

It is important to note that any relative path specified in the in the configuration will always be taken relative from the root of the book where the configuration file is located.

• title: The title of the book
• author: The author of the book
• description: A description for the book, which is added as meta information in the html <head> of each page

book.toml

title = "Example book"
author = "John Doe"
description = "The example book covers examples."


Some books may have multiple authors, there is an alternative key called authors plural that lets you specify an array of authors.

book.toml

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


### Source directory

By default, the source directory is found in the directory named src directly under the root folder. But this is configurable with the source key in the configuration file.

book.toml

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

source = "my-src"  # the source files will be found in root/my-src instead of root/src


### HTML renderer options

The HTML renderer has a couple of options aswell. All the options for the renderer need to be specified under the TOML table [output.html]. The following configuration options are available:

• destination: By default, the HTML book will be rendered in the root/book directory, but this option lets you specify another destination fodler.
• theme: mdBook comes with a default theme and all the resource files needed for it. But if this option is set, mdBook will selectively overwrite the theme files with the ones found in the specified folder.
• curly-quotes: Convert straight quotes to curly quotes, except for those that occur in code blocks and code spans. Defaults to false.
• google-analytics: If you use Google Analytics, this option lets you enable it by simply specifying your ID in the configuration file.
• additional-css: If you need to slightly change the appearance of your book without overwriting the whole style, you can specify a set of stylesheets that will be loaded after the default ones where you can surgically change the style.
• additional-js: If you need to add some behaviour to your book without removing the current behaviour, you can specify a set of javascript files that will be loaded alongside the default one.

book.toml

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

[output.html]
destination = "my-book" # the output files will be generated in root/my-book instead of root/book
theme = "my-theme"
curly-quotes = true


# Theme

The default renderer uses a handlebars template to render your markdown files and comes with a default theme included in the mdBook binary.

The theme is totally customizable, you can selectively replace every file from the theme by your own by adding a theme directory next to src folder in your project root. Create a new file with the name of the file you want to override and now that file will be used instead of the default file.

Here are the files you can override:

• index.hbs is the handlebars template.
• book.css is the style used in the output. If you want to change the design of your book, this is probably the file you want to modify. Sometimes in conjunction with index.hbs when you want to radically change the layout.
• book.js is mostly used to add client side functionality, like hiding / un-hiding the sidebar, changing the theme, ...
• highlight.js is the JavaScript that is used to highlight code snippets, you should not need to modify this.
• highlight.css is the theme used for the code highlighting
• favicon.png the favicon that will be used

Generally, when you want to tweak the theme, you don't need to override all the files. If you only need changes in the stylesheet, there is no point in overriding all the other files. Because custom files take precedence over built-in ones, they will not get updated with new fixes / features.

Note: When you override a file, it is possible that you break some functionality. Therefore I recommend to use the file from the default theme as template and only add / modify what you need. You can copy the default theme into your source directory automatically by using mdbook init --theme just remove the files you don't want to override.

# index.hbs

index.hbs is the handlebars template that is used to render the book. The markdown files are processed to html and then injected in that template.

If you want to change the layout or style of your book, chances are that you will have to modify this template a little bit. Here is what you need to know.

## Data

A lot of data is exposed to the handlebars template with the "context". In the handlebars template you can access this information by using

{{name_of_property}}


Here is a list of the properties that are exposed:

• language Language of the book in the form en. To use in <html lang="{{ language }}"> for example. At the moment it is hardcoded.

• title Title of the book, as specified in book.toml

• chapter_title Title of the current chapter, as listed in SUMMARY.md

• path Relative path to the original markdown file from the source directory

• content This is the rendered markdown.

• path_to_root This is a path containing exclusively ../'s that points to the root of the book from the current file. Since the original directory structure is maintained, it is useful to prepend relative links with this path_to_root.

• chapters Is an array of dictionaries of the form

{"section": "1.2.1", "name": "name of this chapter", "path": "dir/markdown.md"}


containing all the chapters of the book. It is used for example to construct the table of contents (sidebar).

## Handlebars Helpers

In addition to the properties you can access, there are some handlebars helpers at your disposal.

1. ### toc

The toc helper is used like this

{{#toc}}{{/toc}}


and outputs something that looks like this, depending on the structure of your book

<ul class="chapter">
<li>
<ul class="section">
</ul>
</li>
</ul>


If you would like to make a toc with another structure, you have access to the chapters property containing all the data. The only limitation at the moment is that you would have to do it with JavaScript instead of with a handlebars helper.

<script>
var chapters = {{chapters}};
// Processing here
</script>

2. ### previous / next

The previous and next helpers expose a link and name property to the previous and next chapters.

They are used like this

{{#previous}}
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}


The inner html will only be rendered if the previous / next chapter exists. Of course the inner html can be changed to your liking.

If you would like me to expose other properties or helpers, please create a new issue and I will consider it.

# Syntax Highlighting

For syntax highlighting I use Highlight.js with a custom theme.

Automatic language detection has been turned off, so you will probably want to specify the programming language you use like this

rust
fn main() {
// Some code
}


## Custom theme

Like the rest of the theme, the files used for syntax highlighting can be overridden with your own.

• highlight.js normally you shouldn't have to overwrite this file, unless you want to use a more recent version.
• highlight.css theme used by highlight.js for syntax highlighting.

If you want to use another theme for highlight.js download it from their website, or make it yourself, rename it to highlight.css and put it in src/theme (or the equivalent if you changed your source folder)

## Hiding code lines

There is a feature in mdBook that let's you hide code lines by prepending them with a #.

# fn main() {
let x = 5;
let y = 6;

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


Will render as

# fn main() {
let x = 5;
let y = 7;

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


At the moment, this only works for code examples that are annotated with rust. Because it would collide with semantics of some programming languages. In the future, we want to make this configurable through the book.toml so that everyone can benefit from it.

## Improve default theme

If you think the default theme doesn't look quite right for a specific language, or could be improved. Feel free to submit a new issue explaining what you have in mind and I will take a look at it.

You could also create a pull-request with the proposed improvements.

Overall the theme should be light and sober, without to many flashy colors.

# MathJax 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.

[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. Hopefully this limitation will be lifted soon.

### Inline equations

Inline equations are delimited by \$$ and \$$. So for example, to render the following inline equation $$\int x dx = \frac{x^2}{2} + C$$ 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$

you would write:

\$\mu = \frac{1}{N} \sum_{i=0} x_i \$


# Rust code specific features

## Hiding code lines

There is a feature in mdBook that let's you hide code lines by prepending them with a #.

# fn main() {
let x = 5;
let y = 6;

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


Will render as

# fn main() {
let x = 5;
let y = 7;

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


## Inserting runnable Rust files

With the following syntax, you can insert runnable Rust files into your book:

{{#playpen 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 send to the Rust Playpen to be compiled and run. The result is send back and displayed directly underneath the code.

Here is what a rendered code snippet looks like:

fn main() {
println!("Hello World!");
#
#    // You can even hide lines! :D
#   println!("I am hidden! Expand the code snippet to see me");
}



# Rust Library

mdBook is not only a command line tool, it can be used as a crate. You can extend it, integrate it in current projects. Here is a short example:

extern crate mdbook;

use mdbook::MDBook;
use std::path::Path;

# #[allow(unused_variables)]
fn main() {
let mut book =  MDBook::new("my-book")        // Path to root
.with_source("src")       // Path from root to source directory
.with_destination("book") // Path from root to output directory
.read_config()            // Parse book.toml or book.json configuration file
.expect("I don't handle configuration file error, but you should!");

book.build().unwrap();                        // Render the book
}


Check here for the API docs generated by rustdoc.

# Contributors

Here is a list of the contributors who have helped improving mdBook. Big shout-out to them!

If you have contributed to mdBook and I forgot to add you, don't hesitate to add yourself to the list. If you are in the list, feel free to add your real name & contact information if you wish.