|
| 1 | +use comrak::html::ChildRendering; |
| 2 | +use comrak::{create_formatter, nodes::NodeValue}; |
| 3 | +use std::io::Write; |
| 4 | + |
| 5 | +create_formatter!(CustomFormatter<usize>, { |
| 6 | + NodeValue::Emph => |context, entering| { |
| 7 | + context.user += 1; |
| 8 | + if entering { |
| 9 | + context.write_all(b"<i>")?; |
| 10 | + } else { |
| 11 | + context.write_all(b"</i>")?; |
| 12 | + } |
| 13 | + }, |
| 14 | + NodeValue::Strong => |context, entering| { |
| 15 | + context.user += 1; |
| 16 | + context.write_all(if entering { b"<b>" } else { b"</b>" })?; |
| 17 | + }, |
| 18 | + NodeValue::Image(ref nl) => |context, node, entering| { |
| 19 | + assert!(node.data.borrow().sourcepos == (3, 1, 3, 18).into()); |
| 20 | + if entering { |
| 21 | + context.write_all(nl.url.to_uppercase().as_bytes())?; |
| 22 | + } |
| 23 | + return Ok(ChildRendering::Skip); |
| 24 | + }, |
| 25 | +}); |
| 26 | + |
| 27 | +fn main() { |
| 28 | + use comrak::{parse_document, Arena, Options}; |
| 29 | + |
| 30 | + let options = Options::default(); |
| 31 | + let arena = Arena::new(); |
| 32 | + let doc = parse_document( |
| 33 | + &arena, |
| 34 | + "_Hello_, **world**.\n\n", |
| 35 | + &options, |
| 36 | + ); |
| 37 | + |
| 38 | + let mut buf: Vec<u8> = vec![]; |
| 39 | + let converted_count = CustomFormatter::format_document(doc, &options, &mut buf, 0).unwrap(); |
| 40 | + |
| 41 | + assert_eq!( |
| 42 | + std::str::from_utf8(&buf).unwrap(), |
| 43 | + "<p><i>Hello</i>, <b>world</b>.</p>\n<p>/IMG.PNG</p>\n" |
| 44 | + ); |
| 45 | + |
| 46 | + assert_eq!(converted_count, 4); |
| 47 | +} |
0 commit comments