html2md_bulletty/
codes.rs

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