html-to-markdown-rs 3.22.2

High-performance HTML to Markdown converter using the astral-html tokenizer. Part of the Xberg ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use std::borrow::Cow;

use super::raw_text::{PageReads, PassRead, removed_element_name, track_svg_tag};

/// Find `needle` in `haystack` at or after `from`, returning its start offset.
pub(super) fn find_subslice(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
    if from >= haystack.len() {
        return None;
    }
    memchr::memmem::find(&haystack[from..], needle).map(|off| from + off)
}

/// Find the nearest HTML comment terminator whose start is at or after `from`. ~keep
pub fn find_html_comment_end(bytes: &[u8], from: usize) -> Option<usize> {
    let rest = bytes.get(from..)?;
    memchr::memchr_iter(b'>', rest).find_map(|offset| {
        let preceding = &rest[..offset];
        (preceding.ends_with(b"--") || preceding.ends_with(b"--!")).then_some(from + offset + 1)
    })
}

/// Collapse an empty HTML comment `<!---->` at `idx` to `<!-- -->` (a single interior space).
/// Returns `Some(new_pos)` when found, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical prefix match and rewrite,
/// unchanged.
fn collapse_empty_comment(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const EMPTY_COMMENT: &[u8] = b"<!---->";
    if !bytes[idx..].starts_with(EMPTY_COMMENT) {
        return None;
    }
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    out.push_str("<!-- -->");
    Some(idx + EMPTY_COMMENT.len())
}

/// Normalize an XML-style self-closing void element (`<br/>`, `<hr/>`, `<img/>`) at `idx` to its
/// HTML5 form (`<br>`, `<hr>`, `<img>`). Returns `Some(new_pos)` when matched, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical pattern table and rewrite,
/// unchanged.
fn normalize_self_closing_void(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const SELF_CLOSING: [(&[u8], &str); 3] = [(b"<br/>", "<br>"), (b"<hr/>", "<hr>"), (b"<img/>", "<img>")];
    for (pattern, replacement) in &SELF_CLOSING {
        if bytes[idx..].starts_with(pattern) {
            let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
            out.push_str(&input[last..idx]);
            out.push_str(replacement);
            return Some(idx + pattern.len());
        }
    }
    None
}

/// Lowercase the tag name of an HTML5 void element written in upper or mixed case.
///
/// The parser compares a tag's raw source bytes against an all-lowercase
/// void-element table, so `<META>` misses it and is pushed onto the open-element stack as a
/// *container*. The parent's close tag then cannot pop it and every following sibling is
/// absorbed as its child: for `<head><META ...></head><body>` that leaves `<body>` a
/// grandchild of `<head>`, out of reach of `converter::metadata`'s direct-child rescue, and
/// the whole document converts to an empty string (issue #467). Tier-1 lowercases tag names
/// before lookup and was never affected, so this also closes a tier divergence.
///
/// Only the name is rewritten -- attribute names and values are left byte for byte alone.
/// Non-void elements need no rewrite: the parser compares open and close tags against each
/// other, so `<DIV>...</DIV>` already matches.
///
/// Returns `Some(new_pos)` when a name was rewritten, `None` otherwise.
fn normalize_void_tag_case<C: FnMut(PassRead)>(
    input: &str,
    idx: usize,
    last: usize,
    last_gt: usize,
    reads: &mut PageReads<C>,
    output: &mut Option<String>,
) -> Option<usize> {
    let bytes = input.as_bytes();
    let name_start = idx + 1;
    if !bytes.get(name_start)?.is_ascii_alphabetic() {
        return None;
    }
    let name_end = crate::converter::main_helpers::scan_tag_name_end(bytes, name_start);
    let name = &bytes[name_start..name_end];
    // ~keep Uppercase check first: it is a byte scan, while the void-element test allocates.
    if !name.iter().any(u8::is_ascii_uppercase) || !crate::converter::main_helpers::is_html5_void_element(name) {
        return None;
    }
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    out.push('<');
    out.push_str(&input[name_start..name_end].to_ascii_lowercase());
    // ~keep The rest of the tag is read with it: a `<` in an attribute value starts nothing.
    // ~keep No tag ends after the last `>` of the page.
    let whole = if idx < last_gt { reads.tag_end(bytes, idx) } else { None };
    let end = whole.unwrap_or(name_end);
    out.push_str(&input[name_end..end]);
    Some(end)
}

