| 1 |
//! This is a demonstration of an mdBook preprocessor which parses markdown |
| 2 |
//! and removes any instances of emphasis. |
| 3 |
|
| 4 |
use mdbook_preprocessor::book::{Book, Chapter}; |
| 5 |
use mdbook_preprocessor::errors::Result; |
| 6 |
use mdbook_preprocessor::{Preprocessor, PreprocessorContext}; |
| 7 |
use pulldown_cmark::{Event, Parser, Tag, TagEnd}; |
| 8 |
use std::io; |
| 9 |
|
| 10 |
fn main() { |
| 11 |
let mut args = std::env::args().skip(1); |
| 12 |
match args.next().as_deref() { |
| 13 |
Some("supports") => { |
| 14 |
// Supports all renderers. |
| 15 |
return; |
| 16 |
} |
| 17 |
Some(arg) => { |
| 18 |
eprintln!("unknown argument: {arg}"); |
| 19 |
std::process::exit(1); |
| 20 |
} |
| 21 |
None => {} |
| 22 |
} |
| 23 |
|
| 24 |
if let Err(e) = handle_preprocessing() { |
| 25 |
eprintln!("{e}"); |
| 26 |
std::process::exit(1); |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
struct RemoveEmphasis; |
| 31 |
|
| 32 |
impl Preprocessor for RemoveEmphasis { |
| 33 |
fn name(&self) -> &str { |
| 34 |
"remove-emphasis" |
| 35 |
} |
| 36 |
|
| 37 |
fn run(&self, _ctx: &PreprocessorContext, mut book: Book) -> Result<Book> { |
| 38 |
let mut total = 0; |
| 39 |
book.for_each_chapter_mut(|ch| match remove_emphasis(&mut total, ch) { |
| 40 |
Ok(s) => ch.content = s, |
| 41 |
Err(e) => eprintln!("failed to process chapter: {e:?}"), |
| 42 |
}); |
| 43 |
eprintln!("removed {total} emphasis"); |
| 44 |
Ok(book) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
// ANCHOR: remove_emphasis |
| 49 |
fn remove_emphasis(num_removed_items: &mut usize, chapter: &mut Chapter) -> Result<String> { |
| 50 |
let mut buf = String::with_capacity(chapter.content.len()); |
| 51 |
|
| 52 |
let events = Parser::new(&chapter.content).filter(|e| match e { |
| 53 |
Event::Start(Tag::Emphasis) | Event::Start(Tag::Strong) => { |
| 54 |
*num_removed_items += 1; |
| 55 |
false |
| 56 |
} |
| 57 |
Event::End(TagEnd::Emphasis) | Event::End(TagEnd::Strong) => false, |
| 58 |
_ => true, |
| 59 |
}); |
| 60 |
|
| 61 |
Ok(pulldown_cmark_to_cmark::cmark(events, &mut buf).map(|_| buf)?) |
| 62 |
} |
| 63 |
// ANCHOR_END: remove_emphasis |
| 64 |
|
| 65 |
pub fn handle_preprocessing() -> Result<()> { |
| 66 |
let pre = RemoveEmphasis; |
| 67 |
let (ctx, book) = mdbook_preprocessor::parse_input(io::stdin())?; |
| 68 |
|
| 69 |
let processed_book = pre.run(&ctx, book)?; |
| 70 |
serde_json::to_writer(io::stdout(), &processed_book)?; |
| 71 |
|
| 72 |
Ok(()) |
| 73 |
} |