### Example book.toml Configuration Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/configuration/general.md A comprehensive example of a book.toml file showcasing various configuration sections. ```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 ``` -------------------------------- ### Install Custom Backend Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/backends.md Install the custom backend executable locally using Cargo. ```shell cargo install --path . ``` -------------------------------- ### Serve a book locally Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/serve.md Starts a local HTTP server to preview the book. It defaults to `localhost:3000` and watches for changes. ```bash mdbook serve ``` -------------------------------- ### Playground Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/test/passing_tests/src/passing1.md Links to an interactive Rust playground example using 'test1.rs'. ```rust {{#playground test1.rs}} ``` -------------------------------- ### Makefile Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md A basic Makefile demonstrating build targets, variables, and a clean command for removing build artifacts. ```makefile # Makefile BUILDDIR = _build EXTRAS ?= $(BUILDDIR)/extras .PHONY: main clean main: @echo "Building main facility..." build_main $(BUILDDIR) clean: rm -rf $(BUILDDIR)/* ``` -------------------------------- ### Install and build with custom backend Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/backends.md This shell command demonstrates how to install a custom mdbook backend using Cargo and then build a book with it. This is useful for testing your backend's integration. ```shell cargo install --path . --force mdbook build /path/to/book ``` -------------------------------- ### Install rustfmt Component Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Install the rustfmt component using rustup. This is required for code formatting. ```bash rustup component add rustfmt ``` -------------------------------- ### mdBook SUMMARY.md Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/summary.md An example of a complete SUMMARY.md file, demonstrating the integration of various structural elements. ```markdown {{#include ../SUMMARY.md}} ``` -------------------------------- ### Basic Rust Hello World Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/reading.md A simple Rust program that prints 'Hello, World!' to the console. This is a common starting point for Rust examples. ```rust println!("Hello, World!"); ``` -------------------------------- ### Install nvm, Node.js, and sscli Source: https://github.com/rust-lang/mdbook/wiki/Apache Installs Node Version Manager, Node.js, and the static-sitemap-cli for generating sitemaps. Ensure to restart your terminal after nvm installation. ```sh # As of this writing: # installs nvm (Node Version Manager) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash # download and install Node.js (you may need to restart the terminal) nvm install 22 # verifies the right Node.js version is in the environment node -v # should print `v22.11.0` # verifies the right npm version is in the environment npm -v # should print `10.9.0` # install sscli npm i -g static-sitemap-cli ``` -------------------------------- ### Shell: Command Examples Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Shows basic shell commands for checking environment variables, switching branches, and pushing code, along with multi-line input. ```shell $ echo $EDITOR vim $ git checkout main Switched to branch 'main' Your branch is up-to-date with 'origin/main'. $ git push Everything up-to-date $ echo 'All > done!' All done! ``` -------------------------------- ### Less CSS Preprocessor Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md An example of Less syntax, showcasing imports, variables, media queries, nested rules, and mixins. ```less @import 'fruits'; @rhythm: 1.5em; @media screen and (min-resolution: 2dppx) { body { font-size: 125%; } } section > .foo + #bar:hover [href*='less'] { margin: @rhythm 0 0 @rhythm; padding: calc(5% + 20px); background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat; background-image: linear-gradient(-135deg, wheat, fuchsia) !important ; background-blend-mode: multiply; } @font-face { font-family: /* ? */ 'Omega'; src: url('../fonts/omega-webfont.woff?v=2.0.2'); } .icon-baz::before { display: inline-block; font-family: 'Omega', Alpha, sans-serif; content: '\f085'; color: rgba(98, 76 /* or 54 */, 231, 0.75); } ``` -------------------------------- ### Install mdBook from source using Cargo Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/continuous-integration.md Install mdBook using `cargo install` with recommended options for CI. `--no-default-features` speeds up the build, `--features search` enables search functionality, `--vers "^0.4"` pins to a specific minor version, and `--locked` ensures dependency consistency. ```sh cargo install mdbook --no-default-features --features search --vers "^0.4" --locked ``` -------------------------------- ### Install and Build mdBook, Deploy to GitHub Pages Source: https://github.com/rust-lang/mdbook/wiki/Automated-Deployment:-GitHub-Pages-(Deploy-from-branch) This script installs mdBook, builds the book, and deploys it to the 'gh-pages' branch. It overwrites the existing 'gh-pages' branch to maintain a clean history. Ensure you have git and curl installed. ```shell # Installs mdbook mkdir mdbook # Consider using a service like renovatebot if you want to automatically update the version here. curl -Lf https://github.com/rust-lang/mdBook/releases/download/v0.4.37/mdbook-v0.4.37-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=./mdbook echo `pwd`/mdbook >> $GITHUB_PATH # Build the book mdbook build # If the gh-pages branch already exists, this will overwrite it # so that the history is not kept, which can be very expensive. git worktree add --orphan -B gh-pages gh-pages cp -r book/ gh-pages git config user.name "Deploy from CI" git config user.email "" cd gh-pages git add -A git commit -m 'deploy new book' git push origin +gh-pages cd .. ``` -------------------------------- ### Build highlight.js with specific languages Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Run this command to build highlight.js with a specified list of languages. Ensure you have Node.js installed. ```bash npm install node tools/build.js :common apache armasm coffeescript d handlebars haskell http julia nginx nim nix properties r scala x86asm yaml ``` -------------------------------- ### Markdown Definition List Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/markdown.md Create definition lists for glossaries or term explanations. Each definition starts with a colon after optional spaces. ```markdown term A : This is a definition of term A. Text can span multiple lines. term B : This is a definition of term B. : This has more than one definition. ``` -------------------------------- ### GitHub Actions Workflow for Building and Deploying to Vercel Source: https://github.com/rust-lang/mdbook/wiki/Automated-Deployment:-GitHub-Actions This workflow builds an mdbook and deploys it to Vercel. It requires Vercel CLI installation and authentication using VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_ORG_ID, which should be configured as encrypted secrets in GitHub. The workflow checks out the repository, installs mdbook, builds the book, sets up Node.js, installs Vercel CLI, pulls Vercel environment information, and then deploys the book. ```yaml name: Build Book & Deploy to Vercel env: VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} on: [push] jobs: buildAndDeploy: runs-on: ubuntu-latest permissions: contents: write # To push a branch pull-requests: write # To create a PR from that branch steps: - name: Checkout Repository uses: actions/checkout@v4 - name: Install mdBook uses: extractions/setup-crate@v1 with: owner: rust-lang name: mdBook - name: Generate static content for the book run: mdbook build - name: Setup Node.js (required to install Vercel CLI) uses: actions/setup-node@v3 - name: Install Vercel CLI run: npm install --global vercel - name: Pull Vercel environment information run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }} - name: Deploy to Vercel run: vercel book --prod --token=${{ secrets.VERCEL_TOKEN }} ``` -------------------------------- ### Nginx Configuration Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md A sample Nginx configuration file demonstrating worker processes, logging, HTTP server blocks, location directives, and proxy settings. ```nginx user www www; worker_processes 2; pid /var/run/nginx.pid; error_log /var/log/nginx.error_log debug | info | notice | warn | error | crit; events { connections 2000; use kqueue | rtsig | epoll | /dev/poll | select | poll; } http { log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; send_timeout 3m; client_header_buffer_size 1k; gzip on; gzip_min_length 1100; #lingering_time 30; server { server_name one.example.com www.one.example.com; access_log /var/log/nginx.access_log main; rewrite (.*) /index.php?page=$1 break; location / { proxy_pass http://127.0.0.1/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; charset koi8-r; } location /api/ { fastcgi_pass 127.0.0.1:9000; } location ~* \.(jpg|jpeg|gif)$ { root /spool/www; } } } ``` -------------------------------- ### Create New Binary and Add Dependency Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/backends.md Initialize a new Rust binary project and add `mdbook-renderer` as a dependency to start building a custom backend. ```shell cargo new --bin mdbook-wordcount cd mdbook-wordcount cargo add mdbook-renderer ``` -------------------------------- ### Install Clippy Component Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Install the clippy linter component using rustup. This helps in finding code issues. ```bash rustup component add clippy ``` -------------------------------- ### Example No-Op Preprocessor Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/preprocessors.md A basic implementation of a no-operation preprocessor that can be used as a starting point. It demonstrates the basic structure required for an MDBook preprocessor. ```rust use mdbook_preprocessor::*; use std::io; fn main() { let Args { renderer, .. } = Args::parse(); if renderer == "html" { // This preprocessor supports the html renderer return; } let book: Book = serde_json::from_reader(io::stdin()).expect("Failed to read book from stdin"); // No changes are made to the book serde_json::to_writer(io::stdout(), &book).expect("Failed to write book to stdout"); } ``` -------------------------------- ### Example chapter content Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/creating.md Each chapter is a Markdown file, typically starting with a level 1 heading for the chapter title. Content can be added below the heading. ```md # My First Chapter Fill out your content here. ``` -------------------------------- ### Install Shell Completions Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/completions.md Install auto-completion scripts for bash and oh-my-zsh. The output is redirected to a file in the appropriate completion directory. For oh-my-zsh, ensure compinit is loaded. ```bash # bash mdbook completions bash > ~/.local/share/bash-completion/completions/mdbook # oh-my-zsh mdbook completions zsh > ~/.oh-my-zsh/completions/_mdbook autoload -U compinit && compinit ``` -------------------------------- ### Install ESLint and dependencies Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Installs npm packages, including ESLint, required for checking JavaScript files. This should be run after cloning the repository. ```sh npm install ``` -------------------------------- ### Apache Configuration Rules Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Provides examples of Apache rewrite rules for WordPress, including module loading, conditional rewrites, and location-specific configurations. Also includes an example of an Apache log entry. ```apache # rewrite`s rules for wordpress pretty url LoadModule rewrite_module modules/mod_rewrite.so RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [NC,L] ExpiresActive On ExpiresByType application/x-javascript "access plus 1 days" Order Deny,Allow Allow from All RewriteMap map txt:map.txt RewriteMap lower int:tolower RewriteCond %{REQUEST_URI} ^/([^/.]+)\.html$ [NC] RewriteCond ${map:${lower:%1}|NOT_FOUND} !NOT_FOUND RewriteRule .? /index.php?q=${map:${lower:%1}} [NC,L] 20.164.151.111 - - [20/Aug/2015:22:20:18 -0400] "GET /mywebpage/index.php HTTP/1.1" 403 772 "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1" ``` -------------------------------- ### Rust MDBook::load_with_config_and_summary Example Source: https://context7.com/rust-lang/mdbook/llms.txt Loads an mdBook instance programmatically using a custom Summary object and a default Config, bypassing the need to read SUMMARY.md from disk. It then builds the book. ```rust use mdbook_driver::MDBook; use mdbook_driver::config::Config; use mdbook_summary::{parse_summary, Summary}; fn main() -> anyhow::Result<()> { let summary_src = "# Summary\n\n- [Chapter 1](ch1.md)\n- [Chapter 2](ch2.md)\n"; let summary: Summary = parse_summary(summary_src)?; let cfg = Config::default(); let book = MDBook::load_with_config_and_summary( "/path/to/my-book", cfg, summary, )?; book.build()?; Ok(()) } ``` -------------------------------- ### Serve mdBook project with live-reload Source: https://context7.com/rust-lang/mdbook/llms.txt The `mdbook serve` command builds the book, starts a local HTTP server, and enables live-reloading for changes. Use `--open` to automatically open the browser. ```sh mdbook serve --open # Serve on a custom address and port mdbook serve --hostname 0.0.0.0 --port 8080 # The server will print: # Serving on: http://localhost:3000 ``` -------------------------------- ### Smart Punctuation Examples Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/smart_punctuation/src/smart_punctuation.md Demonstrates the automatic conversion of punctuation characters to their smart equivalents. ```markdown "quoted" ``` -------------------------------- ### INI Configuration File Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Shows the structure of an INI file with sections, key-value pairs, multi-line strings, and different data types like integers and booleans. ```ini ; boilerplate [package] name = "some_name" authors = ["Author"] description = "This is \ a description" [[lib]] name = ${NAME} default = True auto = no counter = 1_000 ``` -------------------------------- ### Install mdBook using Cargo Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/installation.md Installs the latest stable version of mdBook from crates.io. Ensure Cargo's binary directory is in your PATH. ```sh cargo install mdbook ``` -------------------------------- ### HTTP POST Request Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md An example of an HTTP POST request with JSON payload, including headers like Host, Content-Type, and Content-Length. ```http POST /task?id=1 HTTP/1.1 Host: example.org Content-Type: application/json; charset=utf-8 Content-Length: 137 { "status": "ok", "extended": true, "results": [ {"value": 0, "type": "int64"}, {"value": 1.0e+3, "type": "decimal"} ] } ``` -------------------------------- ### Diff Example with File Changes Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Shows a diff output format, illustrating changes between two versions of a file, including added and removed lines, and metadata. ```diff Index: languages/ini.js =================================================================== --- languages/ini.js (revision 199) +++ languages/ini.js (revision 200) @@ -1,8 +1,7 @@ hljs.LANGUAGES.ini = { case_insensitive: true, - defaultMode: - { + defaultMode: { contains: ['comment', 'title', 'setting'], illegal: '[^\\s]' }, *** /path/to/original timestamp --- /path/to/new timestamp *************** *** 1,3 **** --- 1,9 ---- + This is an important + notice! It should + therefore be located at + the beginning of this + document! ! compress the size of the ! changes. It is important to spell ``` -------------------------------- ### Mark Backend as Optional Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/configuration/renderers.md Prevent an error if an optional backend is not installed by setting `optional = true` in its `[output.]` table. This changes the error to a warning. ```toml [output.wordcount] optional = true ``` -------------------------------- ### Example of `rustdoc_include` with Hidden Lines Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/mdbook.md Demonstrates the visual effect of `rustdoc_include` where only specified lines are initially visible, with other lines hidden using `#`. ```rust # fn main() { let x = add_one(2); # assert_eq!(x, 3); # } # # fn add_one(num: i32) -> i32 { # num + 1 # } ``` -------------------------------- ### TypeScript Class and Module Syntax Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Demonstrates class definition, constructor, static properties, interface declaration, and module export in TypeScript. Includes an example of using forEach with an arrow function. ```typescript class MyClass { public static myValue: string; constructor(init: string) { this.myValue = init; } } import fs = require("fs"); module MyModule { export interface MyInterface extends Other { myProperty: any; } } declare magicNumber number; myArray.forEach(() => { }); // fat arrow syntax ``` -------------------------------- ### Run GUI tests Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Executes the GUI test suite, which requires Node.js and npm. The first run may prompt to install the 'browser-ui-test' package. ```sh cargo test --test gui ``` -------------------------------- ### Properties: Key-Value Pairs Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Demonstrates the syntax for .properties files, including comments and escaped characters. ```properties # .properties ! Exclamation mark = comments, too key1 = value1 key2 : value2 key3 value3 key\ spaces multiline\ value4 empty_key ! Key can contain escaped chars \:\= = value5 ``` -------------------------------- ### Run mdBook tests in CI Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/continuous-integration.md Execute `mdbook test` to validate Rust code examples within your book. This requires Rust to be installed in the CI environment. ```sh mdbook test ``` -------------------------------- ### Initialize a new mdBook project Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/creating.md Use the `mdbook init` command followed by the desired directory name to create a new, empty book structure. The command will prompt for additional information. ```sh mdbook init my-first-book ``` -------------------------------- ### Run Rust Tests with GitHub Actions Source: https://github.com/rust-lang/mdbook/wiki/Automated-Deployment:-GitHub-Actions This workflow runs `mdbook test` on every push and pull request to ensure Rust examples are tested. It installs the stable Rust toolchain and the latest mdbook release. ```yml name: CI on: [push, pull_request] jobs: test: name: Test runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Install Rust run: | rustup set profile minimal rustup toolchain install stable rustup default stable - name: Install latest mdbook run: | tag=$(curl 'https://api.github.com/repos/rust-lang/mdbook/releases/latest' | jq -r '.tag_name') url="https://github.com/rust-lang/mdbook/releases/download/${tag}/mdbook-${tag}-x86_64-unknown-linux-gnu.tar.gz" mkdir bin curl -sSL $url | tar -xz --directory=bin echo "$(pwd)/bin" >> $GITHUB_PATH - name: Run tests run: mdbook test ``` -------------------------------- ### Rust parse_summary Example Source: https://context7.com/rust-lang/mdbook/llms.txt Demonstrates parsing a SUMMARY.md string into a structured Summary object using the mdbook_summary crate. It shows how to access prefix, numbered, and suffix chapters. ```rust use mdbook_summary::{parse_summary, SummaryItem, Link}; fn main() -> anyhow::Result<()> { let src = r#"# Summary [Preface](preface.md) # Part One - [Introduction](intro.md) - [Sub-topic](intro/sub.md) - [Advanced](advanced.md) [Appendix](appendix.md) "#; let summary = parse_summary(src)?; println!("Prefix chapters: {}", summary.prefix_chapters.len()); // 1 println!("Numbered parts+chapters: {}", summary.numbered_chapters.len()); println!("Suffix chapters: {}", summary.suffix_chapters.len()); // 1 for item in &summary.numbered_chapters { if let SummaryItem::Link(link) = item { println!("Chapter: {} -> {:?}", link.name, link.location); } } Ok(()) } ``` -------------------------------- ### Python Preprocessor Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/preprocessors.md This Python script demonstrates a basic mdBook preprocessor. It checks for a 'supports' argument and modifies the content of the first chapter to '# Hello' before printing the modified book structure to stdout. Ensure the script is executable and configured in `book.toml`. ```python import json import sys if __name__ == '__main__': if len(sys.argv) > 1: # we check if we received any argument if sys.argv[1] == "supports": # then we are good to return an exit status code of 0, since the other argument will just be the renderer's name sys.exit(0) # load both the context and the book representations from stdin context, book = json.load(sys.stdin) # and now, we can just modify the content of the first chapter book['items'][0]['Chapter']['content'] = '# Hello' # we are done with the book's modification, we can just print it to stdout, print(json.dumps(book)) ``` -------------------------------- ### Build the book Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/build.md Use this command to render your book. It parses SUMMARY.md and creates the output. ```bash mdbook build ``` -------------------------------- ### Define Book Structure with SUMMARY.md Source: https://context7.com/rust-lang/mdbook/llms.txt Example of a SUMMARY.md file defining the book's chapter order, hierarchy, and file paths. Draft chapters can be indicated by empty file paths. ```markdown # Summary [Introduction](introduction.md) # Part One: Basics - [Getting Started](getting-started.md) - [Installation](installation.md) - [Linux](installation/linux.md) - [macOS](installation/macos.md) # Part Two: Advanced - [Configuration](configuration.md) - [Draft Chapter]() ---------- [Contributors](contributors.md) ``` -------------------------------- ### Download and build mdBook from pre-compiled binaries Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/continuous-integration.md Use `curl` to download and extract mdBook binaries. This method is fast and doesn't require Rust installation. Ensure the URL points to the correct version and architecture. ```sh mkdir bin curl -sSL https://github.com/rust-lang/mdBook/releases/download/v{{ mdbook-version }}/mdbook-v{{ mdbook-version }}-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin bin/mdbook build ``` -------------------------------- ### Rust External Renderer Example Source: https://context7.com/rust-lang/mdbook/llms.txt Implement an external renderer in Rust that reads RenderContext from stdin, performs a version compatibility check, and writes book content to an output file. It uses the semver crate for version checks. ```rust // External renderer binary: src/main.rs use std::io; use std::fs; use mdbook_renderer::{RenderContext, book::BookItem}; use semver::{Version, VersionReq}; fn main() -> anyhow::Result<()> { let mut stdin = io::stdin(); let ctx = RenderContext::from_json(&mut stdin)?; // Version compatibility check let req = VersionReq::parse(">=0.5").unwrap(); let ver = Version::parse(&ctx.version)?; if !req.matches(&ver) { eprintln!("Warning: mdbook version {} may be incompatible", ctx.version); } fs::create_dir_all(&ctx.destination)?; let out = ctx.destination.join("output.txt"); let mut content = String::new(); for item in ctx.book.iter() { if let BookItem::Chapter(ch) = item { content.push_str(&format!("=== {} ===\n{}\n\n", ch.name, ch.content)); } } fs::write(out, content)?; Ok(()) } ``` -------------------------------- ### Serve and open the book locally Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/creating.md The `mdbook serve --open` command builds the book and starts a local web server. The `--open` flag automatically opens the book in your default web browser. The server watches for file changes and automatically rebuilds and refreshes the browser. ```sh mdbook serve --open ``` -------------------------------- ### Build and open book Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/build.md Use the --open flag to automatically open the rendered book in your default web browser after the build is complete. ```bash mdbook build --open ``` -------------------------------- ### Travis CI Configuration for mdbook Build and Test Source: https://github.com/rust-lang/mdbook/wiki/Automated-Deployment:-Travis-CI This configuration sets up Travis CI to build and test an mdbook project. It caches the cargo installation to speed up subsequent runs. Ensure mdbook is installed using `cargo install` before running build and test commands. ```yaml language: rust sudo: false cache: - cargo ust: - stable before_script: - cargo install --vers "^0.4" mdbook script: # In case of custom book path: mdbook build path/to/mybook && mdbook test path/to/mybook - mdbook build && mdbook test ``` -------------------------------- ### Enable Custom Backend in book.toml Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/backends.md Add an `output.wordcount` table to your `book.toml` file to enable the custom backend. Ensure the HTML backend is also present if you add custom ones. ```diff [book] title = "mdBook Documentation" description = "Create book from markdown files. Like Gitbook but implemented in Rust" authors = ["Mathieu David", "Michael-F-Bryan"] + [output.html] + [output.wordcount] ``` -------------------------------- ### Initialize a new mdBook project Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/init.md Run this command in your terminal to create a new mdBook project in the current directory. It sets up the basic file structure for your book. ```bash mdbook init ``` -------------------------------- ### Serve a book with custom host and port Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/serve.md Allows specifying a custom port (e.g., 8000) and hostname (e.g., 127.0.0.1) for the local server. ```bash mdbook serve path/to/book -p 8000 -n 127.0.0.1 ``` -------------------------------- ### Kotlin Hello World Program Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md A basic Kotlin program that prints 'Hello, World!' to the console, demonstrating the entry point for execution. ```kotlin package org.kotlinlang.play fun main() { println("Hello, World!") } ``` -------------------------------- ### Install latest mdBook from GitHub using Cargo Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/installation.md Installs the latest development version of mdBook directly from its GitHub repository. Ensure Cargo's binary directory is in your PATH. ```sh cargo install --git https://github.com/rust-lang/mdBook.git mdbook ``` -------------------------------- ### Go Program for Hello World Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md A basic Go program that prints 'Hello World!' to the standard output. ```go package main import "fmt" func main() { fmt.Println("Hello World!") } ``` -------------------------------- ### Uninstall mdBook using Cargo Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/installation.md Removes the mdBook executable installed via Cargo. ```sh cargo uninstall mdbook ``` -------------------------------- ### Initialize a new mdBook project Source: https://context7.com/rust-lang/mdbook/llms.txt Use `mdbook init` to create a new book directory with default files. The `--title` flag sets the book's title, and `--ignore` can skip interactive prompts. ```sh mdbook init my-book --title "My Awesome Book" --ignore git # The generated layout: # my-book/ # ├── .gitignore # ├── book.toml # └── src/ # ├── chapter_1.md # └── SUMMARY.md cd my-book ``` -------------------------------- ### Format Entire Project with cargo fmt Source: https://github.com/rust-lang/mdbook/blob/master/CONTRIBUTING.md Run this command from the project's root directory to format all bin and lib files in the current package. ```bash cargo fmt ``` -------------------------------- ### Build Options Configuration Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/configuration/general.md Configure build-related options such as the output directory, handling of missing files, and extra directories to watch. ```toml [build] build-dir = "book" # the directory where the output is placed create-missing = true # whether or not to create missing pages use-default-preprocessors = true # use the default preprocessors extra-watch-dirs = [] # directories to watch for triggering builds ``` -------------------------------- ### Include with Rustdoc Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/test/passing_tests/src/passing1.md Includes code from 'test3.rs' starting from line 2, intended for rustdoc. ```rust {{#rustdoc_include test3.rs:2}} ``` -------------------------------- ### Normal Blockquote Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/basic_markdown/src/blockquotes.md A standard blockquote with multiple lines of text. Each line starts with the '>' character. ```markdown > foo > bar ``` -------------------------------- ### Empty Blockquote Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/basic_markdown/src/blockquotes.md An empty blockquote is rendered as a blank line. No specific setup is required. ```markdown > ``` -------------------------------- ### Nix: String Concatenation Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Demonstrates basic string concatenation in Nix. ```nix let world = "World!"; in "Hello " + world ``` -------------------------------- ### Inline JavaScript Alert Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/search/reasonable_search_index/src/intro.md An example of inline JavaScript within a script tag, which might be indexed. ```javascript alert("inline"); ``` -------------------------------- ### Plaintext: Simple Text Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md An example of plain text content, not associated with any specific programming language syntax. ```plaintext I think this is simply plain text? Hello World! ``` -------------------------------- ### Python: Function and Class Definition Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Includes a decorated function with a docstring, a class definition, and an example of an interpreter prompt. ```python @requires_authorization(roles=["ADMIN"]) def somefunc(param1='', param2=0): r'''A docstring''' if param1 > param2: # interesting print 'Gre\'ater' return (param2 - param1 + 1 + 0b10l) or None class SomeClass: pass >>> message = '''interpreter ... prompt''' ``` -------------------------------- ### Initialize and Scaffold a New mdBook Source: https://context7.com/rust-lang/mdbook/llms.txt Initializes a new mdBook project with a specified directory, configuration, and optional .gitignore file. Requires the mdbook_driver crate. ```rust use mdbook_driver::MDBook; use mdbook_driver::config::Config; fn main() -> anyhow::Result<()> { let mut cfg = Config::default(); cfg.book.title = Some("My New Book".to_string()); cfg.book.authors.push("Bob".to_string()); let book = MDBook::init("/tmp/new-book") .with_config(cfg) .create_gitignore(true) .copy_theme(false) .build()?; // Directory structure created: // /tmp/new-book/ // ├── .gitignore // ├── book.toml // └── src/ // ├── chapter_1.md // └── SUMMARY.md println!("Source dir: {}", book.source_dir().display()); Ok(()) } ``` -------------------------------- ### Indented Code Block Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/basic_markdown/src/code-blocks.md A code block created using indentation, commonly used for simple code examples. ```text Indented code block. ``` -------------------------------- ### CoffeeScript Functions and Classes Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Illustrates CoffeeScript syntax for defining functions with default parameters and creating classes with constructors and methods. ```coffeescript grade = (student, period=(if b? then 7 else 6)) -> if student.excellentWork "A+" else if student.okayStuff if student.triedHard then "B" else "B-" else "C" class Animal extends Being constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." ``` -------------------------------- ### Configure mdBook Renderers and Preprocessors Source: https://context7.com/rust-lang/mdbook/llms.txt Configuration for custom external renderers and preprocessors. Ensure the binary is in PATH. ```toml [output.epub] # Custom preprocessor (binary must be in PATH as "mdbook-katex") [preprocessor.katex] before = ["links"] # run before the links preprocessor optional = true # do not error if binary not found ``` -------------------------------- ### Build mdbook and generate sitemap Source: https://github.com/rust-lang/mdbook/wiki/Apache Builds the mdbook site and generates a sitemap using sscli. Also includes options for creating or overwriting the robots.txt file. ```sh mdbook build --dest-dir /var/www/html/ sscli -b https:// -r /var/www/html/ touch /var/www/html/robot.txt # OR cat > /var/www/html.robots.txt < {{! only show if author exists }} {{#if author}}