/// Close a raw-text `<script>` or `<style>` start tag at `idx` in the second pass: the element
/// is written as an empty element (`<tag ...></tag>`), not removed outright. A
/// `<script type="application/ld+json">` start tag is left alone (its JSON-LD body must survive
/// for metadata extraction).
///
/// Returns `Some(new_pos)` when a tag was closed, `None` when `idx` does not start such a tag.
///
/// ~keep The first pass removes each element that has an end tag, so the element here has
/// ~keep none as a rule. It is closed at its start tag and the markup after it is written: the
/// ~keep rule of issue 277 for a start tag with no end tag, in every spelling of the start tag.
/// ~keep The first pass does not read a start tag in a CDATA section. This pass does, and
/// ~keep removes the element when it has an end tag. The start tag and the end tag are read
/// ~keep with `PageReads`, the rule of the first pass, and no search is made twice.
fn strip_raw_text_tag_reopen<C: FnMut(PassRead)>(
    input: &str,
    idx: usize,
    last: usize,
    reads: &mut PageReads<C>,
    output: &mut Option<String>,
) -> Option<usize> {
    let bytes = input.as_bytes();
    let (slot, open_end) = reads.raw_text_start_tag_end(bytes, idx)?;
    let name = removed_element_name(slot)?;
    if name == "script" && is_json_ld_script_open_tag(&input[idx..open_end]) {
        return None;
    }
    let remove_end = reads
        .raw_text_end_tag(bytes, open_end, slot)
        .map_or(open_end, |(_, end)| end);
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..open_end]);
    out.push_str("</");
    out.push_str(name);
    out.push('>');
    Some(remove_end)
}

/// Strip a `<!doctype ...>` declaration at `idx`. Returns `Some(new_pos)` when found and
/// terminated, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical whitespace-skip and
/// case-insensitive `doctype` match, unchanged.
fn strip_doctype(
    input: &str,
    bytes: &[u8],
    idx: usize,
    len: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const DOCTYPE: &[u8] = b"doctype";

    if idx + 2 >= len || bytes[idx + 1] != b'!' {
        return None;
    }
    let mut cursor = idx + 2;
    while cursor < len && bytes[cursor].is_ascii_whitespace() {
        cursor += 1;
    }

    if cursor + DOCTYPE.len() > len || !bytes[cursor..cursor + DOCTYPE.len()].eq_ignore_ascii_case(DOCTYPE) {
        return None;
    }

    let end = find_tag_end(bytes, cursor + DOCTYPE.len())?;
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    Some(end)
}

/// Whether `<` at `idx` opens something that looks like real markup (a tag, a `<!...>`
/// declaration/comment, or a `<?...?>` processing instruction) rather than a bare `<` that must
/// be entity-escaped so a later HTML parse does not swallow following content as a bogus tag.
///
/// Extracted from `preprocess_html`'s main scan loop — identical byte-class checks, unchanged.
const fn looks_like_tag_start(bytes: &[u8], idx: usize, len: usize) -> bool {
    if idx + 1 >= len {
        return false;
    }
    match bytes[idx + 1] {
        b'!' => {
            idx + 2 < len
                && (bytes[idx + 2] == b'-'
                    || bytes[idx + 2].is_ascii_alphabetic()
                    || bytes[idx + 2].is_ascii_uppercase())
        }
        b'/' => idx + 2 < len && (bytes[idx + 2].is_ascii_alphabetic() || bytes[idx + 2].is_ascii_uppercase()),
        b'?' => true,
        c if c.is_ascii_alphabetic() || c.is_ascii_uppercase() => true,
        _ => false,
    }
}

/// Preprocess HTML to normalize tags and fix common issues.
pub fn preprocess_html(input: &str) -> Cow<'_, str> {
    second_pass(input, |_| {})
}

