html2md_bulletty/
lib.rs

1use lazy_static::lazy_static;
2
3use std::boxed::Box;
4use std::collections::HashMap;
5
6use std::os::raw::c_char;
7use std::ffi::{CString, CStr};
8
9use regex::Regex;
10
11use html5ever::parse_document;
12use html5ever::driver::ParseOpts;
13use html5ever::tendril::TendrilSink;
14
15pub use markup5ever_rcdom::{RcDom, Handle, NodeData};
16
17pub mod common;
18pub mod dummy;
19pub mod anchors;
20pub mod paragraphs;
21pub mod images;
22pub mod headers;
23pub mod lists;
24pub mod styles;
25pub mod codes;
26pub mod quotes;
27pub mod tables;
28pub mod containers;
29pub mod iframes;
30
31use crate::dummy::DummyHandler;
32use crate::dummy::IdentityHandler;
33use crate::dummy::HtmlCherryPickHandler;
34use crate::paragraphs::ParagraphHandler;
35use crate::anchors::AnchorHandler;
36use crate::images::ImgHandler;
37use crate::headers::HeaderHandler;
38use crate::lists::ListItemHandler;
39use crate::lists::ListHandler;
40use crate::styles::StyleHandler;
41use crate::codes::CodeHandler;
42use crate::quotes::QuoteHandler;
43use crate::tables::TableHandler;
44use crate::containers::ContainerHandler;
45use crate::iframes::IframeHandler;
46
47lazy_static! {
48    static ref EXCESSIVE_WHITESPACE_PATTERN: Regex = Regex::new("\\s{2,}").unwrap();   // for HTML on-the-fly cleanup
49
50    static ref EMPTY_LINE_PATTERN: Regex = Regex::new("(?m)^ +$").unwrap();            // for Markdown post-processing
51    static ref EXCESSIVE_NEWLINE_PATTERN: Regex = Regex::new("\\n{3,}").unwrap();      // for Markdown post-processing
52    static ref TRAILING_SPACE_PATTERN: Regex = Regex::new("(?m)(\\S) $").unwrap();     // for Markdown post-processing
53    static ref LEADING_NEWLINES_PATTERN: Regex = Regex::new("^\\n+").unwrap();         // for Markdown post-processing
54    static ref LAST_WHITESPACE_PATTERN: Regex = Regex::new("\\s+$").unwrap();          // for Markdown post-processing
55
56    static ref START_OF_LINE_PATTERN: Regex = Regex::new("(^|\\n) *$").unwrap();                  // for Markdown escaping
57    static ref MARKDOWN_STARTONLY_KEYCHARS: Regex = Regex::new(r"^(\s*)([=>+\-#])").unwrap();     // for Markdown escaping
58    static ref MARKDOWN_MIDDLE_KEYCHARS: Regex = Regex::new(r"[<>*\\_~]").unwrap();               // for Markdown escaping
59}
60
61/// Custom variant of main function. Allows to pass custom tag<->tag factory pairs
62/// in order to register custom tag hadler for tags you want.
63///
64/// You can also override standard tag handlers this way
65/// # Arguments
66/// `html` is source HTML as `String`
67/// `custom` is custom tag hadler producers for tags you want, can be empty
68pub fn parse_html_custom(html: &str, custom: &HashMap<String, Box<dyn TagHandlerFactory>>) -> String {
69    let dom = parse_document(RcDom::default(), ParseOpts::default()).from_utf8().read_from(&mut html.as_bytes()).unwrap();
70    let mut result = StructuredPrinter::default();
71    walk(&dom.document, &mut result, custom);
72
73    return clean_markdown(&result.data);
74}
75
76/// Main function of this library. Parses incoming HTML, converts it into Markdown
77/// and returns converted string.
78/// # Arguments
79/// `html` is source HTML as `String`
80pub fn parse_html(html: &str) -> String {
81    parse_html_custom(html, &HashMap::default())
82}
83
84/// Same as `parse_html` but retains all "span" html elements intact
85/// Markdown parsers usually strip them down when rendering but they
86/// may be useful for later processing
87pub fn parse_html_extended(html: &str) -> String {
88    struct SpanAsIsTagFactory;
89    impl TagHandlerFactory for SpanAsIsTagFactory {
90        fn instantiate(&self) -> Box<dyn TagHandler> {
91            return Box::new(HtmlCherryPickHandler::default());
92        }
93    }
94
95    let mut tag_factory: HashMap<String, Box<dyn TagHandlerFactory>> = HashMap::new();
96    tag_factory.insert(String::from("span"), Box::new(SpanAsIsTagFactory{}));
97    return parse_html_custom(html, &tag_factory);
98}
99
100/// Recursively walk through all DOM tree and handle all elements according to
101/// HTML tag -> Markdown syntax mapping. Text content is trimmed to one whitespace according to HTML5 rules.
102///
103/// # Arguments
104/// `input` is DOM tree or its subtree
105/// `result` is output holder with position and context tracking
106/// `custom` is custom tag hadler producers for tags you want, can be empty
107fn walk(input: &Handle, result: &mut StructuredPrinter, custom: &HashMap<String, Box<dyn TagHandlerFactory>>) {
108    let mut handler : Box<dyn TagHandler> = Box::new(DummyHandler::default());
109    let mut tag_name = String::default();
110    match input.data {
111        NodeData::Document | NodeData::Doctype {..} | NodeData::ProcessingInstruction {..} => {},
112        NodeData::Text { ref contents }  => {
113            let mut text = contents.borrow().to_string();
114            let inside_pre = result.parent_chain.iter().any(|tag| tag == "pre");
115            if inside_pre {
116                // this is preformatted text, insert as-is
117                result.append_str(&text);
118            } else if !(text.trim().len() == 0 && (result.data.chars().last() == Some('\n') || result.data.chars().last() == Some(' '))) {
119                // in case it's not just a whitespace after the newline or another whitespace
120
121                // regular text, collapse whitespace and newlines in text
122                let inside_code = result.parent_chain.iter().any(|tag| tag == "code");
123                if !inside_code {
124                    text = escape_markdown(result, &text);
125                }
126
127                let minified_text = text.replace(['\n', '\r'], " ");
128                let minified_text = EXCESSIVE_WHITESPACE_PATTERN.replace_all(&minified_text, " ");
129
130                result.append_str(&minified_text);
131            }
132        }
133        NodeData::Comment { .. } => {}, // ignore comments
134        NodeData::Element { ref name, .. } => {
135            tag_name = name.local.to_string();
136            let inside_pre = result.parent_chain.iter().any(|tag| tag == "pre");
137            if inside_pre {
138                // don't add any html tags inside the pre section
139                handler = Box::new(DummyHandler::default());
140            }else if custom.contains_key(&tag_name) {
141                // have user-supplied factory, instantiate a handler for this tag
142                let factory = custom.get(&tag_name).unwrap();
143                handler = factory.instantiate();
144            } else {
145                // no user-supplied factory, take one of built-in ones
146                handler = match tag_name.as_ref() {
147                    // containers
148                    "div" | "section" | "header" | "footer" => Box::new(ContainerHandler::default()),
149                    // pagination, breaks
150                    "p" | "br" | "hr" => Box::new(ParagraphHandler::default()),
151                    "q" | "cite" | "blockquote" => Box::new(QuoteHandler::default()),
152                    // spoiler tag
153                    "details" | "summary" => Box::new(HtmlCherryPickHandler::default()),
154                    // formatting
155                    "b" | "i" | "s" | "strong" | "em" | "del" => Box::new(StyleHandler::default()),
156                    "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => Box::new(HeaderHandler::default()),
157                    "pre" | "code" => Box::new(CodeHandler::default()),
158                    // images, links
159                    "img" => Box::new(ImgHandler::default()),
160                    "a" => Box::new(AnchorHandler::default()),
161                    // lists
162                    "ol" | "ul" | "menu" => Box::new(ListHandler::default()),
163                    "li" => Box::new(ListItemHandler::default()),
164                    // as-is
165                    "sub" | "sup" => Box::new(IdentityHandler::default()),
166                    // tables, handled fully internally as markdown can't have nested content in tables
167                    // supports only single tables as of now
168                    "table" => Box::new(TableHandler::default()),
169                    "iframe" => Box::new(IframeHandler::default()),
170                    // other
171                    "html" | "head" | "body" => Box::new(DummyHandler::default()),
172                    _ => Box::new(DummyHandler::default())
173                };
174            }
175        }
176    }
177
178    // handle this tag, while it's not in parent chain
179    // and doesn't have child siblings
180    handler.handle(&input, result);
181
182    // save this tag name as parent for child nodes
183    result.parent_chain.push(tag_name.to_string());     // e.g. it was ["body"] and now it's ["body", "p"]
184    let current_depth = result.parent_chain.len();      // e.g. it was 1 and now it's 2
185
186    // create space for siblings of next level
187    result.siblings.insert(current_depth, vec![]);
188
189    for child in input.children.borrow().iter() {
190        if handler.skip_descendants() {
191            continue;
192        }
193
194        walk(child, result, custom);
195
196        match child.data {
197            NodeData::Element { ref name, .. } => result.siblings.get_mut(&current_depth).unwrap().push(name.local.to_string()),
198            _ => {}
199        };
200    }
201
202    // clear siblings of next level
203    result.siblings.remove(&current_depth);
204
205    // release parent tag
206    result.parent_chain.pop();
207
208    // finish handling of tag - parent chain now doesn't contain this tag itself again
209    handler.after_handle(result);
210}
211
212/// This conversion should only be applied to text tags
213///
214/// Escapes text inside HTML tags so it won't be recognized as Markdown control sequence
215/// like list start or bold text style
216fn escape_markdown(result: &StructuredPrinter, text: &str) -> String {
217    // always escape bold/italic/strikethrough
218    let mut data = MARKDOWN_MIDDLE_KEYCHARS.replace_all(&text, "\\$0").to_string();
219
220    // if we're at the start of the line we need to escape list- and quote-starting sequences
221    if START_OF_LINE_PATTERN.is_match(&result.data) {
222        data = MARKDOWN_STARTONLY_KEYCHARS.replace(&data, "$1\\$2").to_string();
223    }
224
225    // no handling of more complicated cases such as
226    // ![] or []() ones, for now this will suffice
227    return data;
228}
229
230/// Called after all processing has been finished
231///
232/// Clears excessive punctuation that would be trimmed by renderer anyway
233fn clean_markdown(text: &str) -> String {
234    // remove redundant newlines
235    let intermediate = EMPTY_LINE_PATTERN.replace_all(&text, "");                           // empty line with trailing spaces, replace with just newline
236    let intermediate = EXCESSIVE_NEWLINE_PATTERN.replace_all(&intermediate, "\n\n");  // > 3 newlines - not handled by markdown anyway
237    let intermediate = TRAILING_SPACE_PATTERN.replace_all(&intermediate, "$1");       // trim space if it's just one
238    let intermediate = LEADING_NEWLINES_PATTERN.replace_all(&intermediate, "");       // trim leading newlines
239    let intermediate = LAST_WHITESPACE_PATTERN.replace_all(&intermediate, "");        // trim last newlines
240
241    return intermediate.into_owned();
242}
243
244/// Intermediate result of HTML -> Markdown conversion.
245///
246/// Holds context in the form of parent tags and siblings chain
247/// and resulting string of markup content with current position.
248#[derive(Debug, Default)]
249pub struct StructuredPrinter {
250    /// Chain of parents leading to upmost <html> tag
251    pub parent_chain: Vec<String>,
252
253    /// Siblings of currently processed tag in order where they're appearing in html
254    pub siblings: HashMap<usize, Vec<String>>,
255
256    /// resulting markdown document
257    pub data: String,
258}
259
260impl StructuredPrinter {
261
262    /// Inserts newline
263    pub fn insert_newline(&mut self) {
264        self.append_str("\n");
265    }
266
267    /// Append string to the end of the printer
268    pub fn append_str(&mut self, it: &str) {
269        self.data.push_str(it);
270    }
271
272    /// Insert string at specified position of printer, adjust position to the end of inserted string
273    pub fn insert_str(&mut self, pos: usize, it: &str) {
274        self.data.insert_str(pos, it);
275    }
276}
277
278/// Tag handler factory. This class is required in providing proper
279/// custom tag parsing capabilities to users of this library.
280///
281/// The problem with directly providing tag handlers is that they're not stateless.
282/// Once tag handler is parsing some tag, it holds data, such as start position, indent etc.
283/// The only way to create fresh tag handler for each tag is to provide a factory like this one.
284///
285pub trait TagHandlerFactory {
286    fn instantiate(&self) -> Box<dyn TagHandler>;
287}
288
289/// Trait interface describing abstract handler of arbitrary HTML tag.
290pub trait TagHandler {
291    /// Handle tag encountered when walking HTML tree.
292    /// This is executed before the children processing
293    fn handle(&mut self, tag: &Handle, printer: &mut StructuredPrinter);
294
295    /// Executed after all children of this tag have been processed
296    fn after_handle(&mut self, printer: &mut StructuredPrinter);
297
298    fn skip_descendants(&self) -> bool {
299        return false;
300    }
301}
302
303/// FFI variant for HTML -> Markdown conversion for calling from other languages
304#[no_mangle]
305pub extern fn parse(html: *const c_char) -> *const c_char {
306    let in_html = unsafe { CStr::from_ptr(html) };
307    let out_md = parse_html(&in_html.to_string_lossy());
308
309    CString::new(out_md).unwrap().into_raw()
310}
311
312/// Expose the JNI interface for android below
313#[cfg(target_os="android")]
314#[allow(non_snake_case)]
315pub mod android {
316    extern crate jni;
317
318    use super::parse_html;
319    use super::parse_html_extended;
320
321    use self::jni::JNIEnv;
322    use self::jni::objects::{JClass, JString};
323    use self::jni::sys::jstring;
324
325    #[no_mangle]
326    pub unsafe extern fn Java_com_kanedias_html2md_Html2Markdown_parse(mut env: JNIEnv, _clazz: JClass, html: JString) -> jstring {
327        let html_java : String = env.get_string(&html).expect("Couldn't get java string!").into();
328        let markdown = parse_html(&html_java);
329        let output = env.new_string(markdown).expect("Couldn't create java string!");
330        output.into_raw()
331    }
332
333    #[no_mangle]
334    pub unsafe extern fn Java_com_kanedias_html2md_Html2Markdown_parseExtended(mut env: JNIEnv, _clazz: JClass, html: JString) -> jstring {
335        let html_java : String = env.get_string(&html).expect("Couldn't get java string!").into();
336        let markdown = parse_html_extended(&html_java);
337        let output = env.new_string(markdown).expect("Couldn't create java string!");
338        output.into_raw()
339    }
340}