Debian Codegraph @

examples/custom_headings.rs

raw
1 use comrak::{
2 Options,
3 adapters::{HeadingAdapter, HeadingMeta},
4 markdown_to_html_with_plugins,
5 nodes::Sourcepos,
6 options::Plugins,
7 };
8 use std::fmt::{self, Write};
9
10 fn main() {
11 let adapter = CustomHeadingAdapter;
12 let mut options = Options::default();
13 let mut plugins = Plugins::default();
14 plugins.render.heading_adapter = Some(&adapter);
15
16 print_html(
17 "Some text.\n\n## Please hide me from search\n\nSome other text",
18 &options,
19 &plugins,
20 );
21 print_html(
22 "Some text.\n\n### Here is some `code`\n\nSome other text",
23 &options,
24 &plugins,
25 );
26 print_html(
27 "Some text.\n\n### Here is some **bold** text and some *italicized* text\n\nSome other text",
28 &options,
29 &plugins,
30 );
31 options.render.sourcepos = true;
32 print_html("# Here is a [link](/)", &options, &plugins);
33 }
34
35 struct CustomHeadingAdapter;
36
37 impl HeadingAdapter for CustomHeadingAdapter {
38 fn enter(
39 &self,
40 output: &mut dyn Write,
41 heading: &HeadingMeta,
42 sourcepos: Option<Sourcepos>,
43 ) -> fmt::Result {
44 let id = slug::slugify(&heading.content);
45
46 let search_include = !&heading.content.contains("hide");
47
48 write!(output, "<h{}", heading.level)?;
49
50 if let Some(sourcepos) = sourcepos {
51 write!(output, " data-sourcepos=\"{}\"", sourcepos)?;
52 }
53
54 write!(
55 output,
56 " id=\"{}\" data-search-include=\"{}\">",
57 id, search_include
58 )
59 }
60
61 fn exit(&self, output: &mut dyn Write, heading: &HeadingMeta) -> fmt::Result {
62 write!(output, "</h{}>", heading.level)
63 }
64 }
65
66 fn print_html(document: &str, options: &Options, plugins: &Plugins) {
67 let html = markdown_to_html_with_plugins(document, options, plugins);
68 println!("{}", html);
69 }