/// The second pass over one page, with the reads that a test counts.
pub(super) fn second_pass<C: FnMut(PassRead)>(input: &str, count: C) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();
    if len == 0 {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;
    let mut svg_depth = 0usize;
    let mut reads = PageReads::new(count);
    let last_gt = memchr::memrchr(b'>', bytes).unwrap_or(0);

    while idx < len {
        if bytes[idx] != b'<' {
            idx += 1;
            continue;
        }
        // ~keep No tag can terminate beyond the final `>`; do not rescan unfinished suffixes (#773).
        if last_gt <= idx && looks_like_tag_start(bytes, idx, len) {
            break;
        }
        let rewritten = collapse_empty_comment(input, bytes, idx, last, &mut output)
            .or_else(|| normalize_self_closing_void(input, bytes, idx, last, &mut output));
        if let Some(new_pos) = rewritten {
            last = new_pos;
            idx = new_pos;
            continue;
        }

        if let Some(new_idx) = track_svg_tag(bytes, idx, &mut svg_depth) {
            idx = new_idx;
            continue;
        }

        let rewritten = if svg_depth == 0 {
            normalize_void_tag_case(input, idx, last, last_gt, &mut reads, &mut output)
                .or_else(|| strip_raw_text_tag_reopen(input, idx, last, &mut reads, &mut output))
                .or_else(|| strip_doctype(input, bytes, idx, len, last, &mut output))
        } else {
            None
        };
        if let Some(new_pos) = rewritten {
            last = new_pos;
            idx = new_pos;
            continue;
        }

        if !looks_like_tag_start(bytes, idx, len) {
            let out = output.get_or_insert_with(|| String::with_capacity(input.len() + 4));
            out.push_str(&input[last..idx]);
            out.push_str("&lt;");
            idx += 1;
            last = idx;
            continue;
        }

        // ~keep A comment and a tag are read whole, as the first pass reads them: a `<` in a
        // ~keep comment or in an attribute value starts nothing. No tag ends after the last `>`
        // ~keep of the page, and no search for the end of a tag starts there.
        let whole = if svg_depth == 0 && idx < last_gt {
            reads.comment_end(bytes, idx).or_else(|| reads.tag_end(bytes, idx))
        } else {
            None
        };
        idx = whole.unwrap_or(idx + 1);
    }

    if let Some(mut out) = output {
        if last < len {
            out.push_str(&input[last..]);
        }
        Cow::Owned(out)
    } else {
        Cow::Borrowed(input)
    }
}

/// Find the end of an unquoted attribute value starting at `start`: the first ASCII whitespace
/// or `>` byte, or `bytes.len()` if neither occurs before the end of `bytes`.
///
/// Extracted from `is_json_ld_script_open_tag`'s unquoted-value branch — identical scan,
/// unchanged.
const fn scan_unquoted_attr_value_end(bytes: &[u8], start: usize) -> usize {
    let mut end = start;
    while end < bytes.len() && !bytes[end].is_ascii_whitespace() && bytes[end] != b'>' {
        end += 1;
    }
    end
}

/// Check if a script tag is a JSON-LD script.
pub fn is_json_ld_script_open_tag(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    let mut idx = 0;
    while idx + 4 <= bytes.len() {
        if eq_ascii_case_insensitive(&bytes[idx..], b"type") {
            let before_ok = idx == 0
                || bytes
                    .get(idx.saturating_sub(1))
                    .is_some_and(|b| b.is_ascii_whitespace() || *b == b'<' || *b == b'/');
            let after_ok = bytes
                .get(idx + 4)
                .is_some_and(|b| b.is_ascii_whitespace() || *b == b'=');
            if !before_ok || !after_ok {
                idx += 4;
                continue;
            }

            let mut i = idx + 4;
            while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
                i += 1;
            }
            if bytes.get(i) != Some(&b'=') {
                idx += 4;
                continue;
            }
            i += 1;
            while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
                i += 1;
            }
            if i >= bytes.len() {
                return false;
            }

            let (value_start, value_end) = match bytes[i] {
                b'"' | b'\'' => {
                    let quote = bytes[i];
                    let start = i + 1;
                    let mut end = start;
                    while end < bytes.len() && bytes[end] != quote {
                        end += 1;
                    }
                    (start, end)
                }
                _ => {
                    let start = i;
                    (start, scan_unquoted_attr_value_end(bytes, start))
                }
            };

            // ~keep The decision reads the decoded value: `ld&#43;json` names the same type.
            let value = crate::text::decode_attribute_value_cow(&tag[value_start..value_end]);
            return script_type(&value) != ScriptType::Removed;
        }
        idx += 1;
    }
    false
}