{{firstName}} {{lastName}}

{{/if}} ``` -------------------------------- ### Serve a book from a specific directory Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/serve.md Specifies a directory to use as the book's root instead of the current working directory. ```bash mdbook serve path/to/book ``` -------------------------------- ### mdBook configuration file (book.toml) Source: https://context7.com/rust-lang/mdbook/llms.txt The `book.toml` file configures book metadata, build settings, and output options. It uses TOML format. ```toml [book] title = "My Book" authors = ["Jane Doe"] description = "A comprehensive guide." src = "src" # source directory (default: "src") language = "en" text-direction = "ltr" # "ltr" or "rtl" [rust] edition = "2021" # default Rust edition for code blocks [build] build-dir = "book" # output directory create-missing = true # auto-create missing chapter files use-default-preprocessors = true extra-watch-dirs = ["../shared-assets"] [output.html] default-theme = "light" preferred-dark-theme = "navy" smart-punctuation = true # curly quotes, em-dashes, etc. definition-lists = true admonitions = true mathjax-support = false additional-css = ["custom.css"] additional-js = ["custom.js"] git-repository-url = "https://github.com/user/my-book" edit-url-template = "https://github.com/user/my-book/edit/main/{path}" [output.html.search] enable = true limit-results = 30 use-boolean-and = true [output.html.code.hidelines] python = "~" # hide Python lines starting with "~" [output.html.playground] runnable = true editable = false ``` -------------------------------- ### Separator Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/summary.md Separators, represented by a line of at least three dashes ('---'), render as a horizontal line in the table of contents. ```markdown # My Part Title [A Prefix Chapter](relative/path/to/markdown.md) --- - [First Chapter](relative/path/to/markdown2.md) ``` -------------------------------- ### Suffix Chapter Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/summary.md Unnumbered suffix chapters appear after the numbered chapters and can be denoted by either a link or a list item. ```markdown - [Last Chapter](relative/path/to/markdown.md) [Title of Suffix Chapter](relative/path/to/markdown2.md) ``` -------------------------------- ### Python-like Pseudocode with Hidden Lines Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/rendering/hidelines/expected/hide-lines.html Illustrates hidden and non-hidden lines in a Python-like syntax. Lines starting with '#' are typically hidden. ```pseudocode hidden() nothidden(): hidden() hidden() nothidden() ``` ```pseudocode hidden() nothidden(): hidden() hidden() nothidden() ``` -------------------------------- ### Markdown Formatting Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Illustrates various Markdown features including headings, links, emphasis, lists, code segments, and blockquotes. ```markdown # hello world you can write text [with links](http://example.com) inline or [link references][1]. - one _thing_ has *em*phasis - two **things** are **bold** [1]: http://example.com --- # hello world > markdown is so cool so are code segments 1. one thing (yeah!) 2. two thing `i can write code`, and `more` wipee! ``` -------------------------------- ### JavaScript Alert Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/search/reasonable_search_index/src/intro.md This JavaScript code demonstrates an alert box. It is embedded within HTML and may be indexed by search engines. ```javascript if (3 < 5 > 10) { alert("The sky is falling!"); } ``` -------------------------------- ### Using Font-Awesome Icons in mdBook Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/mdbook.md This example shows the HTML syntax for including a Font-Awesome icon, which mdBook will convert to an inline SVG. ```hbs The result looks like this: ``` -------------------------------- ### Handling Inline HTML Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/basic_markdown/expected/html.html Inline HTML is generally preserved as-is. This example shows a simple HTML tag within markdown. ```markdown This is a paragraph with bold text. ``` -------------------------------- ### Run mdbook-compare Source: https://github.com/rust-lang/mdbook/blob/master/crates/mdbook-compare/README.md Execute the mdbook-compare utility with paths to the original and new mdbook executables, and the book directory. ```sh cargo run --manifest-path /path/to/mdBook/Cargo.toml -p mdbook-compare -- \ /path/to/orig/mdbook /path/to/my-book /path/to/new/mdbook /path/to/my-book ``` -------------------------------- ### Markdown Images Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/markdown.md Shows how to embed images using the same syntax as links, but with an exclamation mark prefix. The example includes an HTML representation. ```markdown ![The Rust Logo](images/rust-logo-blk.svg) ``` ```html

