Debian Codegraph @

examples/custom_formatter.rs

raw
1 use comrak::html::ChildRendering;
2 use comrak::{create_formatter, nodes::NodeValue};
3 use std::fmt::Write;
4
5 create_formatter!(CustomFormatter, {
6 NodeValue::Emph => |context, entering| {
7 if entering {
8 context.write_str("<i>")?;
9 } else {
10 context.write_str("</i>")?;
11 }
12 },
13 NodeValue::Strong => |context, entering| {
14 context.write_str(if entering { "<b>" } else { "</b>" })?;
15 },
16 NodeValue::Image(ref nl) => |context, node, entering| {
17 assert!(node.data().sourcepos == (3, 1, 3, 18).into());
18 if entering {
19 context.write_str(&nl.url.to_uppercase())?;
20 }
21 return Ok(ChildRendering::Skip);
22 },
23 });
24
25 fn main() {
26 use comrak::{Arena, Options, parse_document};
27
28 let options = Options::default();
29 let arena = Arena::new();
30 let doc = parse_document(
31 &arena,
32 "_Hello_, **world**.\n\n![title](/img.png)",
33 &options,
34 );
35
36 let mut out = String::new();
37 CustomFormatter::format_document(doc, &options, &mut out).unwrap();
38
39 assert_eq!(out, "<p><i>Hello</i>, <b>world</b>.</p>\n<p>/IMG.PNG</p>\n");
40 }