/// What the `type` of a script makes of the script.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptType {
    /// The two passes remove the script.
    Removed,
    /// The script stays in the tree and is not read as structured data.
    KeptNotRead,
    /// The script stays in the tree and is read as structured data.
    StructuredData,
}

/// The one rule of the `type` of a script. `type_value` is the decoded value of the attribute.
///
/// ~keep The two passes, the fast converter and the reader of the metadata ask this function,
/// ~keep so they cannot disagree. The media type is the value before the first `;`, with no
/// ~keep white space at its two ends, in any case. A media type that only starts with the name
/// ~keep (`application/ld+jsonx`) keeps the script in the tree, as it always did, and is not
/// ~keep structured data.
pub fn script_type(type_value: &str) -> ScriptType {
    const STRUCTURED_DATA: &[u8] = b"application/ld+json";
    let media_type = type_value.split(';').next().unwrap_or(type_value).trim().as_bytes();
    if media_type.eq_ignore_ascii_case(STRUCTURED_DATA) {
        ScriptType::StructuredData
    } else if eq_ascii_case_insensitive(media_type, STRUCTURED_DATA) {
        ScriptType::KeptNotRead
    } else {
        ScriptType::Removed
    }
}

/// Case-insensitive byte comparison for ASCII.
#[inline]
pub fn eq_ascii_case_insensitive(haystack: &[u8], needle: &[u8]) -> bool {
    if haystack.len() < needle.len() {
        return false;
    }
    haystack
        .iter()
        .zip(needle.iter())
        .all(|(a, b)| a.eq_ignore_ascii_case(b))
}

/// Check if bytes match a tag start pattern.
pub fn matches_tag_start(bytes: &[u8], mut start: usize, tag: &[u8]) -> bool {
    if start >= bytes.len() {
        return false;
    }

    if start + tag.len() > bytes.len() {
        return false;
    }

    if !bytes[start..start + tag.len()].eq_ignore_ascii_case(tag) {
        return false;
    }

    start += tag.len();

    match bytes.get(start) {
        Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') => true,
        Some(_) => false,
        None => true,
    }
}

/// Find the end of an HTML tag (the position of '>').
pub fn find_tag_end(bytes: &[u8], mut idx: usize) -> Option<usize> {
    loop {
        idx += memchr::memchr3(b'"', b'\'', b'>', bytes.get(idx..)?)?;
        let delimiter = bytes[idx];
        idx += 1;
        if delimiter == b'>' {
            return Some(idx);
        }
        idx += memchr::memchr(delimiter, &bytes[idx..])? + 1;
    }
}

/// Check if bytes match an end tag pattern.
pub fn matches_end_tag_start(bytes: &[u8], start: usize, tag: &[u8]) -> bool {
    if start >= bytes.len() || bytes[start] != b'/' {
        return false;
    }
    matches_tag_start(bytes, start + 1, tag)
}