The Rust Logo

``` -------------------------------- ### Prefix Chapter Example Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/summary.md Unnumbered prefix chapters, like forewords or introductions, must be at the root level and cannot follow numbered chapters. ```markdown [A Prefix Chapter](relative/path/to/markdown.md) - [First Chapter](relative/path/to/markdown2.md) ``` -------------------------------- ### Initialize mdBook with a gitignore file Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/cli/init.md Use the `--ignore=git` flag to automatically create a `.gitignore` file that excludes the `book` output directory. This is the default behavior if not explicitly disabled. ```bash mdbook init --ignore=git ``` -------------------------------- ### JSON Data Structure Example Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md A sample JSON array of objects, illustrating a common data structure for items with titles, counts, and descriptions. ```json [ { "title": "apples", "count": [12000, 20000], "description": { "text": "...", "sensitive": false } }, { "title": "oranges", "count": [17500, null], "description": { "text": "...", "sensitive": false } } ] ``` -------------------------------- ### Rust Code Block with Variable Assignment Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/markdown/basic_markdown/expected/code-blocks.html A standard Rust code block demonstrating variable assignment. Useful for simple Rust examples. ```rust #![allow(unused)] fn main() { let x = 1; } ``` -------------------------------- ### Navigate to the book directory Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/guide/creating.md After initializing a book, change your current directory to the newly created book's root folder to execute further mdbook commands. ```sh cd my-first-book ``` -------------------------------- ### Define Wordcount Configuration Struct Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/for_developers/backends.md Define a serializable struct to hold custom configuration for a backend. This example shows a `WordcountConfig` with an `ignores` field. ```rust use serde_derive::{Serialize, Deserialize}; ... #[derive(Debug, Default, Serialize, Deserialize)] #[serde(default, rename_all = "kebab-case")] pub struct WordcountConfig { pub ignores: Vec, } ``` -------------------------------- ### SQL: Table Creation and Insertion Source: https://github.com/rust-lang/mdbook/blob/master/tests/gui/books/highlighting/src/languages.md Defines a 'topic' table with foreign key constraints and inserts a sample record. ```sql CREATE TABLE "topic" ( "id" integer NOT NULL PRIMARY KEY, "forum_id" integer NOT NULL, "subject" varchar(255) NOT NULL ); ALTER TABLE "topic" ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id") REFERENCES "forum" ("id"); -- Initials insert into "topic" ("forum_id", "subject") values (2, 'D\'artagnian'); ``` -------------------------------- ### Configure Custom Backend Options Source: https://github.com/rust-lang/mdbook/blob/master/guide/src/format/configuration/renderers.md Custom backends can accept additional configuration options. These are added as key-value pairs within the backend's `[output.]` table. ```toml [output.wordcount] ignores = ["Example Chapter"] ``` -------------------------------- ### Python Code with Hidden Lines Source: https://github.com/rust-lang/mdbook/blob/master/tests/testsuite/rendering/hidelines/src/hide-lines.md Demonstrates hiding lines in Python code using '~' prefix. Lines starting with '~' are hidden. ```python ~hidden() nothidden(): ~ hidden() ~hidden() nothidden() ```