Preprocessors

A preprocessor is simply a bit of code which gets run immediately after the book is loaded and before it gets rendered, allowing you to update and mutate the book. Possible use cases are:

  • Creating custom helpers like {{#include /path/to/file.md}}
  • Updating links so [some chapter](some_chapter.md) is automatically changed to [some chapter](some_chapter.html) for the HTML renderer
  • Substituting in latex-style expressions ($$ \frac{1}{3} $$) with their mathjax equivalents

Hooking Into MDBook

MDBook uses a fairly simple mechanism for discovering third party plugins. A new table is added to book.toml (e.g. preprocessor.foo for the foo preprocessor) and then mdbook will try to invoke the mdbook-foo program as part of the build process.

While preprocessors can be hard-coded to specify which backend it should be run for (e.g. it doesn’t make sense for MathJax to be used for non-HTML renderers) with the preprocessor.foo.renderer key.

[book] title = "My Book" authors = ["Michael-F-Bryan"] [preprocessor.foo] # The command can also be specified manually command = "python3 /path/to/foo.py" # Only run the `foo` preprocessor for the HTML and EPUB renderer renderer = ["html", "epub"]

In typical unix style, all inputs to the plugin will be written to stdin as JSON and mdbook will read from stdout if it is expecting output.

The easiest way to get started is by creating your own implementation of the Preprocessor trait (e.g. in lib.rs) and then creating a shell binary which translates inputs to the correct Preprocessor method. For convenience, there is an example no-op preprocessor in the examples/ directory which can easily be adapted for other preprocessors.

Example no-op preprocessor

  1. // nop-preprocessors.rs
  2. use crate::nop_lib::Nop;
  3. use clap::{App, Arg, ArgMatches, SubCommand};
  4. use mdbook::book::Book;
  5. use mdbook::errors::Error;
  6. use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext};
  7. use std::io;
  8. use std::process;
  9. pub fn make_app() -> App<'static, 'static> {
  10. App::new("nop-preprocessor")
  11. .about("A mdbook preprocessor which does precisely nothing")
  12. .subcommand(
  13. SubCommand::with_name("supports")
  14. .arg(Arg::with_name("renderer").required(true))
  15. .about("Check whether a renderer is supported by this preprocessor"),
  16. )
  17. }
  18. fn main() {
  19. let matches = make_app().get_matches();
  20. // Users will want to construct their own preprocessor here
  21. let preprocessor = Nop::new();
  22. if let Some(sub_args) = matches.subcommand_matches("supports") {
  23. handle_supports(&preprocessor, sub_args);
  24. } else if let Err(e) = handle_preprocessing(&preprocessor) {
  25. eprintln!("{}", e);
  26. process::exit(1);
  27. }
  28. }
  29. fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<(), Error> {
  30. let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?;
  31. if ctx.mdbook_version != mdbook::MDBOOK_VERSION {
  32. // We should probably use the `semver` crate to check compatibility
  33. // here...
  34. eprintln!(
  35. "Warning: The {} plugin was built against version {} of mdbook, \
  36. but we're being called from version {}",
  37. pre.name(),
  38. mdbook::MDBOOK_VERSION,
  39. ctx.mdbook_version
  40. );
  41. }
  42. let processed_book = pre.run(&ctx, book)?;
  43. serde_json::to_writer(io::stdout(), &processed_book)?;
  44. Ok(())
  45. }
  46. fn handle_supports(pre: &dyn Preprocessor, sub_args: &ArgMatches) -> ! {
  47. let renderer = sub_args.value_of("renderer").expect("Required argument");
  48. let supported = pre.supports_renderer(&renderer);
  49. // Signal whether the renderer is supported by exiting with 1 or 0.
  50. if supported {
  51. process::exit(0);
  52. } else {
  53. process::exit(1);
  54. }
  55. }
  56. /// The actual implementation of the `Nop` preprocessor. This would usually go
  57. /// in your main `lib.rs` file.
  58. mod nop_lib {
  59. use super::*;
  60. /// A no-op preprocessor.
  61. pub struct Nop;
  62. impl Nop {
  63. pub fn new() -> Nop {
  64. Nop
  65. }
  66. }
  67. impl Preprocessor for Nop {
  68. fn name(&self) -> &str {
  69. "nop-preprocessor"
  70. }
  71. fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book, Error> {
  72. // In testing we want to tell the preprocessor to blow up by setting a
  73. // particular config value
  74. if let Some(nop_cfg) = ctx.config.get_preprocessor(self.name()) {
  75. if nop_cfg.contains_key("blow-up") {
  76. return Err("Boom!!1!".into());
  77. }
  78. }
  79. // we *are* a no-op preprocessor after all
  80. Ok(book)
  81. }
  82. fn supports_renderer(&self, renderer: &str) -> bool {
  83. renderer != "not-supported"
  84. }
  85. }
  86. }

Hints For Implementing A Preprocessor

By pulling in mdbook as a library, preprocessors can have access to the existing infrastructure for dealing with books.

For example, a custom preprocessor could use the CmdPreprocessor::parse_input() function to deserialize the JSON written to stdin. Then each chapter of the Book can be mutated in-place via Book::for_each_mut(), and then written to stdout with the serde_json crate.

Chapters can be accessed either directly (by recursively iterating over chapters) or via the Book::for_each_mut() convenience method.

The chapter.content is just a string which happens to be markdown. While it’s entirely possible to use regular expressions or do a manual find & replace, you’ll probably want to process the input into something more computer-friendly. The pulldown-cmark crate implements a production-quality event-based Markdown parser, with the pulldown-cmark-to-cmark allowing you to translate events back into markdown text.

The following code block shows how to remove all emphasis from markdown, without accidentally breaking the document.

  1. #![allow(unused_variables)]
  2. fn main() {
  3. fn remove_emphasis(
  4. num_removed_items: &mut usize,
  5. chapter: &mut Chapter,
  6. ) -> Result<String> {
  7. let mut buf = String::with_capacity(chapter.content.len());
  8. let events = Parser::new(&chapter.content).filter(|e| {
  9. let should_keep = match *e {
  10. Event::Start(Tag::Emphasis)
  11. | Event::Start(Tag::Strong)
  12. | Event::End(Tag::Emphasis)
  13. | Event::End(Tag::Strong) => false,
  14. _ => true,
  15. };
  16. if !should_keep {
  17. *num_removed_items += 1;
  18. }
  19. should_keep
  20. });
  21. cmark(events, &mut buf, None).map(|_| buf).map_err(|err| {
  22. Error::from(format!("Markdown serialization failed: {}", err))
  23. })
  24. }
  25. }

For everything else, have a look at the complete example.