/// ~keep CDATA outside SVG/MathML is an HTML bogus comment, while foreign content owns its body.
pub fn strip_html_cdata(input: &str) -> Cow<'_, str> {
    if !input.contains("<![CDATA[") {
        return Cow::Borrowed(input);
    }
    let bytes = input.as_bytes();
    let mut cursor = 0;
    let mut last = 0;
    let mut foreign_depth = 0usize;
    let mut output = None;
    while let Some(offset) = memchr::memchr(b'<', &bytes[cursor..]) {
        cursor += offset;
        if bytes[cursor..].starts_with(b"<![CDATA[") {
            let end = cdata_end(bytes, cursor, foreign_depth == 0);
            if foreign_depth == 0 {
                let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
                out.push_str(&input[last..cursor]);
                last = end;
            }
            cursor = end;
            continue;
        }
        if let Some(end) =
            super::raw_text::skip_opaque_region(bytes, cursor).or_else(|| skip_cdata_text_element(bytes, cursor))
        {
            cursor = end;
            continue;
        }
        let name_start = cursor + 1 + usize::from(bytes.get(cursor + 1) == Some(&b'/'));
        if !bytes.get(name_start).is_some_and(u8::is_ascii_alphabetic) {
            cursor += 1;
            continue;
        }
        let Some(end) = find_tag_end(bytes, cursor + 1) else {
            break;
        };
        update_cdata_foreign_depth(bytes, cursor, end, &mut foreign_depth);
        cursor = end;
    }
    match output {
        Some(mut out) => {
            out.push_str(&input[last..]);
            Cow::Owned(out)
        }
        None => Cow::Borrowed(input),
    }
}

fn skip_cdata_text_element(bytes: &[u8], cursor: usize) -> Option<usize> {
    for tag in [
        b"textarea".as_slice(),
        b"title",
        b"xmp",
        b"iframe",
        b"noembed",
        b"noframes",
        b"noscript",
    ] {
        if matches_tag_start(bytes, cursor + 1, tag) {
            return text_element_end(bytes, cursor, tag);
        }
    }
    matches_tag_start(bytes, cursor + 1, b"plaintext").then_some(bytes.len())
}

/// The index just past the element that the start tag of `tag` at `cursor` opens, when the
/// content of the element is text: the element ends at the first end tag of its name, or at
/// the end of the input. `None` when the start tag has no end.
fn text_element_end(bytes: &[u8], cursor: usize, tag: &[u8]) -> Option<usize> {
    let open_end = find_tag_end(bytes, cursor + 1 + tag.len())?;
    Some(super::raw_text::find_closing_tag_bytes(bytes, open_end, tag).unwrap_or(bytes.len()))
}

/// The elements whose content is text and reaches the scan for the tags of kept elements as
/// written.
///
/// ~keep `<title>`, `<xmp>` and `<iframe>` hold text too, but the inert-body pass takes their
/// ~keep bodies out of the page before that scan reads it. `<plaintext>` has no end tag.
const WRITTEN_TEXT_ELEMENTS: [&[u8]; 3] = [b"textarea", b"noembed", b"noframes"];

/// If the `<` at `cursor` is the start tag of an element of [`WRITTEN_TEXT_ELEMENTS`] or of a
/// `<plaintext>`, the index just past the element. A `<template>` or a `<noscript>` tag in
/// its content is text and not a tag.
pub(super) fn skip_written_text_element(bytes: &[u8], cursor: usize) -> Option<usize> {
    if matches_tag_start(bytes, cursor + 1, b"plaintext") {
        return Some(bytes.len());
    }
    WRITTEN_TEXT_ELEMENTS
        .iter()
        .find(|name| matches_tag_start(bytes, cursor + 1, name))
        .and_then(|name| text_element_end(bytes, cursor, name))
}

fn update_cdata_foreign_depth(bytes: &[u8], cursor: usize, end: usize, depth: &mut usize) {
    for tag in [b"svg".as_slice(), b"math".as_slice()] {
        if matches_tag_start(bytes, cursor + 1, tag) && !bytes[cursor..end].ends_with(b"/>") {
            *depth += 1;
        } else if matches_end_tag_start(bytes, cursor + 1, tag) {
            *depth = depth.saturating_sub(1);
        }
    }
}

fn cdata_end(bytes: &[u8], cursor: usize, in_html: bool) -> usize {
    if in_html {
        // ~keep HTML bogus comments end at the first `>`; only foreign CDATA uses `]]>`.
        memchr::memchr(b'>', &bytes[cursor + 2..]).map_or(bytes.len(), |offset| cursor + 2 + offset + 1)
    } else {
        super::raw_text::skip_opaque_region(bytes, cursor).unwrap_or(bytes.len())
    }
}