プリプロセッサー

プリプロセッサーは、本の読み込み直後、出力生成の前に実行されるコードです。本を更新・変更できます。たとえば、次のように使えます。

  • {{#include /path/to/file.md}}のような独自のヘルパーを作る
  • LaTeX形式の式($$ \frac{1}{3} $$)を、対応するMathJaxの式へ置き換える

プリプロセッサーの使い方について、詳しくはプリプロセッサーの設定を参照してください。

MDBookへ組み込む

MDBookが第三者のプラグインを見つける仕組みは簡単です。book.tomlへ新しいテーブル(fooプリプロセッサーなら[preprocessor.foo])を追加すると、mdbookはビルド処理の中でmdbook-fooプログラムの呼び出しを試みます。

プリプロセッサーを定義し、ビルド処理を開始すると、mdBookはpreprocessor.foo.commandキーで定義したコマンドを2回実行します。1回目は、指定したレンダラーに対応するかを確認します。プロセスへ2つの引数を渡します。最初は文字列supports、次はレンダラーの名前です。プリプロセッサーは、対応する場合は終了コード0、対応しない場合は0以外で終了する必要があります。

レンダラーに対応する場合、mdbookは2回目を実行し、stdinへJSONデータを渡します。JSONは[context, book]という配列です。contextはシリアライズしたPreprocessorContextオブジェクト、bookは本の内容を含むBookオブジェクトです。

プリプロセッサーは、任意の変更を加えたBookオブジェクトを、JSON形式でstdoutへ返す必要があります。

最も簡単な始め方は、独自のPreprocessorトレイト実装を作り(たとえばlib.rsへ)、入力を適切なPreprocessorメソッドへ振り分ける、外側の実行ファイルを作る方法です。examples/ディレクトリには、ほかのプリプロセッサーへ簡単に応用できる何もしないプリプロセッサーの例があります。

何もしないプリプロセッサーの例
// nop-preprocessors.rs

//! A basic example of a preprocessor that does nothing.

use crate::nop_lib::Nop;
use clap::{Arg, ArgMatches, Command};
use mdbook_preprocessor::book::Book;
use mdbook_preprocessor::errors::Result;
use mdbook_preprocessor::{Preprocessor, PreprocessorContext};
use semver::{Version, VersionReq};
use std::io;
use std::process;

fn make_app() -> Command {
    Command::new("nop-preprocessor")
        .about("A mdbook preprocessor which does precisely nothing")
        .subcommand(
            Command::new("supports")
                .arg(Arg::new("renderer").required(true))
                .about("Check whether a renderer is supported by this preprocessor"),
        )
}

fn main() {
    let matches = make_app().get_matches();

    // Users will want to construct their own preprocessor here
    let preprocessor = Nop::new();

    if let Some(sub_args) = matches.subcommand_matches("supports") {
        handle_supports(&preprocessor, sub_args);
    } else if let Err(e) = handle_preprocessing(&preprocessor) {
        eprintln!("{e:?}");
        process::exit(1);
    }
}

fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<()> {
    let (ctx, book) = mdbook_preprocessor::parse_input(io::stdin())?;

    let book_version = Version::parse(&ctx.mdbook_version)?;
    let version_req = VersionReq::parse(mdbook_preprocessor::MDBOOK_VERSION)?;

    if !version_req.matches(&book_version) {
        eprintln!(
            "Warning: The {} plugin was built against version {} of mdbook, \
             but we're being called from version {}",
            pre.name(),
            mdbook_preprocessor::MDBOOK_VERSION,
            ctx.mdbook_version
        );
    }

    let processed_book = pre.run(&ctx, book)?;
    serde_json::to_writer(io::stdout(), &processed_book)?;

    Ok(())
}

fn handle_supports(pre: &dyn Preprocessor, sub_args: &ArgMatches) -> ! {
    let renderer = sub_args
        .get_one::<String>("renderer")
        .expect("Required argument");
    let supported = pre.supports_renderer(renderer).unwrap();

    // Signal whether the renderer is supported by exiting with 1 or 0.
    if supported {
        process::exit(0);
    } else {
        process::exit(1);
    }
}

/// The actual implementation of the `Nop` preprocessor. This would usually go
/// in your main `lib.rs` file.
#[allow(unreachable_pub, reason = "wouldn't be a problem in a proper lib.rs")]
mod nop_lib {
    use super::*;

    /// A no-op preprocessor.
    pub struct Nop;

    impl Nop {
        pub fn new() -> Nop {
            Nop
        }
    }

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

        fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book> {
            // In testing we want to tell the preprocessor to blow up by setting a
            // particular config value
            match ctx
                .config
                .get::<bool>("preprocessor.nop-preprocessor.blow-up")
            {
                Ok(Some(true)) => anyhow::bail!("Boom!!1!"),
                Ok(_) => {}
                Err(e) => anyhow::bail!("expect bool for blow-up: {e}"),
            }

            // we *are* a no-op preprocessor after all
            Ok(book)
        }

        fn supports_renderer(&self, renderer: &str) -> Result<bool> {
            Ok(renderer != "not-supported")
        }
    }

    #[cfg(test)]
    mod test {
        use super::*;

        #[test]
        fn nop_preprocessor_run() {
            let input_json = r##"[
                {
                    "root": "/path/to/book",
                    "config": {
                        "book": {
                            "authors": ["AUTHOR"],
                            "language": "en",
                            "src": "src",
                            "title": "TITLE"
                        },
                        "preprocessor": {
                            "nop": {}
                        }
                    },
                    "renderer": "html",
                    "mdbook_version": "0.4.21"
                },
                {
                    "items": [
                        {
                            "Chapter": {
                                "name": "Chapter 1",
                                "content": "# Chapter 1\n",
                                "number": [1],
                                "sub_items": [],
                                "path": "chapter_1.md",
                                "source_path": "chapter_1.md",
                                "parent_names": []
                            }
                        }
                    ]
                }
            ]"##;
            let input_json = input_json.as_bytes();

            let (ctx, book) = mdbook_preprocessor::parse_input(input_json).unwrap();
            let expected_book = book.clone();
            let result = Nop::new().run(&ctx, book);
            assert!(result.is_ok());

            // The nop-preprocessor should not have made any changes to the book content.
            let actual_book = result.unwrap();
            assert_eq!(actual_book, expected_book);
        }
    }
}

