html2md/
codes.rs

1use super::StructuredPrinter;
2use super::TagHandler;
3
4use markup5ever_rcdom::{Handle, NodeData};
5
6#[derive(Default)]
7pub struct CodeHandler {
8    code_type: String,
9}
10
11impl CodeHandler {
12    /// Used in both starting and finishing handling
13    fn do_handle(&mut self, printer: &mut StructuredPrinter, start: bool) {
14        let immediate_parent = printer.parent_chain.last().unwrap().to_owned();
15        if self.code_type == "code" && immediate_parent == "pre" {
16            // we are already in "code" mode
17            return;
18        }
19
20        match self.code_type.as_ref() {
21            "pre" => {
22                // code block should have its own paragraph
23                if start {
24                    printer.insert_newline();
25                }
26                printer.append_str("\n```\n");
27                if !start {
28                    printer.insert_newline();
29                }
30            }
31            "code" | "samp" => printer.append_str("`"),
32            _ => {}
33        }
34    }
35}
36
37impl TagHandler for CodeHandler {
38    fn handle(&mut self, tag: &Handle, printer: &mut StructuredPrinter) {
39        self.code_type = match tag.data {
40            NodeData::Element { ref name, .. } => name.local.to_string(),
41            _ => String::new(),
42        };
43
44        self.do_handle(printer, true);
45    }
46    fn after_handle(&mut self, printer: &mut StructuredPrinter) {
47        self.do_handle(printer, false);
48    }
49}