Skip to main content

web_capture/
markdown.rs

1//! Markdown conversion module
2//!
3//! This module provides functions for converting HTML to Markdown format.
4
5use crate::html::convert_relative_urls;
6use crate::Result;
7use regex::Regex;
8use scraper::{Html, Selector};
9use tracing::{debug, info};
10
11/// Convert HTML content to Markdown
12///
13/// This function cleans the HTML (removing scripts, styles, etc.)
14/// and converts it to Markdown format.
15///
16/// # Arguments
17///
18/// * `html` - The HTML content to convert
19/// * `base_url` - Optional base URL for converting relative URLs to absolute
20///
21/// # Returns
22///
23/// The Markdown content as a string
24///
25/// # Errors
26///
27/// Returns an error if conversion fails
28pub fn convert_html_to_markdown(html: &str, base_url: Option<&str>) -> Result<String> {
29    info!("Converting HTML to Markdown");
30
31    // Convert relative URLs to absolute if base_url is provided
32    let processed_html = base_url.map_or_else(
33        || html.to_string(),
34        |base| convert_relative_urls(html, base),
35    );
36
37    // Parse and clean the HTML
38    let cleaned_html = clean_html(&processed_html);
39
40    // Preserve hierarchical heading numbering (e.g. "13. Foo", "13.1 Bar").
41    // Unwrap <ol><li><hN>13. Foo</hN></li></ol> -> <hN>13. Foo</hN> so that
42    // html2md does not restart the OL counter at "1." and clobber the source
43    // number that already lives inside the heading text.
44    let cleaned_html = preserve_leading_heading_numbering(&cleaned_html);
45
46    // Drop empty `title=""` attributes from `<img>` tags. html2md emits
47    // `![](src "")` for them, which the markdown-side base64 image extractor
48    // mis-parses (its `[^)]+` payload group swallows the trailing ` ""`,
49    // making the decoded base64 invalid).
50    let cleaned_html = strip_empty_img_titles(&cleaned_html);
51
52    // Move <img> elements out of headings so html2md always sees them.
53    // Some html2md versions only emit text children for <h1>..<h6>,
54    // silently dropping inline images.
55    let heading_safe_html = hoist_images_from_headings(&cleaned_html);
56
57    // Compute the number that each top-level <ol> item should carry, in
58    // document order, so we can rewrite html2md's per-list-restarting "1."
59    // prefixes into a single continuous sequence (matching the JS converter's
60    // output) and honour explicit `<ol start="N">` attributes.
61    let ol_item_numbers = compute_top_level_ordered_list_item_numbers(&heading_safe_html);
62
63    // Convert to Markdown using html2md
64    let markdown = html2md::parse_html(&heading_safe_html);
65
66    // Renumber unindented ordered-list lines in the markdown output to match
67    // the precomputed numbers. Indented lines (nested lists) are left alone
68    // so html2md's per-list "1." restart for nested levels is preserved.
69    let markdown = renumber_top_level_ordered_list_lines(&markdown, &ol_item_numbers);
70
71    // Decode HTML entities to unicode characters
72    let decoded_markdown = crate::html::decode_html_entities(&markdown);
73
74    // Preserve non-breaking spaces as &nbsp; entities for clear marking
75    let normalized_markdown = decoded_markdown.replace('\u{00A0}', "&nbsp;");
76
77    // Clean up the markdown output
78    let cleaned_markdown = clean_markdown(&normalized_markdown);
79
80    info!(
81        "Successfully converted to Markdown ({} bytes)",
82        cleaned_markdown.len()
83    );
84    Ok(cleaned_markdown)
85}
86
87#[must_use]
88pub fn select_html(html: &str, selector_str: &str) -> Option<String> {
89    let selector = Selector::parse(selector_str).ok()?;
90    let document = Html::parse_document(html);
91    document
92        .select(&selector)
93        .next()
94        .map(|element| element.html())
95}
96
97/// Clean HTML content before Markdown conversion
98///
99/// Removes scripts, styles, and other elements that shouldn't be in Markdown.
100fn clean_html(html: &str) -> String {
101    debug!("Cleaning HTML for Markdown conversion");
102
103    let document = Html::parse_document(html);
104
105    // Create a mutable string to build our cleaned HTML
106    let mut cleaned = html.to_string();
107
108    // Remove script tags
109    if let Ok(selector) = Selector::parse("script") {
110        for element in document.select(&selector) {
111            let outer_html = element.html();
112            cleaned = cleaned.replace(&outer_html, "");
113        }
114    }
115
116    // Remove style tags
117    if let Ok(selector) = Selector::parse("style") {
118        for element in document.select(&selector) {
119            let outer_html = element.html();
120            cleaned = cleaned.replace(&outer_html, "");
121        }
122    }
123
124    // Remove noscript tags
125    if let Ok(selector) = Selector::parse("noscript") {
126        for element in document.select(&selector) {
127            let outer_html = element.html();
128            cleaned = cleaned.replace(&outer_html, "");
129        }
130    }
131
132    cleaned
133}
134
135/// Unwrap `<ol><li><hN>...</hN></li></ol>` when the heading text already
136/// carries a leading number (e.g. "13. Foo"), and replace such a list with the
137/// bare heading. Without this, `html2md` restarts ordered-list numbering at
138/// "1." and the document loses the original section number.
139///
140/// Also lifts a leading "13. " out of an inner `<strong>` so html2md emits
141/// `#### 13. Foo` (matchable by the test) rather than `#### **13. Foo**`.
142fn preserve_leading_heading_numbering(html: &str) -> String {
143    let pattern = Regex::new(
144        r"(?is)<ol\b[^>]*>\s*<li\b[^>]*>\s*(<h[1-6]\b[^>]*>(?:.*?)</h[1-6]>)\s*</li>\s*</ol>",
145    )
146    .expect("valid regex");
147    let leading_number_in_strong =
148        Regex::new(r"(?is)(<h[1-6]\b[^>]*>)\s*<strong\b[^>]*>\s*(\d+\.\s+)([\s\S]*?)</strong>")
149            .expect("valid regex");
150    let leading_number_plain = Regex::new(r"(?is)<h[1-6]\b[^>]*>\s*\d+\.\s").expect("valid regex");
151
152    let unwrapped = pattern
153        .replace_all(html, |caps: &regex::Captures<'_>| {
154            let heading = &caps[1];
155            if leading_number_in_strong.is_match(heading) || leading_number_plain.is_match(heading)
156            {
157                heading.to_string()
158            } else {
159                caps[0].to_string()
160            }
161        })
162        .into_owned();
163
164    leading_number_in_strong
165        .replace_all(&unwrapped, |caps: &regex::Captures<'_>| {
166            let open = &caps[1];
167            let number = &caps[2];
168            let inner = &caps[3];
169            format!("{open}{number}<strong>{inner}</strong>")
170        })
171        .into_owned()
172}
173
174/// Move `<img>` tags out of `<h1>`..`<h6>` elements.
175///
176/// Rewrites `<hN>...<img ...>...text</hN>` →
177/// `<hN>...text</hN>\n<p><img ...></p>` so that any HTML→Markdown
178/// converter sees the images at block level.
179fn hoist_images_from_headings(html: &str) -> String {
180    use std::fmt::Write;
181
182    let img_re = Regex::new(r"<img\s[^>]*>").expect("valid regex");
183    let mut result = html.to_string();
184
185    for level in 1..=6 {
186        let heading_re = Regex::new(&format!(r"(?si)(<h{level}\b[^>]*>)(.*?)(</h{level}>)"))
187            .expect("valid regex");
188
189        result = heading_re
190            .replace_all(&result, |caps: &regex::Captures<'_>| {
191                let open = &caps[1];
192                let inner = &caps[2];
193                let close = &caps[3];
194
195                let imgs: Vec<&str> = img_re.find_iter(inner).map(|m| m.as_str()).collect();
196
197                if imgs.is_empty() {
198                    return caps[0].to_string();
199                }
200
201                let stripped = img_re.replace_all(inner, "").to_string();
202                let mut out = format!("{open}{stripped}{close}");
203                for img in imgs {
204                    write!(out, "\n<p>{img}</p>").expect("write to String");
205                }
206                out
207            })
208            .into_owned();
209    }
210
211    result
212}
213
214/// Remove `title=""` (case-insensitive, single or double quoted, with any
215/// surrounding whitespace) from `<img>` tags.
216///
217/// Background: Google Docs HTML exports emit `<img title="" alt="" src="...">`.
218/// The `html2md` crate renders that as `![](src "")` — a syntactically valid
219/// markdown image, but the empty title attribute then trips up the markdown-side
220/// base64 image extractor, whose `[^)]+` payload group greedily swallows the
221/// trailing ` ""`, leaving an invalid base64 string that fails to decode.
222///
223/// Stripping the attribute here keeps the rendered markdown clean *and* lets
224/// any downstream tool that parses the markdown image syntax do the right
225/// thing. Non-empty titles are left untouched.
226fn strip_empty_img_titles(html: &str) -> String {
227    let img_re = Regex::new(r"(?is)<img\b[^>]*>").expect("valid regex");
228    let empty_title_re = Regex::new(r#"(?i)\s+title\s*=\s*(?:""|'')"#).expect("valid regex");
229    img_re
230        .replace_all(html, |caps: &regex::Captures<'_>| {
231            let tag = caps.get(0).expect("match 0").as_str();
232            empty_title_re.replace_all(tag, "").into_owned()
233        })
234        .into_owned()
235}
236
237/// Walk every top-level `<ol>` in document order and return the number that
238/// each direct `<li>` child should carry. Without an explicit `start="N"`,
239/// lists continue the running counter from the previous list (e.g. 1, 2 then
240/// 3, 4 across two consecutive `<ol>`s). With `start="N"`, the counter resets
241/// to `N` for that list and subsequent lists continue from there.
242///
243/// Top-level here means "not nested inside another `<ol>` or `<ul>`" — nested
244/// lists keep their own per-list numbering, matching `html2md`'s default.
245fn compute_top_level_ordered_list_item_numbers(html: &str) -> Vec<u32> {
246    let document = Html::parse_document(html);
247    let Ok(ol_selector) = Selector::parse("ol") else {
248        return Vec::new();
249    };
250    let mut numbers = Vec::new();
251    let mut counter: u32 = 1;
252    for ol in document.select(&ol_selector) {
253        let nested = ol.ancestors().any(|n| {
254            n.value()
255                .as_element()
256                .is_some_and(|e| e.name() == "ol" || e.name() == "ul")
257        });
258        if nested {
259            continue;
260        }
261        if let Some(start) = ol
262            .value()
263            .attr("start")
264            .and_then(|s| s.trim().parse::<u32>().ok())
265        {
266            counter = start;
267        }
268        let li_count = ol
269            .children()
270            .filter(|n| n.value().as_element().is_some_and(|e| e.name() == "li"))
271            .count();
272        for _ in 0..li_count {
273            numbers.push(counter);
274            counter = counter.saturating_add(1);
275        }
276    }
277    numbers
278}
279
280/// Replace the prefix of each unindented `^\d+\.\s` line in `markdown` with
281/// the next number from `numbers`, in document order. Indented lines (nested
282/// list items) are skipped so `html2md`'s per-list "1." restart for nested
283/// levels is preserved. Setext heading underlines (`====` / `----`) are
284/// detected so a `1. Headings` line followed by an underline is not treated
285/// as a list item. Lines beyond the end of `numbers` are left untouched.
286fn renumber_top_level_ordered_list_lines(markdown: &str, numbers: &[u32]) -> String {
287    use std::fmt::Write;
288
289    let item_re = Regex::new(r"^(\d+)\.(\s)").expect("valid regex");
290    let setext_re = Regex::new(r"^(=+|-+)\s*$").expect("valid regex");
291    let lines: Vec<&str> = markdown.split_inclusive('\n').collect();
292    let mut out = String::with_capacity(markdown.len());
293    let mut idx: usize = 0;
294
295    for (i, line) in lines.iter().enumerate() {
296        let body = line.strip_suffix('\n').unwrap_or(line);
297        if let Some(caps) = item_re.captures(body) {
298            let next_body = lines
299                .get(i + 1)
300                .map_or("", |l| l.strip_suffix('\n').unwrap_or(l));
301            let is_setext_heading = setext_re.is_match(next_body);
302            if !is_setext_heading {
303                if let Some(&n) = numbers.get(idx) {
304                    let after = &body[caps.get(0).expect("match 0").end()..];
305                    let sep = caps.get(2).expect("group 2").as_str();
306                    write!(out, "{n}.{sep}{after}").expect("write to String");
307                    if line.ends_with('\n') {
308                        out.push('\n');
309                    }
310                    idx += 1;
311                    continue;
312                }
313            }
314        }
315        out.push_str(line);
316    }
317    out
318}
319
320/// Clean up Markdown output
321///
322/// Removes excessive whitespace and normalizes the output.
323pub fn clean_markdown(markdown: &str) -> String {
324    debug!("Cleaning Markdown output");
325
326    // Remove excessive blank lines (more than 2 consecutive newlines)
327    let mut result = markdown.to_string();
328
329    // Replace multiple consecutive newlines with at most two
330    while result.contains("\n\n\n") {
331        result = result.replace("\n\n\n", "\n\n");
332    }
333
334    // Trim leading and trailing whitespace
335    result = result.trim().to_string();
336
337    // Ensure the document ends with a newline
338    if !result.is_empty() && !result.ends_with('\n') {
339        result.push('\n');
340    }
341
342    result
343}