プリプロセッサーを実装するヒント

mdbook-preprocessorをライブラリーとして取り込むと、本を扱う既存の仕組みをプリプロセッサーから使えます。

たとえば、独自プリプロセッサーでは、parse_input()関数で、stdinへ渡されたJSONをデシリアライズできます。続いて、Book::for_each_mut()でBookの各章をその場で変更し、serde_jsonクレートでstdoutへ書き出せます。

章には、再帰的に順にたどって直接アクセスする方法と、便利なBook::for_each_mut()メソッドを使う方法があります。

chapter.contentは、Markdownを含む文字列にすぎません。正規表現や手作業の検索・置換でも処理できますが、コンピューターで扱いやすい形式へ変換するとよいでしょう。mdbook-markdownクレートは、mdBookがMarkdownの解析に使うpulldown-cmarkクレートを公開しています。pulldown-cmark-to-cmarkクレートで、イベントをMarkdownのテキストへ戻せます。

次のコードブロックは、文書を意図せず壊さずに、Markdownの強調をすべて取り除く方法を示します。

//! This is a demonstration of an mdBook preprocessor which parses markdown
//! and removes any instances of emphasis.

use mdbook_preprocessor::book::{Book, Chapter};
use mdbook_preprocessor::errors::Result;
use mdbook_preprocessor::{Preprocessor, PreprocessorContext};
use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use std::io;

fn main() {
    let mut args = std::env::args().skip(1);
    match args.next().as_deref() {
        Some("supports") => {
            // Supports all renderers.
            return;
        }
        Some(arg) => {
            eprintln!("unknown argument: {arg}");
            std::process::exit(1);
        }
        None => {}
    }

    if let Err(e) = handle_preprocessing() {
        eprintln!("{e}");
        std::process::exit(1);
    }
}

struct RemoveEmphasis;

impl Preprocessor for RemoveEmphasis {
    fn name(&self) -> &str {
        "remove-emphasis"
    }

    fn run(&self, _ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
        let mut total = 0;
        book.for_each_chapter_mut(|ch| match remove_emphasis(&mut total, ch) {
            Ok(s) => ch.content = s,
            Err(e) => eprintln!("failed to process chapter: {e:?}"),
        });
        eprintln!("removed {total} emphasis");
        Ok(book)
    }
}

fn remove_emphasis(num_removed_items: &mut usize, chapter: &mut Chapter) -> Result<String> {
    let mut buf = String::with_capacity(chapter.content.len());

    let events = Parser::new(&chapter.content).filter(|e| match e {
        Event::Start(Tag::Emphasis) | Event::Start(Tag::Strong) => {
            *num_removed_items += 1;
            false
        }
        Event::End(TagEnd::Emphasis) | Event::End(TagEnd::Strong) => false,
        _ => true,
    });

    Ok(pulldown_cmark_to_cmark::cmark(events, &mut buf).map(|_| buf)?)
}

pub fn handle_preprocessing() -> Result<()> {
    let pre = RemoveEmphasis;
    let (ctx, book) = mdbook_preprocessor::parse_input(io::stdin())?;

    let processed_book = pre.run(&ctx, book)?;
    serde_json::to_writer(io::stdout(), &processed_book)?;

    Ok(())
}

詳しくは例の完全なソースを参照してください。

別の言語でプリプロセッサーを実装する

mdBookはstdinとstdoutでプリプロセッサーと通信するため、Rust以外の言語でも簡単に実装できます。次のコードは、最初の章の内容を変更する、Pythonによる簡単なプリプロセッサーの実装を示します。上で示した設定に従い、preprocessor.foo.commandが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))