Skip to main content

fifthtry_mdbook/preprocess/
mod.rs

1//! Book preprocessing.
2
3pub use self::cmd::CmdPreprocessor;
4pub use self::index::IndexPreprocessor;
5pub use self::links::LinkPreprocessor;
6
7mod cmd;
8mod index;
9mod links;
10
11use crate::book::Book;
12use crate::config::Config;
13use crate::errors::*;
14
15use std::cell::RefCell;
16use std::collections::HashMap;
17use std::path::PathBuf;
18
19/// Extra information for a `Preprocessor` to give them more context when
20/// processing a book.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct PreprocessorContext {
23    /// The location of the book directory on disk.
24    pub root: PathBuf,
25    /// The book configuration (`book.toml`).
26    pub config: Config,
27    /// The `Renderer` this preprocessor is being used with.
28    pub renderer: String,
29    /// The calling `mdbook` version.
30    pub mdbook_version: String,
31    #[serde(skip)]
32    pub(crate) chapter_titles: RefCell<HashMap<PathBuf, String>>,
33    #[serde(skip)]
34    __non_exhaustive: (),
35}
36
37impl PreprocessorContext {
38    /// Create a new `PreprocessorContext`.
39    pub fn new(root: PathBuf, config: Config, renderer: String) -> Self {
40        PreprocessorContext {
41            root,
42            config,
43            renderer,
44            mdbook_version: crate::MDBOOK_VERSION.to_string(),
45            chapter_titles: RefCell::new(HashMap::new()),
46            __non_exhaustive: (),
47        }
48    }
49}
50
51/// An operation which is run immediately after loading a book into memory and
52/// before it gets rendered.
53pub trait Preprocessor {
54    /// Get the `Preprocessor`'s name.
55    fn name(&self) -> &str;
56
57    /// Run this `Preprocessor`, allowing it to update the book before it is
58    /// given to a renderer.
59    fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book>;
60
61    /// A hint to `MDBook` whether this preprocessor is compatible with a
62    /// particular renderer.
63    ///
64    /// By default, always returns `true`.
65    fn supports_renderer(&self, _renderer: &str) -> bool {
66        true
67    }
68}