Skip to main content

tabnas_markdown/
block.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Phase 1 of the CommonMark parse: block structure. Port of
4//! `ts/src/block.ts` (canonical) and `go/block.go`; keep the three in
5//! step, function for function. Spec 0.31.2, Appendix A "A parsing
6//! strategy".
7//!
8//! The document is a tree of blocks whose right spine (the document, then
9//! last child, then last child of that, and so on) is *open*: each open
10//! block imposes a continuation condition on the next line. For every line
11//! we
12//!
13//! 1. walk that spine, consuming each block's continuation marker (`>` for
14//!    a block quote, the content indent for a list item, ...) and remember
15//!    the last container that matched;
16//! 2. look for new block starts at the offset that walk reached, closing
17//!    the unmatched tail of the spine as soon as a start actually matches;
18//! 3. add whatever is left of the line to the deepest open block, opening a
19//!    paragraph if there is nowhere else for the text to go.
20//!
21//! Unmatched blocks are closed in step 2/3 rather than in step 1 because a
22//! paragraph line may be a *lazy continuation*: its containers' markers are
23//! missing, but the paragraph carries on regardless (section 5.1 rule 2).
24//!
25//! Positions on a line are tracked twice: `offset`, a BYTE index used to
26//! slice the text we keep (the TypeScript's is a UTF-16 index), and
27//! `column`, the tab-expanded display column used for every indent
28//! decision (section 2.2). Every block delimiter is ASCII and no UTF-8
29//! continuation byte can collide with one, so scanning by byte is exact;
30//! `column` and sourcepos columns still count CHARACTERS, which is what the
31//! spec means, so byte offsets pass through `char_count` on the way to a
32//! column. The two must move together, including the case where a marker
33//! consumes only part of a tab; see `advance_offset` and `add_line`.
34//!
35//! The two regexes in `block.ts` that use lookahead (the code fences) are
36//! hand-coded here, as they are in Go: the `regex` crate has no lookahead.
37//! Fence runs are counted with a loop, never with a regex built from an
38//! input-derived repeat count.
39//!
40//! This file owns everything the block phase sets on a node: type, level,
41//! literal (code_block / html_block), info / is_fenced, list_data
42//! (including the final `tight`), sourcepos, and `string_content`, the
43//! raw, unparsed text of paragraphs and headings that the inline phase
44//! consumes.
45
46use std::collections::HashMap;
47use std::sync::OnceLock;
48
49use regex::Regex;
50
51use crate::common::{js_trim, normalize_reference, unescape_string};
52use crate::inline::parse_definitions;
53use crate::node::{
54    Align, Definition, DefinitionSite, ListData, ListType, MdNode, NodeId, NodeType, SourcePos,
55    TableAlign, Tree,
56};
57use crate::options::{Options, RefDef, RefMap};
58
59/// What the block phase did, in the order it did it, for a driver that
60/// writes blocks as they finish ([`BlockParser::events`]): a container
61/// opened (a block quote, a list, a list item or a table, whose fields at
62/// that point are read when the line's events are), a table row made
63/// (complete, with its cells), a definition read off a paragraph, and a
64/// block closed, after its finalizer ran. A closed paragraph that held
65/// nothing but definitions has been unlinked by then, and has no parent.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum BlockEvent {
68    Open(NodeId),
69    Row(NodeId),
70    Definition(Definition),
71    Close(NodeId),
72}
73
74/// The containers whose opening is an event: the ones a driver writes
75/// open.
76fn opens_event(tag: NodeType) -> bool {
77    matches!(
78        tag,
79        NodeType::BlockQuote | NodeType::List | NodeType::Item | NodeType::Table
80    )
81}
82
83/// Section 4.4: four columns of indentation open an indented code block.
84const CODE_INDENT: usize = 4;
85
86/// One physical line of the source, with section 2.3's NUL replacement.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct LineSegment {
89    /// The line's text, terminator excluded.
90    pub text: String,
91    /// The byte offset past the terminator.
92    pub next: usize,
93}
94
95/// Cut the next physical line out of `src` at `pos`: up to (not including)
96/// the next `\n`, `\r` or `\r\n`, with `next` past the terminator. `None`
97/// at the end of the source, which is why a final line ending does not
98/// introduce a trailing blank line. Insecure NULs are replaced here, before
99/// anything else looks at the text.
100pub fn segment_next_line(src: &str, pos: usize) -> Option<LineSegment> {
101    if pos >= src.len() {
102        return None;
103    }
104    let bytes = src.as_bytes();
105    let mut i = pos;
106    while i < bytes.len() && bytes[i] != b'\n' && bytes[i] != b'\r' {
107        i += 1;
108    }
109    let mut next = i;
110    if next < bytes.len() {
111        if bytes[next] == b'\r' && next + 1 < bytes.len() && bytes[next + 1] == b'\n' {
112            next += 2;
113        } else {
114            next += 1;
115        }
116    }
117    let text = &src[pos..i];
118    let text = if text.contains('\0') {
119        text.replace('\0', "\u{FFFD}")
120    } else {
121        text.to_string()
122    };
123    Some(LineSegment { text, next })
124}
125
126/// Section 4.1: 3+ matching `*`, `_` or `-`, each optionally followed by
127/// spaces or tabs, and nothing else.
128pub fn is_thematic_break(s: &str) -> bool {
129    let bytes = s.as_bytes();
130    let Some(&c) = bytes.first() else {
131        return false;
132    };
133    if c != b'*' && c != b'_' && c != b'-' {
134        return false;
135    }
136    let mut count = 0;
137    for &b in bytes {
138        if b == c {
139            count += 1;
140        } else if b != b' ' && b != b'\t' {
141            return false;
142        }
143    }
144    count >= 3
145}
146
147/// Step 2's fast reject: every block start begins with one of these
148/// characters.
149pub fn maybe_special(ln: &str, pos: usize) -> bool {
150    match ln.as_bytes().get(pos) {
151        Some(c) => {
152            matches!(
153                c,
154                b'#' | b'`' | b'~' | b'*' | b'+' | b'_' | b'=' | b'<' | b'>' | b'-'
155            ) || c.is_ascii_digit()
156        }
157        None => false,
158    }
159}
160
161/// The same fast reject with `|` and `:` added, used when GFM is on: a GFM
162/// table's delimiter row may begin with either (`| --- |`, `:-: | ---:`),
163/// and neither is a CommonMark block start.
164///
165/// Kept separate so that a GFM-off parse takes exactly the path it always
166/// did: same characters rejected, same lines never offered to the block
167/// starts at all.
168pub fn maybe_special_gfm(ln: &str, pos: usize) -> bool {
169    match ln.as_bytes().get(pos) {
170        Some(c) => {
171            matches!(
172                c,
173                b'#' | b'`' | b'~' | b'*' | b'+' | b'_' | b'=' | b'<' | b'>' | b'-' | b':' | b'|'
174            ) || c.is_ascii_digit()
175        }
176        None => false,
177    }
178}
179
180/// Nothing but spaces, tabs, form feeds, vertical tabs and line endings.
181/// All members of the set are ASCII, so a byte scan classifies UTF-8
182/// correctly: a continuation byte counts as non-space, as the character it
183/// belongs to would.
184pub fn is_blank(s: &str) -> bool {
185    s.bytes()
186        .all(|b| matches!(b, b' ' | b'\t' | b'\x0c' | b'\x0b' | b'\r' | b'\n'))
187}
188
189/// Section 5.2: a bullet list marker is one of `*`, `+`, `-`.
190pub fn is_bullet_list_marker(s: &str) -> bool {
191    matches!(s.as_bytes().first(), Some(b'*' | b'+' | b'-'))
192}
193
194/// Section 5.2: an ordered list marker is 1 to 9 digits and `.` or `)`.
195/// Returns the digit count and the delimiter. Ten or more digits do not
196/// match.
197pub fn match_ordered_list_marker(s: &str) -> Option<(usize, u8)> {
198    let bytes = s.as_bytes();
199    let mut i = 0;
200    while i < bytes.len() && bytes[i].is_ascii_digit() {
201        i += 1;
202    }
203    if !(1..=9).contains(&i) || i >= bytes.len() {
204        return None;
205    }
206    if bytes[i] == b'.' || bytes[i] == b')' {
207        return Some((i, bytes[i]));
208    }
209    None
210}
211
212/// Section 4.2: 1 to 6 `#` followed by spaces or tabs, or the end of the
213/// line. Returns the level and the whole marker's length. Seven or more `#`
214/// do not match.
215pub fn match_atx_heading_marker(s: &str) -> Option<(usize, usize)> {
216    let bytes = s.as_bytes();
217    let mut n = 0;
218    while n < bytes.len() && bytes[n] == b'#' {
219        n += 1;
220    }
221    if !(1..=6).contains(&n) {
222        return None;
223    }
224    if n == bytes.len() {
225        return Some((n, n));
226    }
227    if bytes[n] != b' ' && bytes[n] != b'\t' {
228        return None;
229    }
230    let mut i = n;
231    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
232        i += 1;
233    }
234    Some((n, i))
235}
236
237/// Section 4.2: drop an optional closing sequence of `#`s, preceded by
238/// spaces or tabs; a line of nothing but `#`s (and spaces) has empty
239/// content. Hand-coded from the two regexes the TypeScript uses.
240pub fn strip_atx_closing(content: &str) -> &str {
241    let bytes = content.as_bytes();
242    let space = |b: u8| b == b' ' || b == b'\t';
243
244    // /^[ \t]*#+[ \t]*$/ : the whole line is one closing sequence.
245    let mut i = 0;
246    while i < bytes.len() && space(bytes[i]) {
247        i += 1;
248    }
249    let hashes_start = i;
250    while i < bytes.len() && bytes[i] == b'#' {
251        i += 1;
252    }
253    let hashes = i - hashes_start;
254    while i < bytes.len() && space(bytes[i]) {
255        i += 1;
256    }
257    if hashes > 0 && i == bytes.len() {
258        return "";
259    }
260
261    // /[ \t]+#+[ \t]*$/ : a trailing closing sequence after content.
262    let mut end = bytes.len();
263    while end > 0 && space(bytes[end - 1]) {
264        end -= 1;
265    }
266    let hashes_end = end;
267    while end > 0 && bytes[end - 1] == b'#' {
268        end -= 1;
269    }
270    if end == hashes_end {
271        return content;
272    }
273    let spaces_end = end;
274    while end > 0 && space(bytes[end - 1]) {
275        end -= 1;
276    }
277    if end == spaces_end {
278        return content;
279    }
280    &content[..end]
281}
282
283/// Section 4.5: the opening code fence at the start of `s`, as its length,
284/// or 0. A backtick fence is only a fence if the rest of the line (the info
285/// string) holds no backtick; a tilde fence has no such restriction.
286pub fn match_code_fence(s: &str) -> usize {
287    let bytes = s.as_bytes();
288    let Some(&c) = bytes.first() else {
289        return 0;
290    };
291    if c != b'`' && c != b'~' {
292        return 0;
293    }
294    let mut n = 0;
295    while n < bytes.len() && bytes[n] == c {
296        n += 1;
297    }
298    if n < 3 {
299        return 0;
300    }
301    if c == b'`' && bytes[n..].contains(&b'`') {
302        return 0;
303    }
304    n
305}
306
307/// Section 4.5: the closing-fence candidate at the start of `s`, as its
308/// length, or 0: the maximal run must be followed by spaces or tabs only.
309/// The caller still checks the fence character and length against the open
310/// block.
311pub fn match_closing_code_fence(s: &str) -> usize {
312    let bytes = s.as_bytes();
313    let Some(&c) = bytes.first() else {
314        return 0;
315    };
316    if c != b'`' && c != b'~' {
317        return 0;
318    }
319    let mut n = 0;
320    while n < bytes.len() && bytes[n] == c {
321        n += 1;
322    }
323    if n < 3 {
324        return 0;
325    }
326    if bytes[n..].iter().any(|&b| b != b' ' && b != b'\t') {
327        return 0;
328    }
329    n
330}
331
332/// Section 4.3: a run of `=` or `-` with only spaces or tabs after it.
333/// Returns the run's character, or `None` when the line is not an
334/// underline.
335pub fn match_setext_heading_line(s: &str) -> Option<u8> {
336    let bytes = s.as_bytes();
337    let &c = bytes.first()?;
338    if c != b'=' && c != b'-' {
339        return None;
340    }
341    let mut i = 0;
342    while i < bytes.len() && bytes[i] == c {
343        i += 1;
344    }
345    if bytes[i..].iter().any(|&b| b != b' ' && b != b'\t') {
346        return None;
347    }
348    Some(c)
349}
350
351// --- HTML blocks (section 4.6) ---------------------------------------------
352//
353// Seven kinds, each with its own start and end condition. Types 1 to 5 end
354// on a line *containing* their closing string (checked in
355// `incorporate_line` after the line is added); types 6 and 7 end at a blank
356// line (checked in the html_block continuation condition). Type 7 alone may
357// not interrupt a paragraph.
358
359/// Tag-shape fragments shared by HTML block type 7 (section 6.6 raw HTML).
360/// The block forms allow only spaces and tabs where the inline forms allow
361/// any whitespace.
362const BLOCK_TAG_NAME: &str = "[A-Za-z][A-Za-z0-9-]*";
363const BLOCK_ATTRIBUTE_NAME: &str = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
364const BLOCK_UNQUOTED_VALUE: &str = "[^\"'=<>`\\x00-\\x20]+";
365const BLOCK_SINGLE_QUOTED_VALUE: &str = "'[^']*'";
366const BLOCK_DOUBLE_QUOTED_VALUE: &str = "\"[^\"]*\"";
367
368/// The type 6 tag list, verbatim from section 4.6 (0.31.2 has `search`,
369/// not `source`).
370const BLOCK_TAGS: &str = "address|article|aside|base|basefont|blockquote|body|caption|\
371center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|\
372figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|\
373li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|\
374section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
375
376/// The type 1 tag list: the four whose content is raw text.
377const BLOCK_RAW_TEXT_TAGS: &str = "script|pre|textarea|style";
378
379/// Spell a lowercase pattern in both cases, mapping each ASCII letter to a
380/// two-element class and passing everything else through (so `h[1-6]`
381/// becomes `[hH][1-6]` and `|` stays an alternation).
382///
383/// This is what the TypeScript's `i` flag means and what a Unicode-aware
384/// `(?i)` does not: the `regex` crate folds case over all of Unicode, so
385/// `(?i)script` also matches `ſcript`, and `(?i)[A-Za-z]` also matches
386/// U+017F LATIN SMALL LETTER LONG S and U+212A KELVIN SIGN, where
387/// JavaScript's non-unicode `i` deliberately never folds a non-ASCII code
388/// point onto an ASCII one.
389fn ascii_fold_pattern(s: &str) -> String {
390    let mut out = String::with_capacity(4 * s.len());
391    for c in s.chars() {
392        if c.is_ascii_lowercase() {
393            out.push('[');
394            out.push(c);
395            out.push(c.to_ascii_uppercase());
396            out.push(']');
397        } else if c.is_ascii_uppercase() {
398            out.push('[');
399            out.push(c.to_ascii_lowercase());
400            out.push(c);
401            out.push(']');
402        } else {
403            out.push(c);
404        }
405    }
406    out
407}
408
409/// Indexed by HTML block type 1 to 7; slot 0 is unused.
410fn re_html_block_open() -> &'static [Regex; 8] {
411    static RE: OnceLock<[Regex; 8]> = OnceLock::new();
412    RE.get_or_init(|| {
413        let attribute_value = format!(
414            "(?:{BLOCK_UNQUOTED_VALUE}|{BLOCK_SINGLE_QUOTED_VALUE}|{BLOCK_DOUBLE_QUOTED_VALUE})"
415        );
416        let attribute_value_spec = format!("(?:[ \\t]*=[ \\t]*{attribute_value})");
417        let attribute = format!("(?:[ \\t]+{BLOCK_ATTRIBUTE_NAME}{attribute_value_spec}?)");
418        let open_tag = format!("<{BLOCK_TAG_NAME}{attribute}*[ \\t]*/?>");
419        let close_tag = format!("</{BLOCK_TAG_NAME}[ \\t]*>");
420        let compile = |p: String| Regex::new(&p).expect("the HTML block patterns compile");
421        [
422            compile("^$".to_string()),
423            compile(format!(
424                "^<(?:{})(?:[ \\t]|>|$)",
425                ascii_fold_pattern(BLOCK_RAW_TEXT_TAGS)
426            )),
427            compile("^<!--".to_string()),
428            compile("^<[?]".to_string()),
429            compile("^<![A-Za-z]".to_string()),
430            compile("^<!\\[CDATA\\[".to_string()),
431            compile(format!(
432                "^</?(?:{})(?:[ \\t]|/?>|$)",
433                ascii_fold_pattern(BLOCK_TAGS)
434            )),
435            compile(format!("^(?:{open_tag}|{close_tag})[ \\t]*$")),
436        ]
437    })
438}
439
440fn re_html_block_close_raw_text() -> &'static Regex {
441    static RE: OnceLock<Regex> = OnceLock::new();
442    RE.get_or_init(|| {
443        Regex::new(&format!(
444            "</(?:{})>",
445            ascii_fold_pattern(BLOCK_RAW_TEXT_TAGS)
446        ))
447        .expect("the raw-text close pattern compiles")
448    })
449}
450
451/// Section 4.6: which of the seven HTML block kinds `s` opens, or 0. The
452/// type-7 paragraph-interrupt restriction is contextual and stays with the
453/// caller.
454pub fn html_block_open_kind(s: &str) -> u8 {
455    let patterns = re_html_block_open();
456    for kind in 1..=7u8 {
457        if patterns[kind as usize].is_match(s) {
458            return kind;
459        }
460    }
461    0
462}
463
464/// Section 4.6: does `s` contain the closing condition for HTML block
465/// `kind` (types 1 to 5; 6 and 7 end at a blank line instead)?
466pub fn html_block_closes(s: &str, kind: u8) -> bool {
467    match kind {
468        1 => re_html_block_close_raw_text().is_match(s),
469        2 => s.contains("-->"),
470        3 => s.contains("?>"),
471        4 => s.contains('>'),
472        5 => s.contains("]]>"),
473        _ => false,
474    }
475}
476
477// --- small lexical helpers --------------------------------------------------
478
479/// The byte at `pos`, or `None` past the end of the line. Every caller
480/// compares against an ASCII constant, which no UTF-8 continuation byte can
481/// equal, so a byte here is as good as the TypeScript's code unit.
482fn peek(ln: &str, pos: usize) -> Option<u8> {
483    ln.as_bytes().get(pos).copied()
484}
485
486fn is_space_or_tab(c: Option<u8>) -> bool {
487    matches!(c, Some(b' ') | Some(b'\t'))
488}
489
490/// The number of characters in `s`. `offset` is a byte index in this port;
491/// sourcepos columns count characters, so the conversion happens here.
492pub fn char_count(s: &str) -> usize {
493    s.chars().count()
494}
495
496/// The index at which the trailing `(\n *)+` of `b` begins, or `b.len()`
497/// when there is none: the offset the JavaScript `.replace(/(\n *)+$/, ..)`
498/// would rewrite from.
499fn trailing_blank_run_start(b: &[u8]) -> usize {
500    let mut end = b.len();
501    loop {
502        let mut j = end;
503        while j > 0 && b[j - 1] == b' ' {
504            j -= 1;
505        }
506        if j > 0 && b[j - 1] == b'\n' {
507            end = j - 1;
508            continue;
509        }
510        return end;
511    }
512}
513
514// --- GFM tables (extension) -------------------------------------------------
515//
516// Everything the extension needs from a line is here: how a row splits into
517// cells, and whether a line is a delimiter row. Both are pure functions of
518// one line of text, which is what lets the block start below stay a few
519// lines long.
520//
521// Byte scanning throughout, as everywhere else in this file: every
522// character these functions test for (space, tab, `|`, `\`, `-`, `:`) is
523// ASCII, and no UTF-8 continuation byte can equal one. The cell text itself
524// is only ever *sliced* at those positions, never decoded character by
525// character, so a multi-byte character inside a cell is carried through
526// whole.
527
528/// The set `cmark_isspace` trims from a table cell: ASCII whitespace only.
529fn is_ascii_space(c: u8) -> bool {
530    c == 32 || (9..=13).contains(&c)
531}
532
533fn trim_ascii_space(s: &str) -> &str {
534    let bytes = s.as_bytes();
535    let mut start = 0;
536    let mut end = bytes.len();
537    while start < end && is_ascii_space(bytes[start]) {
538        start += 1;
539    }
540    while end > start && is_ascii_space(bytes[end - 1]) {
541        end -= 1;
542    }
543    &s[start..end]
544}
545
546/// Split one row of a table into its cell texts.
547///
548/// Cells are separated by *unescaped* pipes; a leading and a trailing pipe
549/// are both optional and may differ from row to row, so they are stripped
550/// before the split rather than producing empty cells at the ends. A
551/// trailing pipe is only a delimiter if it is itself unescaped, which is
552/// why the backslash run before it is counted.
553///
554/// `\|` is resolved to a literal `|` *here*, as the extension requires
555/// ("include a pipe in a cell's content by escaping it, including inside
556/// other inline spans"). Doing it at split time is the whole point: the
557/// inline phase never sees the backslash, so a code span in the cell yields
558/// a real pipe, which no amount of unescaping *after* inline parsing could
559/// produce. Every other backslash escape is left exactly as written for the
560/// inline phase to handle in the usual way, so no cell text is unescaped
561/// twice.
562///
563/// Scanning skips the byte after any backslash, so `\\` cannot shield the
564/// pipe that follows it: `a\\|b` is two cells, the first holding `a\\`.
565///
566/// A row of nothing but whitespace has no cells at all, which is how a
567/// header candidate that is really empty fails the cell-count test instead
568/// of matching a one-column delimiter row.
569pub fn split_table_row(line: &str) -> Vec<String> {
570    let bytes = line.as_bytes();
571    let mut start = 0;
572    let mut end = bytes.len();
573    while start < end && is_ascii_space(bytes[start]) {
574        start += 1;
575    }
576    while end > start && is_ascii_space(bytes[end - 1]) {
577        end -= 1;
578    }
579    if start == end {
580        return Vec::new();
581    }
582
583    // Optional leading pipe.
584    if bytes[start] == b'|' {
585        start += 1;
586    }
587
588    // Optional trailing pipe, but an escaped one is content, not a delimiter.
589    if start < end && bytes[end - 1] == b'|' {
590        let mut bs = end as isize - 2;
591        while bs >= start as isize && bytes[bs as usize] == b'\\' {
592            bs -= 1;
593        }
594        // An even-length backslash run leaves the pipe unescaped.
595        if (end as isize - 2 - bs) % 2 == 0 {
596            end -= 1;
597        }
598    }
599
600    let mut cells = Vec::with_capacity(4);
601    // `cur` holds the parts of the current cell that have already been
602    // rewritten; `seg` is the start of the run since then, so the common
603    // case (no escapes) costs one slice per cell rather than one per byte.
604    let mut cur = String::new();
605    let mut seg = start;
606    let mut i = start;
607
608    while i < end {
609        let c = bytes[i];
610        if c == b'\\' && i + 1 < end {
611            if bytes[i + 1] == b'|' {
612                cur.push_str(&line[seg..i]);
613                cur.push('|');
614                i += 2;
615                seg = i;
616            } else {
617                i += 2;
618            }
619            continue;
620        }
621        if c == b'|' {
622            cur.push_str(&line[seg..i]);
623            cells.push(trim_ascii_space(&cur).to_string());
624            cur.clear();
625            i += 1;
626            seg = i;
627            continue;
628        }
629        i += 1;
630    }
631    cur.push_str(&line[seg..end]);
632    cells.push(trim_ascii_space(&cur).to_string());
633
634    cells
635}
636
637/// A delimiter cell is hyphens with an optional leading and/or trailing
638/// colon, and nothing else. One `+`, one space in the middle, one stray
639/// character and the line is not a delimiter row. Hand-coded from
640/// `/^(:?)-+(:?)$/`.
641fn delimiter_cell_align(cell: &str) -> Option<TableAlign> {
642    let bytes = cell.as_bytes();
643    let mut i = 0;
644    let left = bytes.first() == Some(&b':');
645    if left {
646        i += 1;
647    }
648    let hyphens_start = i;
649    while i < bytes.len() && bytes[i] == b'-' {
650        i += 1;
651    }
652    if i == hyphens_start {
653        return None;
654    }
655    let right = i < bytes.len() && bytes[i] == b':';
656    if right {
657        i += 1;
658    }
659    if i != bytes.len() {
660        return None;
661    }
662    Some(match (left, right) {
663        (true, true) => Some(Align::Center),
664        (true, false) => Some(Align::Left),
665        (false, true) => Some(Align::Right),
666        (false, false) => None,
667    })
668}
669
670/// Read a line as a table's delimiter row, returning one alignment per
671/// column, or `None` if it is not one.
672pub fn parse_delimiter_row(line: &str) -> Option<Vec<TableAlign>> {
673    let cells = split_table_row(line);
674    if cells.is_empty() {
675        return None;
676    }
677    let mut align = Vec::with_capacity(cells.len());
678    for cell in &cells {
679        align.push(delimiter_cell_align(cell)?);
680    }
681    Some(align)
682}
683
684/// Cap on the empty cells inserted to pad short body rows, across a whole
685/// document: cmark-gfm's `MAX_AUTOCOMPLETED_CELLS`, and for the same reason.
686///
687/// Padding is the one place where a table's node count is not bounded by
688/// the size of its source: a 10000-column header followed by 10000 one-cell
689/// rows is 60 KB of input asking for 10^8 cells. Every other part of the
690/// extension is linear in the input, so this single budget is what keeps
691/// the whole of it so. Reaching it needs input that is already
692/// pathological; ordinary tables are nowhere near.
693const MAX_AUTOCOMPLETED_CELLS: usize = 0x80000;
694
695/// The most container blocks (block quotes, lists and list items, each
696/// counted) that may be open at once. A block quote marker or list marker
697/// that would open a deeper one is not a block start, so it is paragraph
698/// text, which is what markdown-it's `maxNesting` does at its limit.
699///
700/// This bound exists for the caller's stack, not the parser's: every
701/// phase here is iterative, but the AST is a `tabnas::Value`, whose
702/// destructor and `to_json` recurse once per nesting level. Unbounded,
703/// a few thousand nested block quotes made an ordinary caller's drop
704/// abort the process. Measured in a debug build on a 2 MiB thread: drop
705/// survives about 5,300 nested levels and `to_json` about 1,250, and
706/// each container is two levels (an object and its children array), so
707/// 100 containers leaves the deepest document well inside both. The
708/// canonical TypeScript has no such limit; `DIVERGENCE.md` records it,
709/// and `tests/robust_test.rs` pins the boundary. The inline phase bounds
710/// its own wrappers the same way: `inline::MAX_INLINE_NESTING`.
711pub const MAX_CONTAINER_NESTING: usize = 100;
712
713/// The blocks `MAX_CONTAINER_NESTING` counts.
714fn is_container(t: NodeType) -> bool {
715    matches!(t, NodeType::BlockQuote | NodeType::List | NodeType::Item)
716}
717
718/// Section 5.3: two markers make the same list only if type, bullet and
719/// delimiter agree.
720fn lists_match(list_data: &ListData, item_data: &ListData) -> bool {
721    list_data.list_type == item_data.list_type
722        && list_data.delimiter == item_data.delimiter
723        && list_data.bullet_char == item_data.bullet_char
724}
725
726/// `continue` result: matched, not matched, or line fully consumed (fenced
727/// code close), stop processing this line entirely.
728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729enum ContinueResult {
730    Matched,
731    NotMatched,
732    LineDone,
733}
734
735/// A block start's result: no match, a container started, or a leaf
736/// started (stop looking).
737#[derive(Debug, Clone, Copy, PartialEq, Eq)]
738enum StartResult {
739    None,
740    Container,
741    Leaf,
742}
743
744/// The per-type block behaviour the TypeScript keeps in `BLOCK_HANDLERS`:
745/// which children a block may hold, whether it accumulates raw text, and
746/// whether its lines are literal.
747fn can_contain(t: NodeType, child: NodeType) -> bool {
748    match t {
749        NodeType::Document | NodeType::BlockQuote | NodeType::Item => child != NodeType::Item,
750        NodeType::List => child == NodeType::Item,
751        NodeType::Table => child == NodeType::TableRow,
752        NodeType::TableRow => child == NodeType::TableCell,
753        _ => false,
754    }
755}
756
757/// Leaves that take lines: code blocks, HTML blocks, paragraphs, tables.
758fn accepts_lines(t: NodeType) -> bool {
759    matches!(
760        t,
761        NodeType::CodeBlock | NodeType::HtmlBlock | NodeType::Paragraph | NodeType::Table
762    )
763}
764
765/// Lines belonging to this block are literal text, so Appendix A step 2
766/// does not look for block starts while it is the last matched container.
767///
768/// True for exactly the two blocks the spec names: code blocks and HTML
769/// blocks. Paragraphs and GFM tables also accept lines, but a block start
770/// may still interrupt either: that is how `> bar` ends a table, and how
771/// `# h` ends a paragraph.
772fn verbatim(t: NodeType) -> bool {
773    matches!(t, NodeType::CodeBlock | NodeType::HtmlBlock)
774}
775
776/// The block-phase parser: the open spine, the current line, and the
777/// tree being built.
778pub struct BlockParser {
779    pub options: Options,
780    pub refmap: RefMap,
781
782    pub tree: Tree,
783    doc: NodeId,
784    /// The deepest open block; `None` only once the document itself is
785    /// finalized.
786    tip: Option<NodeId>,
787    /// The tip as it was before the current line was walked.
788    oldtip: NodeId,
789    last_matched_container: NodeId,
790    /// False while some open block failed its continuation condition.
791    all_closed: bool,
792
793    current_line: String,
794    line_number: usize,
795    last_line_length: usize,
796
797    /// The length of the line before the one `last_line_length` measures.
798    ///
799    /// `finalize` dates a block's end from `last_line_length`, which is
800    /// right for every block that ends on the line before the current one.
801    /// A GFM table splits its paragraph *two* lines back (the header row is
802    /// the previous line and stays with the table, so the paragraph left
803    /// behind ends on the line before that) and needs this one instead.
804    prev_line_length: usize,
805
806    /// A byte index into `current_line`.
807    offset: usize,
808    /// The tab-expanded display column matching `offset` (section 2.2),
809    /// counted in characters.
810    column: usize,
811    /// True when `offset` sits inside a tab whose columns were partly
812    /// consumed.
813    partially_consumed_tab: bool,
814
815    /// Memoize the last byte offset in `current_line` whose character count
816    /// is known, so sourcepos columns cost amortized O(1) rather than a
817    /// fresh count from the start of the line. Both reset per line. See
818    /// `source_column`.
819    col_anchor_offset: usize,
820    col_anchor_chars: usize,
821
822    next_nonspace: usize,
823    next_nonspace_column: usize,
824    /// Columns between `column` and the next non-space character.
825    indent: usize,
826    indented: bool,
827    blank: bool,
828
829    /// Empty cells inserted so far to pad short table rows. See
830    /// `MAX_AUTOCOMPLETED_CELLS`.
831    autocompleted_cells: usize,
832
833    /// The text `add_line` last appended, the column it started in, and the
834    /// block it went to.
835    ///
836    /// `try_open_table` needs the *last line* of an open paragraph, and
837    /// reading it back out of `string_content` is not affordable in the
838    /// canonical runtime: that content is built by repeated `+=`, so every
839    /// index into it flattens a fresh rope. The field is carried across
840    /// anyway: it is what makes the three runtimes the same function, and
841    /// scanning back for the previous newline is its own O(n) per line.
842    ///
843    /// The node is recorded alongside it because "the previous line went to
844    /// this very paragraph" is the extension's own rule: a header row is by
845    /// definition the line immediately above the delimiter row. If some
846    /// other block took that line, there is no header row.
847    ///
848    /// The column is what a table's sourcepos starts at: a table opens on
849    /// its header row, which is a line already consumed by the time the
850    /// delimiter row identifies it, so its column has to have been recorded
851    /// when it went past.
852    last_added_line: String,
853    last_added_column: usize,
854    last_added_to: Option<NodeId>,
855
856    /// Step 2's fast reject, widened for a table's delimiter row when GFM is
857    /// on.
858    gfm_special: bool,
859
860    /// `MdNode` has no field for the HTML block type, and the tree contract
861    /// is not ours to change, so open HTML blocks carry it here.
862    html_block_types: HashMap<NodeId, u8>,
863
864    /// The events of the lines incorporated since the driver last took
865    /// them, or `None`, the default, when no driver asks: the batch parse
866    /// records nothing.
867    pub events: Option<Vec<BlockEvent>>,
868
869    /// The table whose delimiter row is the next line `add_line` writes:
870    /// that row opened the table and holds no data, so it makes no row.
871    table_delimiter_row: Option<NodeId>,
872
873    /// Blocks the block phase took out of the tree with no `Close` of their
874    /// own, while a driver asks for events: a paragraph a table's header
875    /// row or a setext underline replaced. A driver that keeps no tree
876    /// gives them back with [`BlockParser::release_block`].
877    pub dropped: Vec<NodeId>,
878}
879
880impl BlockParser {
881    /// Note a block taken out of the tree with no `Close` of its own, for a
882    /// driver that asked for events (see [`BlockParser::dropped`]).
883    fn note_dropped(&mut self, block: NodeId) {
884        if self.events.is_some() {
885            self.dropped.push(block);
886        }
887    }
888
889    /// Give back the arena slots of `block` and everything below it, for a
890    /// driver that writes blocks as they finish and keeps no tree: a block
891    /// at the top of the document once its `Close` is written, a block the
892    /// phase took out of the tree. Nothing reads such a block again: the
893    /// phase's continuation and laziness rules read only the open blocks
894    /// on the spine, and the blank-line flags and a list's looseness are
895    /// settled before its `Close`. What the phase still holds of it is let
896    /// go too, so that a slot taken by a new block is never mistaken for it
897    /// (tabnas/markdown#100).
898    pub fn release_block(&mut self, block: NodeId) {
899        // An open block on the spine is not done; a dropped one may still
900        // say open, as nothing finalized it, but nothing links to it.
901        let node = self.tree.get(block);
902        if block == self.doc || self.tip == Some(block) || (node.open && node.parent.is_some()) {
903            return;
904        }
905        for id in self.tree.free_subtree(block) {
906            if self.last_added_to == Some(id) {
907                self.last_added_to = None;
908            }
909            if self.table_delimiter_row == Some(id) {
910                self.table_delimiter_row = None;
911            }
912            self.html_block_types.remove(&id);
913        }
914    }
915
916    /// Whether `block` sits at the top of the document.
917    pub fn is_top_level(&self, block: NodeId) -> bool {
918        self.tree.get(block).parent == Some(self.doc)
919    }
920
921    pub fn new(options: Options) -> Self {
922        let mut tree = Tree::new(NodeType::Document);
923        let doc = tree.root();
924        tree.get_mut(doc).sourcepos = [[1, 1], [0, 0]];
925        BlockParser {
926            options,
927            refmap: RefMap::new(),
928            tree,
929            doc,
930            tip: Some(doc),
931            oldtip: doc,
932            last_matched_container: doc,
933            all_closed: true,
934            current_line: String::new(),
935            line_number: 0,
936            last_line_length: 0,
937            prev_line_length: 0,
938            offset: 0,
939            column: 0,
940            partially_consumed_tab: false,
941            col_anchor_offset: 0,
942            col_anchor_chars: 0,
943            next_nonspace: 0,
944            next_nonspace_column: 0,
945            indent: 0,
946            indented: false,
947            blank: false,
948            autocompleted_cells: 0,
949            last_added_line: String::new(),
950            last_added_column: 1,
951            last_added_to: None,
952            gfm_special: options.gfm,
953            html_block_types: HashMap::new(),
954            events: None,
955            table_delimiter_row: None,
956            dropped: Vec::new(),
957        }
958    }
959
960    /// The deepest open block. Only meaningful while a line is being
961    /// processed. The TypeScript throws when the tip is null; a missing tip
962    /// means the document itself has been closed, which cannot happen
963    /// mid-line, and this port must not panic on any input, so the document
964    /// stands in.
965    fn open_tip(&self) -> NodeId {
966        self.tip.unwrap_or(self.doc)
967    }
968
969    fn html_block_type(&self, block: NodeId) -> u8 {
970        self.html_block_types.get(&block).copied().unwrap_or(0)
971    }
972
973    fn set_html_block_type(&mut self, block: NodeId, kind: u8) {
974        self.html_block_types.insert(block, kind);
975    }
976
977    fn node_type(&self, id: NodeId) -> NodeType {
978        self.tree.get(id).node_type
979    }
980
981    /// Advance `count` characters (`columns` false) or `count` columns
982    /// (`columns` true), expanding tabs to the next 4-column tab stop
983    /// (section 2.2). A tab whose columns are only partly consumed leaves
984    /// `offset` on the tab itself and sets `partially_consumed_tab`, so
985    /// `add_line` can re-emit the remainder as spaces.
986    fn advance_offset(&mut self, mut count: usize, columns: bool) {
987        let bytes = self.current_line.as_bytes();
988        while count > 0 && self.offset < bytes.len() {
989            if bytes[self.offset] == b'\t' {
990                let chars_to_tab = 4 - (self.column % 4);
991                if columns {
992                    self.partially_consumed_tab = chars_to_tab > count;
993                    let chars_to_advance = chars_to_tab.min(count);
994                    self.column += chars_to_advance;
995                    if !self.partially_consumed_tab {
996                        self.offset += 1;
997                    }
998                    count -= chars_to_advance;
999                } else {
1000                    self.partially_consumed_tab = false;
1001                    self.column += chars_to_tab;
1002                    self.offset += 1;
1003                    count -= 1;
1004                }
1005            } else {
1006                self.partially_consumed_tab = false;
1007                // One character, not one byte: offset is a byte index but
1008                // column counts characters. Block markers are all ASCII, so
1009                // the two only part company on the advance-to-end-of-line
1010                // calls.
1011                let size = self.current_line[self.offset..]
1012                    .chars()
1013                    .next()
1014                    .map_or(1, char::len_utf8);
1015                self.offset += size;
1016                self.column += 1;
1017                count -= 1;
1018            }
1019        }
1020    }
1021
1022    fn advance_next_nonspace(&mut self) {
1023        self.offset = self.next_nonspace;
1024        self.column = self.next_nonspace_column;
1025        self.partially_consumed_tab = false;
1026    }
1027
1028    /// Locate the next non-space character and the indent leading up to
1029    /// it.
1030    fn find_next_nonspace(&mut self) {
1031        let bytes = self.current_line.as_bytes();
1032        let mut i = self.offset;
1033        let mut cols = self.column;
1034
1035        while i < bytes.len() {
1036            if bytes[i] == b' ' {
1037                i += 1;
1038                cols += 1;
1039            } else if bytes[i] == b'\t' {
1040                i += 1;
1041                cols += 4 - (cols % 4);
1042            } else {
1043                break;
1044            }
1045        }
1046
1047        self.blank = i >= bytes.len() || bytes[i] == b'\n' || bytes[i] == b'\r';
1048        self.next_nonspace = i;
1049        self.next_nonspace_column = cols;
1050        self.indent = self.next_nonspace_column - self.column;
1051        self.indented = self.indent >= CODE_INDENT;
1052    }
1053
1054    /// The number of characters of `current_line` before byte `offset`:
1055    /// what a sourcepos column needs.
1056    ///
1057    /// Counted incrementally from the last offset already measured.
1058    /// `add_child` runs once per container opened, so counting from the
1059    /// start of the line every time would make a line of n nested
1060    /// containers (`> - > - ...`) cost O(n^2); untrusted input picks n.
1061    /// Offsets advance monotonically as a line is consumed, making this
1062    /// amortized O(1); a smaller offset than the anchor is still correct,
1063    /// just recounted from the start.
1064    fn source_column(&mut self, offset: usize) -> usize {
1065        if offset < self.col_anchor_offset {
1066            self.col_anchor_offset = 0;
1067            self.col_anchor_chars = 0;
1068        }
1069        self.col_anchor_chars += char_count(&self.current_line[self.col_anchor_offset..offset]);
1070        self.col_anchor_offset = offset;
1071        self.col_anchor_chars
1072    }
1073
1074    /// Add the rest of the current line to the tip's raw content.
1075    fn add_line(&mut self) {
1076        let tip = self.open_tip();
1077        // Taken before the tab fixup below moves `offset`, so a line's
1078        // recorded column is the one `add_child` would report for that
1079        // same position.
1080        let column = self.source_column(self.offset) + 1; // offset 0 is column 1
1081        let text = if self.partially_consumed_tab {
1082            self.offset += 1; // step over the tab
1083            let chars_to_tab = 4 - (self.column % 4);
1084            let mut text = " ".repeat(chars_to_tab);
1085            text.push_str(&self.current_line[self.offset..]);
1086            text
1087        } else {
1088            self.current_line[self.offset..].to_string()
1089        };
1090        if self.node_type(tip) == NodeType::Table {
1091            // A table's line is a row the moment it arrives, but for the
1092            // delimiter row that opened it.
1093            if self.table_delimiter_row == Some(tip) {
1094                self.table_delimiter_row = None;
1095            } else {
1096                let cells = split_table_row(&text);
1097                self.add_table_row(tip, &cells, false, self.line_number, char_count(&text));
1098            }
1099        } else {
1100            let node = self.tree.get_mut(tip);
1101            node.string_content.push_str(&text);
1102            node.string_content.push('\n');
1103        }
1104        self.last_added_line = text;
1105        self.last_added_column = column;
1106        self.last_added_to = Some(tip);
1107    }
1108
1109    /// How many container blocks the spine holds from the document down
1110    /// to `id`, `id` included.
1111    fn container_depth(&self, id: NodeId) -> usize {
1112        let mut depth = 0;
1113        let mut cur = Some(id);
1114        while let Some(n) = cur {
1115            if is_container(self.node_type(n)) {
1116                depth += 1;
1117            }
1118            cur = self.tree.get(n).parent;
1119        }
1120        depth
1121    }
1122
1123    /// The container depth a new block of `tag` would open at under `tip`.
1124    /// `add_child` closes the blocks that cannot hold it first, so the
1125    /// holder is the nearest of `tip` and its ancestors that can (or the
1126    /// document), and the new block is one deeper than that. The walk is
1127    /// bounded by `MAX_CONTAINER_NESTING` itself, since the spine never
1128    /// holds more containers than that.
1129    fn depth_of_new(&self, tip: NodeId, tag: NodeType) -> usize {
1130        let mut holder = tip;
1131        while holder != self.doc && !can_contain(self.node_type(holder), tag) {
1132            holder = self
1133                .tree
1134                .get(holder)
1135                .parent
1136                .expect("every block below the document has a parent");
1137        }
1138        self.container_depth(holder) + 1
1139    }
1140
1141    /// Open a block of `tag` as a child of the tip, closing blocks that
1142    /// cannot contain it first.
1143    fn add_child(&mut self, tag: NodeType, offset: usize) -> NodeId {
1144        // The document accepts everything but an item, and the list-item
1145        // start always opens a list first, so this terminates at the
1146        // document at the latest. Stopping there rather than closing the
1147        // document keeps the parser total where the TypeScript would throw
1148        // on the next `openTip`.
1149        loop {
1150            let tip = self.open_tip();
1151            if tip == self.doc || can_contain(self.node_type(tip), tag) {
1152                break;
1153            }
1154            self.finalize(tip, self.line_number - 1);
1155        }
1156
1157        let column_number = self.source_column(offset) + 1; // offset 0 is column 1
1158        let mut node = MdNode::new(tag);
1159        node.sourcepos = [[self.line_number, column_number], [0, 0]];
1160        if tag == NodeType::Paragraph {
1161            node.content_line = self.line_number;
1162        }
1163        let id = self.tree.add(node);
1164        let tip = self.open_tip();
1165        self.tree.append_child(tip, id);
1166        self.tip = Some(id);
1167        if opens_event(tag) {
1168            if let Some(events) = &mut self.events {
1169                events.push(BlockEvent::Open(id));
1170            }
1171        }
1172        id
1173    }
1174
1175    /// The GFM tables block start: read the current line as the delimiter
1176    /// row of a table whose header row is the last line of the open
1177    /// paragraph `container`.
1178    ///
1179    /// The two rows must agree on the number of cells; if they do not,
1180    /// there is no table and the line is nothing special (spec example 6
1181    /// keeps the whole thing a paragraph). The header row is the paragraph's
1182    /// **last** line only, so a paragraph that had earlier lines is split:
1183    /// those lines stay a paragraph, finalized here, which is what still
1184    /// lets them contribute link reference definitions, and the table is
1185    /// opened after it.
1186    ///
1187    /// On success the table is the tip and the caller returns "leaf
1188    /// started", so step 3 hands the delimiter row itself to `add_line`,
1189    /// which skips it: the header row is made here, and every later line of
1190    /// the table is a body row the moment it arrives.
1191    fn try_open_table(&mut self, container: NodeId) -> bool {
1192        if !self.options.gfm || self.indented || self.node_type(container) != NodeType::Paragraph {
1193            return false;
1194        }
1195
1196        let Some(align) = parse_delimiter_row(&self.current_line[self.next_nonspace..]) else {
1197            return false;
1198        };
1199
1200        // The header row is the line directly above, which is the line
1201        // `add_line` last wrote: to this paragraph, or there is no header
1202        // row at all.
1203        if self.last_added_to != Some(container) {
1204            return false;
1205        }
1206        let header_cells = split_table_row(&self.last_added_line);
1207        if header_cells.len() != align.len() {
1208            return false;
1209        }
1210
1211        self.close_unmatched_blocks();
1212
1213        let header_line = self.line_number - 1;
1214        let header_column = self.last_added_column;
1215        // `string_content` ends with that same line plus the newline
1216        // `add_line` put after it, so the header row starts this far in: no
1217        // scan needed, and the content is only ever touched on the split
1218        // branch, at most once per table.
1219        let content_len = self.tree.get(container).string_content.len();
1220        let header_start = content_len as isize - self.last_added_line.len() as isize - 1;
1221        if header_start > 0 {
1222            // Split: everything above the header row stays a paragraph. It
1223            // ends two lines back, not one, so `finalize`'s default end
1224            // column (the previous line's, which here is the header row's)
1225            // would be somebody else's.
1226            self.tree
1227                .get_mut(container)
1228                .string_content
1229                .truncate(header_start as usize);
1230            let end_column = self.prev_line_length;
1231            self.finalize_at(container, header_line - 1, end_column);
1232        } else {
1233            let parent = self.tree.get(container).parent;
1234            self.tree.unlink(container);
1235            self.note_dropped(container);
1236            self.tip = parent;
1237        }
1238
1239        let table = self.add_child(NodeType::Table, self.next_nonspace);
1240        // `add_child` both dated and placed the table from the delimiter
1241        // row, and neither belongs to it: the table begins on the header
1242        // row, one line above, in the column where *that* row's content
1243        // starts. The two rows are indented independently, so the delimiter
1244        // row's column is simply somebody else's: `  a | b` over `| - | -`
1245        // starts in column 3, and `a | b` over `  | - | -` starts in column
1246        // 1.
1247        {
1248            let node = self.tree.get_mut(table);
1249            node.sourcepos[0][0] = header_line;
1250            node.sourcepos[0][1] = header_column;
1251            node.table_align = Some(align);
1252        }
1253        self.table_delimiter_row = Some(table);
1254
1255        // The row is measured over its own text, exactly as `add_line`
1256        // measures the body rows: `last_line_length` counts the whole source
1257        // line, container markers included, so inside a block quote it would
1258        // end the header row two columns past where every body row of the
1259        // same table ends.
1260        let end_column = char_count(&self.last_added_line);
1261        self.add_table_row(table, &header_cells, true, header_line, end_column);
1262        true
1263    }
1264
1265    /// Append one row of `cells` to `table`, padded with empty cells or
1266    /// truncated so that it is exactly as wide as the delimiter row said.
1267    ///
1268    /// Rows and cells are built closed: they are not part of the open
1269    /// spine, and the line walk in `incorporate_line` must stop at the
1270    /// table itself.
1271    fn add_table_row(
1272        &mut self,
1273        table: NodeId,
1274        cells: &[String],
1275        is_header: bool,
1276        line_number: usize,
1277        end_column: usize,
1278    ) {
1279        let width = self
1280            .tree
1281            .get(table)
1282            .table_align
1283            .as_ref()
1284            .map_or(0, Vec::len);
1285
1286        // See MAX_AUTOCOMPLETED_CELLS: padding is the only unbounded part of
1287        // a table.
1288        let mut limit = width;
1289        if cells.len() < width {
1290            let budget = MAX_AUTOCOMPLETED_CELLS.saturating_sub(self.autocompleted_cells);
1291            let padding = width - cells.len();
1292            if padding > budget {
1293                limit = cells.len() + budget;
1294            }
1295            self.autocompleted_cells += limit - cells.len();
1296        }
1297
1298        // A row and its cells occupy one source line. Columns within that
1299        // line are not tracked: nothing reads them (the AST drops sourcepos
1300        // and the renderer ignores it), and threading offsets through the
1301        // cell split to invent them would be cost with no reader.
1302        let span: SourcePos = [[line_number, 1], [line_number, end_column]];
1303
1304        let mut row = MdNode::new(NodeType::TableRow);
1305        row.sourcepos = span;
1306        row.is_header_row = is_header;
1307        row.open = false;
1308        let row = self.tree.add(row);
1309        self.tree.append_child(table, row);
1310
1311        for i in 0..limit {
1312            let mut cell = MdNode::new(NodeType::TableCell);
1313            cell.sourcepos = span;
1314            cell.open = false;
1315            // Consumed by the inline phase, exactly as a paragraph's content
1316            // is.
1317            if i < cells.len() {
1318                cell.string_content = cells[i].clone();
1319            }
1320            let cell = self.tree.add(cell);
1321            self.tree.append_child(row, cell);
1322        }
1323
1324        if let Some(events) = &mut self.events {
1325            events.push(BlockEvent::Row(row));
1326        }
1327    }
1328
1329    /// Close a table. Its body rows were made one per line as the lines
1330    /// came (`add_line`): the table accepts exactly one line per source
1331    /// line, and a blank line closes it, so each row's line is the line that
1332    /// made it, and a row is finished the moment its line is, which is what
1333    /// lets a driver write a table a row at a time.
1334    fn finalize_table(&mut self, table: NodeId) {
1335        self.tree.get_mut(table).string_content.clear();
1336    }
1337
1338    /// Close every block that failed its continuation condition on this
1339    /// line.
1340    fn close_unmatched_blocks(&mut self) {
1341        if self.all_closed {
1342            return;
1343        }
1344        while self.oldtip != self.last_matched_container {
1345            let parent = self.tree.get(self.oldtip).parent;
1346            self.finalize(self.oldtip, self.line_number - 1);
1347            match parent {
1348                Some(p) => self.oldtip = p,
1349                None => break,
1350            }
1351        }
1352        self.all_closed = true;
1353    }
1354
1355    /// Close a block, record its end position, and run its finalizer. The
1356    /// end column is the previous line's length, which is where every block
1357    /// that ends on `line_number` ends.
1358    fn finalize(&mut self, block: NodeId, line_number: usize) {
1359        self.finalize_at(block, line_number, self.last_line_length);
1360    }
1361
1362    /// `finalize` with the end column given rather than assumed. Only a
1363    /// table's paragraph split needs it: that one closes a block two lines
1364    /// back, where `finalize`'s default is one line too recent.
1365    fn finalize_at(&mut self, block: NodeId, line_number: usize, end_column: usize) {
1366        let above = self.tree.get(block).parent;
1367        {
1368            let node = self.tree.get_mut(block);
1369            node.open = false;
1370            node.sourcepos[1] = [line_number, end_column];
1371        }
1372        self.finalize_block(block);
1373        self.html_block_types.remove(&block);
1374        self.tip = above;
1375        if let Some(events) = &mut self.events {
1376            events.push(BlockEvent::Close(block));
1377        }
1378    }
1379
1380    /// `block.listData.tight = false` on a list, as the other runtimes see
1381    /// it. In TypeScript the list and the item that opened it hold the SAME
1382    /// `listData` object (`addChild('list').listData = data` and then
1383    /// `addChild('item').listData = data`), and Go shares the pointer the
1384    /// same way, so loosening the list also loosens that first item's
1385    /// `listData`. Here `list_data` is an owned value on each node, so the
1386    /// aliasing has to be spelled out: the native tree (and its goldens)
1387    /// carry the item's `tight`, and the projection and the renderer read
1388    /// only the list's. Later items keep their own `tight: true`, in every
1389    /// runtime.
1390    fn mark_list_loose(&mut self, list: NodeId) {
1391        if let Some(data) = self.tree.get_mut(list).list_data.as_mut() {
1392            data.tight = false;
1393        }
1394        if let Some(first) = self.tree.get(list).first_child {
1395            if let Some(data) = self.tree.get_mut(first).list_data.as_mut() {
1396                data.tight = false;
1397            }
1398        }
1399    }
1400
1401    /// The per-type finalizer the TypeScript keeps in `BLOCK_HANDLERS`.
1402    fn finalize_block(&mut self, block: NodeId) {
1403        match self.node_type(block) {
1404            NodeType::List => {
1405                // Section 5.3: the list is loose if any item is followed by
1406                // a blank line, or if any item directly contains two blocks
1407                // separated by one. A blank line at the very end of the
1408                // last item does not count, hence the `next` guards.
1409                let mut item = self.tree.get(block).first_child;
1410                'items: while let Some(it) = item {
1411                    let item_next = self.tree.get(it).next;
1412                    if self.ends_with_blank_line(it) && item_next.is_some() {
1413                        self.mark_list_loose(block);
1414                        break;
1415                    }
1416                    let mut subitem = self.tree.get(it).first_child;
1417                    while let Some(sub) = subitem {
1418                        let sub_next = self.tree.get(sub).next;
1419                        if self.ends_with_blank_line(sub)
1420                            && (item_next.is_some() || sub_next.is_some())
1421                        {
1422                            self.mark_list_loose(block);
1423                            break 'items;
1424                        }
1425                        subitem = sub_next;
1426                    }
1427                    item = item_next;
1428                }
1429                if let Some(last) = self.tree.get(block).last_child {
1430                    let end = self.tree.get(last).sourcepos[1];
1431                    self.tree.get_mut(block).sourcepos[1] = end;
1432                }
1433            }
1434
1435            NodeType::Item => {
1436                let node = self.tree.get(block);
1437                if let Some(last) = node.last_child {
1438                    let end = self.tree.get(last).sourcepos[1];
1439                    self.tree.get_mut(block).sourcepos[1] = end;
1440                } else if let Some(data) = &node.list_data {
1441                    let end = [node.sourcepos[0][0], data.marker_offset + data.padding];
1442                    self.tree.get_mut(block).sourcepos[1] = end;
1443                }
1444            }
1445
1446            NodeType::CodeBlock => {
1447                let node = self.tree.get_mut(block);
1448                if node.is_fenced {
1449                    // The first accumulated line is the info string, not
1450                    // content.
1451                    let content = std::mem::take(&mut node.string_content);
1452                    match content.find('\n') {
1453                        Some(nl) => {
1454                            node.info = Some(unescape_string(js_trim(&content[..nl])));
1455                            node.literal = content[nl + 1..].to_string();
1456                        }
1457                        None => {
1458                            node.info = Some(unescape_string(js_trim(&content)));
1459                            node.literal = String::new();
1460                        }
1461                    }
1462                } else {
1463                    // Section 4.4: trailing blank lines are not part of an
1464                    // indented code block. This is `.replace(/(\n *)+$/, '\n')`.
1465                    let content = std::mem::take(&mut node.string_content);
1466                    let start = trailing_blank_run_start(content.as_bytes());
1467                    if start < content.len() {
1468                        node.literal = format!("{}\n", &content[..start]);
1469                    } else {
1470                        node.literal = content;
1471                    }
1472                }
1473            }
1474
1475            NodeType::HtmlBlock => {
1476                // `.replace(/(\n *)+$/, '')`
1477                let node = self.tree.get_mut(block);
1478                let content = std::mem::take(&mut node.string_content);
1479                let start = trailing_blank_run_start(content.as_bytes());
1480                node.literal = content[..start].to_string();
1481            }
1482
1483            NodeType::Paragraph => {
1484                // Section 4.7: a paragraph may begin with link reference
1485                // definitions. Consume them from the front; if nothing is
1486                // left, the paragraph disappears.
1487                if self.read_definitions(block) && is_blank(&self.tree.get(block).string_content) {
1488                    self.tree.unlink(block);
1489                } else {
1490                    self.mark_task_item(block);
1491                }
1492            }
1493
1494            // GFM tables. The header row is built when the table opens (see
1495            // `try_open_table`); every later line is accumulated raw and
1496            // split into a body row at finalize, so the table behaves like a
1497            // paragraph that happens to print as a grid: it ends at a blank
1498            // line, and any block start interrupts it, because it is not
1499            // verbatim and `can_contain` refuses everything the block starts
1500            // can open.
1501            NodeType::Table => self.finalize_table(block),
1502
1503            _ => {}
1504        }
1505    }
1506
1507    /// Section 5.3 looseness input: does this block end with a blank line?
1508    /// For lists and items the question recurses into the last child, since
1509    /// the blank line is recorded on the deepest block that saw it. The
1510    /// `last_line_checked` flag makes the recursion linear over the whole
1511    /// document rather than quadratic.
1512    fn ends_with_blank_line(&mut self, block: NodeId) -> bool {
1513        let mut cur = Some(block);
1514        while let Some(id) = cur {
1515            let node = self.tree.get_mut(id);
1516            if node.last_line_blank {
1517                return true;
1518            }
1519            let t = node.node_type;
1520            if !node.last_line_checked && (t == NodeType::List || t == NodeType::Item) {
1521                node.last_line_checked = true;
1522                cur = node.last_child;
1523            } else {
1524                node.last_line_checked = true;
1525                return false;
1526            }
1527        }
1528        false
1529    }
1530
1531    /// Section 4.7: read the link reference definitions off the front of a
1532    /// paragraph's raw content, as the paragraph finishes or a setext
1533    /// underline converts it, and report whether any was read. Each is
1534    /// recorded three ways: in the refmap (the first definition of a label
1535    /// wins), beside the paragraph's container where it stands (after the
1536    /// paragraph's previous sibling, so before the paragraph, or where it
1537    /// stood once it is gone), and, for a driver, as an event. Mirrors
1538    /// `ts/src/block.ts` `readDefinitions`.
1539    fn read_definitions(&mut self, para: NodeId) -> bool {
1540        let content = std::mem::take(&mut self.tree.get_mut(para).string_content);
1541        let definitions = parse_definitions(&content);
1542        let Some(consumed) = definitions.last().map(|d| d.end) else {
1543            self.tree.get_mut(para).string_content = content;
1544            return false;
1545        };
1546        let parent = self.tree.get(para).parent;
1547        let after = self.tree.get(para).prev;
1548        let mut line = self.tree.get(para).content_line;
1549        for d in definitions {
1550            // Every line of a paragraph is one source line, so the
1551            // definition's lines are counted from where the content begins.
1552            let taken = &content[d.start..d.end];
1553            let newlines = taken.bytes().filter(|&b| b == b'\n').count();
1554            let last = usize::from(taken.ends_with('\n'));
1555            let def = Definition {
1556                label: d.label,
1557                destination: d.destination,
1558                title: d.title,
1559                start: line,
1560                end: line + newlines - last,
1561            };
1562            line += newlines;
1563            self.refmap
1564                .entry(normalize_reference(&def.label))
1565                .or_insert(RefDef {
1566                    destination: def.destination.clone(),
1567                    title: def.title.clone(),
1568                });
1569            if let Some(parent) = parent {
1570                self.tree.get_mut(parent).definitions.push(DefinitionSite {
1571                    after,
1572                    def: def.clone(),
1573                });
1574            }
1575            if let Some(events) = &mut self.events {
1576                events.push(BlockEvent::Definition(def));
1577            }
1578        }
1579        let node = self.tree.get_mut(para);
1580        node.content_line = line;
1581        node.string_content = content[consumed..].to_string();
1582        true
1583    }
1584
1585    /// GFM task list items: an item whose first block is a paragraph
1586    /// beginning with a task list item marker is checked or not, and the
1587    /// marker is consumed so it does not survive into the text. Decided as
1588    /// the paragraph finishes, on its raw content, before the inline phase
1589    /// has seen it: that is what makes the marker win over anything the
1590    /// inline scanner would make of the brackets (with a `[x]: /url`
1591    /// definition in the document, `- [x] foo` is still a task item rather
1592    /// than a link), and what settles the item's checked state before the
1593    /// item itself finishes.
1594    fn mark_task_item(&mut self, para: NodeId) {
1595        if !self.options.gfm {
1596            return;
1597        }
1598        let Some(item) = self.tree.get(para).parent else {
1599            return;
1600        };
1601        if self.node_type(item) != NodeType::Item || self.tree.get(item).first_child != Some(para) {
1602            return;
1603        }
1604        if let Some((state, length)) = task_list_marker(&self.tree.get(para).string_content) {
1605            // Whitespace between the brackets is unchecked; `x`/`X` is
1606            // checked.
1607            self.tree.get_mut(item).checked = Some(state != b' ' && state != b'\t');
1608            self.tree.get_mut(para).string_content.drain(..length);
1609        }
1610    }
1611
1612    /// Can `container` absorb the current line?
1613    fn continue_block(&mut self, container: NodeId) -> ContinueResult {
1614        match self.node_type(container) {
1615            NodeType::Document | NodeType::List => ContinueResult::Matched,
1616
1617            NodeType::BlockQuote => {
1618                if !self.indented && peek(&self.current_line, self.next_nonspace) == Some(b'>') {
1619                    self.advance_next_nonspace();
1620                    self.advance_offset(1, false);
1621                    // Section 5.1: one optional space of indentation after
1622                    // `>`, tab-aware.
1623                    if is_space_or_tab(peek(&self.current_line, self.offset)) {
1624                        self.advance_offset(1, true);
1625                    }
1626                    return ContinueResult::Matched;
1627                }
1628                ContinueResult::NotMatched
1629            }
1630
1631            NodeType::Item => {
1632                let (marker_offset, padding, first_child) = {
1633                    let node = self.tree.get(container);
1634                    let Some(data) = &node.list_data else {
1635                        return ContinueResult::NotMatched;
1636                    };
1637                    (data.marker_offset, data.padding, node.first_child)
1638                };
1639
1640                if self.blank {
1641                    // An item whose first line is blank cannot be continued
1642                    // by a second blank line (section 5.2 rule 3: at most
1643                    // one leading blank line).
1644                    if first_child.is_none() {
1645                        return ContinueResult::NotMatched;
1646                    }
1647                    self.advance_next_nonspace();
1648                    return ContinueResult::Matched;
1649                }
1650
1651                // Section 5.2: subsequent lines belong to the item if
1652                // indented to the content column derived from the marker.
1653                if self.indent >= marker_offset + padding {
1654                    self.advance_offset(marker_offset + padding, true);
1655                    return ContinueResult::Matched;
1656                }
1657                ContinueResult::NotMatched
1658            }
1659
1660            // A heading is always exactly one line (setext headings are
1661            // converted from an already-complete paragraph).
1662            NodeType::Heading | NodeType::ThematicBreak => ContinueResult::NotMatched,
1663
1664            NodeType::CodeBlock => {
1665                let indent = self.indent;
1666                let (is_fenced, fence_char, fence_length, fence_offset) = {
1667                    let node = self.tree.get(container);
1668                    (
1669                        node.is_fenced,
1670                        node.fence_char,
1671                        node.fence_length,
1672                        node.fence_offset,
1673                    )
1674                };
1675
1676                if is_fenced {
1677                    // Section 4.5: the closing fence is the same character,
1678                    // at least as long, at most 3 columns indented, and
1679                    // followed only by spaces or tabs.
1680                    let mut match_len = 0;
1681                    if indent <= 3
1682                        && peek(&self.current_line, self.next_nonspace) == Some(fence_char)
1683                    {
1684                        match_len =
1685                            match_closing_code_fence(&self.current_line[self.next_nonspace..]);
1686                    }
1687                    if match_len > 0 && match_len >= fence_length {
1688                        self.last_line_length =
1689                            char_count(&self.current_line[..self.offset]) + indent + match_len;
1690                        self.finalize(container, self.line_number);
1691                        return ContinueResult::LineDone;
1692                    }
1693                    // Content is de-indented by up to the opening fence's own
1694                    // indent.
1695                    let mut i = fence_offset;
1696                    while i > 0 && is_space_or_tab(peek(&self.current_line, self.offset)) {
1697                        self.advance_offset(1, true);
1698                        i -= 1;
1699                    }
1700                    return ContinueResult::Matched;
1701                }
1702
1703                // Section 4.4 indented code: four columns, or a blank line
1704                // (which is kept).
1705                if indent >= CODE_INDENT {
1706                    self.advance_offset(CODE_INDENT, true);
1707                    return ContinueResult::Matched;
1708                }
1709                if self.blank {
1710                    self.advance_next_nonspace();
1711                    return ContinueResult::Matched;
1712                }
1713                ContinueResult::NotMatched
1714            }
1715
1716            NodeType::HtmlBlock => {
1717                // Types 6 and 7 end at a blank line; 1 to 5 end on their
1718                // closing string, which `incorporate_line` checks after
1719                // adding the line.
1720                let kind = self.html_block_type(container);
1721                if self.blank && (kind == 6 || kind == 7) {
1722                    return ContinueResult::NotMatched;
1723                }
1724                ContinueResult::Matched
1725            }
1726
1727            NodeType::Paragraph | NodeType::Table => {
1728                if self.blank {
1729                    ContinueResult::NotMatched
1730                } else {
1731                    ContinueResult::Matched
1732                }
1733            }
1734
1735            // Rows and cells are created closed, and are never the parser's
1736            // tip, so nothing here is reached in a normal parse. An inert
1737            // leaf is the safe reading: no continuation, no children, no
1738            // lines.
1739            _ => ContinueResult::NotMatched,
1740        }
1741    }
1742
1743    /// Parse a list marker at `next_nonspace` and derive the item's
1744    /// content indent.
1745    ///
1746    /// The content indent is marker width + the spaces that follow it,
1747    /// with two exceptions that both fall back to marker width + 1:
1748    ///
1749    /// - rule 2, item starting with indented code: 5+ spaces after the
1750    ///   marker means only the first space belongs to the marker, the rest
1751    ///   is code;
1752    /// - rule 3, item starting with a blank line: nothing follows the
1753    ///   marker at all, so there are no spaces to measure.
1754    ///
1755    /// Returns `None` when this is not a list item start. Advances the
1756    /// parser to the item's content column when it is.
1757    fn parse_list_marker(&mut self, container: NodeId) -> Option<ListData> {
1758        // Four columns of indentation is indented code, never a list marker.
1759        if self.indent >= CODE_INDENT {
1760            return None;
1761        }
1762
1763        let container_is_paragraph = self.node_type(container) == NodeType::Paragraph;
1764        let rest = &self.current_line[self.next_nonspace..];
1765
1766        let mut data = ListData {
1767            list_type: ListType::Bullet,
1768            tight: true, // lists are tight until finalize proves otherwise
1769            start: 1,
1770            delimiter: String::new(),
1771            bullet_char: String::new(),
1772            padding: 0,
1773            marker_offset: self.indent,
1774        };
1775
1776        let marker_len;
1777        if is_bullet_list_marker(rest) {
1778            data.list_type = ListType::Bullet;
1779            data.bullet_char = rest[..1].to_string();
1780            marker_len = 1;
1781        } else {
1782            let (digits, delimiter) = match_ordered_list_marker(rest)?;
1783            // At most nine digits, which always fit.
1784            let start: i64 = rest[..digits].parse().ok()?;
1785            // Section 5.2 exception 1(b): an ordered item interrupting a
1786            // paragraph must start at 1.
1787            if container_is_paragraph && start != 1 {
1788                return None;
1789            }
1790            data.list_type = ListType::Ordered;
1791            data.start = start;
1792            data.delimiter = (delimiter as char).to_string();
1793            marker_len = digits + 1;
1794        }
1795
1796        // At least one space or tab (or the end of the line) must follow the
1797        // marker.
1798        let nextc = peek(&self.current_line, self.next_nonspace + marker_len);
1799        if !(nextc.is_none() || nextc == Some(b'\t') || nextc == Some(b' ')) {
1800            return None;
1801        }
1802
1803        // Section 5.2 exception 1(a): an item interrupting a paragraph may
1804        // not start blank.
1805        if container_is_paragraph && is_blank(&self.current_line[self.next_nonspace + marker_len..])
1806        {
1807            return None;
1808        }
1809
1810        self.advance_next_nonspace(); // to the marker
1811        self.advance_offset(marker_len, true); // past the marker
1812
1813        let spaces_start_col = self.column;
1814        let spaces_start_offset = self.offset;
1815        loop {
1816            self.advance_offset(1, true);
1817            let nextc = peek(&self.current_line, self.offset);
1818            if !(self.column - spaces_start_col < 5 && is_space_or_tab(nextc)) {
1819                break;
1820            }
1821        }
1822
1823        let blank_item = peek(&self.current_line, self.offset).is_none();
1824        let spaces_after_marker = self.column - spaces_start_col;
1825
1826        if !(1..5).contains(&spaces_after_marker) || blank_item {
1827            data.padding = marker_len + 1;
1828            self.column = spaces_start_col;
1829            self.offset = spaces_start_offset;
1830            if is_space_or_tab(peek(&self.current_line, self.offset)) {
1831                self.advance_offset(1, true);
1832            }
1833        } else {
1834            data.padding = marker_len + spaces_after_marker;
1835        }
1836
1837        Some(data)
1838    }
1839
1840    /// The block starts, tried in order, and the order is the spec's: a
1841    /// setext underline beats a thematic break (so `Foo\n---` is a
1842    /// heading), a thematic break beats a list item (so `- - -` is a
1843    /// break), and indented code comes last because any of the others may
1844    /// be indented up to three columns. The GFM table start is last of all;
1845    /// see `try_open_table`.
1846    fn block_start(&mut self, index: usize, container: NodeId) -> StartResult {
1847        match index {
1848            // Block quote (section 5.1).
1849            0 => {
1850                if !self.indented && peek(&self.current_line, self.next_nonspace) == Some(b'>') {
1851                    // The nesting limit: past it the marker is text. The
1852                    // holder is judged from `container`, which is what the
1853                    // tip becomes once `close_unmatched_blocks` has run.
1854                    if self.depth_of_new(container, NodeType::BlockQuote) > MAX_CONTAINER_NESTING {
1855                        return StartResult::None;
1856                    }
1857                    self.advance_next_nonspace();
1858                    self.advance_offset(1, false);
1859                    if is_space_or_tab(peek(&self.current_line, self.offset)) {
1860                        self.advance_offset(1, true);
1861                    }
1862                    self.close_unmatched_blocks();
1863                    self.add_child(NodeType::BlockQuote, self.next_nonspace);
1864                    return StartResult::Container;
1865                }
1866                StartResult::None
1867            }
1868
1869            // ATX heading (section 4.2).
1870            1 => {
1871                if self.indented {
1872                    return StartResult::None;
1873                }
1874                let Some((level, match_len)) =
1875                    match_atx_heading_marker(&self.current_line[self.next_nonspace..])
1876                else {
1877                    return StartResult::None;
1878                };
1879
1880                self.advance_next_nonspace();
1881                self.advance_offset(match_len, false);
1882                self.close_unmatched_blocks();
1883
1884                let heading = self.add_child(NodeType::Heading, self.next_nonspace);
1885                let content = strip_atx_closing(&self.current_line[self.offset..]).to_string();
1886                {
1887                    let node = self.tree.get_mut(heading);
1888                    node.level = level;
1889                    node.string_content = content;
1890                }
1891                let rest = self.current_line.len() - self.offset;
1892                self.advance_offset(rest, false);
1893                StartResult::Leaf
1894            }
1895
1896            // Fenced code block (section 4.5).
1897            2 => {
1898                if self.indented {
1899                    return StartResult::None;
1900                }
1901                let rest = &self.current_line[self.next_nonspace..];
1902                let fence_length = match_code_fence(rest);
1903                if fence_length == 0 {
1904                    return StartResult::None;
1905                }
1906                let fence_char = rest.as_bytes()[0];
1907
1908                self.close_unmatched_blocks();
1909                let code = self.add_child(NodeType::CodeBlock, self.next_nonspace);
1910                {
1911                    let node = self.tree.get_mut(code);
1912                    node.is_fenced = true;
1913                    node.fence_length = fence_length;
1914                    node.fence_char = fence_char;
1915                    node.fence_offset = self.indent;
1916                }
1917                self.advance_next_nonspace();
1918                self.advance_offset(fence_length, false);
1919                // The rest of the line is added as the block's first line:
1920                // the info string.
1921                StartResult::Leaf
1922            }
1923
1924            // HTML block (section 4.6), types 1 to 7.
1925            3 => {
1926                if self.indented || peek(&self.current_line, self.next_nonspace) != Some(b'<') {
1927                    return StartResult::None;
1928                }
1929                let kind = html_block_open_kind(&self.current_line[self.next_nonspace..]);
1930                if kind == 0 {
1931                    return StartResult::None;
1932                }
1933                // Type 7 may not interrupt a paragraph, including a
1934                // paragraph we are only about to continue lazily.
1935                if kind == 7
1936                    && (self.node_type(container) == NodeType::Paragraph
1937                        || (!self.all_closed
1938                            && !self.blank
1939                            && self.node_type(self.open_tip()) == NodeType::Paragraph))
1940                {
1941                    return StartResult::None;
1942                }
1943                self.close_unmatched_blocks();
1944                // The offset is deliberately not advanced: leading spaces
1945                // are part of the raw HTML.
1946                let block = self.add_child(NodeType::HtmlBlock, self.offset);
1947                self.set_html_block_type(block, kind);
1948                StartResult::Leaf
1949            }
1950
1951            // Setext heading underline (section 4.3): converts the whole
1952            // open paragraph.
1953            4 => {
1954                if self.indented || self.node_type(container) != NodeType::Paragraph {
1955                    return StartResult::None;
1956                }
1957                let Some(underline) =
1958                    match_setext_heading_line(&self.current_line[self.next_nonspace..])
1959                else {
1960                    return StartResult::None;
1961                };
1962
1963                self.close_unmatched_blocks();
1964
1965                // Section 4.7: the paragraph may still have led with
1966                // reference definitions; only what remains becomes the
1967                // heading. If nothing remains this is not a setext underline
1968                // at all (it falls through to thematic break / paragraph).
1969                self.read_definitions(container);
1970                if self.tree.get(container).string_content.is_empty() {
1971                    return StartResult::None;
1972                }
1973
1974                let start = self.tree.get(container).sourcepos[0];
1975                let content = std::mem::take(&mut self.tree.get_mut(container).string_content);
1976                let mut heading = MdNode::new(NodeType::Heading);
1977                heading.sourcepos = [[start[0], start[1]], [0, 0]];
1978                heading.level = if underline == b'=' { 1 } else { 2 };
1979                heading.string_content = content;
1980                let heading = self.tree.add(heading);
1981                self.tree.insert_after(container, heading);
1982                self.tree.unlink(container);
1983                self.note_dropped(container);
1984                self.tip = Some(heading);
1985                let rest = self.current_line.len() - self.offset;
1986                self.advance_offset(rest, false);
1987                StartResult::Leaf
1988            }
1989
1990            // Thematic break (section 4.1).
1991            5 => {
1992                if self.indented {
1993                    return StartResult::None;
1994                }
1995                if !is_thematic_break(&self.current_line[self.next_nonspace..]) {
1996                    return StartResult::None;
1997                }
1998                self.close_unmatched_blocks();
1999                self.add_child(NodeType::ThematicBreak, self.next_nonspace);
2000                let rest = self.current_line.len() - self.offset;
2001                self.advance_offset(rest, false);
2002                StartResult::Leaf
2003            }
2004
2005            // List item (section 5.2). `parse_list_marker` rejects a marker
2006            // indented four or more columns on its own, so there is no
2007            // `indented` test here.
2008            6 => {
2009                // `parse_list_marker` moves the cursor when it matches, so
2010                // the position is kept for the nesting limit below, which
2011                // has to leave the line exactly as it found it.
2012                let before = (self.offset, self.column, self.partially_consumed_tab);
2013                let Some(data) = self.parse_list_marker(container) else {
2014                    return StartResult::None;
2015                };
2016
2017                // Section 5.3: a change of bullet character or ordered
2018                // delimiter starts a new list. Judged from `container`,
2019                // which is what the tip becomes once
2020                // `close_unmatched_blocks` has run.
2021                let same_list = self.node_type(container) == NodeType::List
2022                    && self
2023                        .tree
2024                        .get(container)
2025                        .list_data
2026                        .as_ref()
2027                        .is_some_and(|existing| lists_match(existing, &data));
2028
2029                // The nesting limit: an item in the open list is one
2030                // container deeper, a new list and its item are two. Past
2031                // it the marker is text.
2032                let depth = if same_list {
2033                    self.depth_of_new(container, NodeType::Item)
2034                } else {
2035                    self.depth_of_new(container, NodeType::List) + 1
2036                };
2037                if depth > MAX_CONTAINER_NESTING {
2038                    (self.offset, self.column, self.partially_consumed_tab) = before;
2039                    return StartResult::None;
2040                }
2041
2042                self.close_unmatched_blocks();
2043
2044                let tip = self.open_tip();
2045                debug_assert_eq!(tip, container, "the tip is the last matched container");
2046                if !same_list {
2047                    let list = self.add_child(NodeType::List, self.next_nonspace);
2048                    self.tree.get_mut(list).list_data = Some(data.clone());
2049                }
2050
2051                let item = self.add_child(NodeType::Item, self.next_nonspace);
2052                self.tree.get_mut(item).list_data = Some(data);
2053                StartResult::Container
2054            }
2055
2056            // Indented code block (section 4.4): may not interrupt a
2057            // paragraph.
2058            7 => {
2059                if !self.indented
2060                    || self.node_type(self.open_tip()) == NodeType::Paragraph
2061                    || self.blank
2062                {
2063                    return StartResult::None;
2064                }
2065                self.advance_offset(CODE_INDENT, true);
2066                self.close_unmatched_blocks();
2067                self.add_child(NodeType::CodeBlock, self.offset);
2068                StartResult::Leaf
2069            }
2070
2071            // GFM table (extension): a delimiter row directly under an open
2072            // paragraph.
2073            //
2074            // Last, and the position is load-bearing in both directions. It
2075            // must come after the setext underline so that `foo` over `---`
2076            // stays an `<h2>` rather than becoming a one-column table, and
2077            // after the list marker so that `- | -` stays a list item;
2078            // cmark-gfm reaches its extensions from the same place, once
2079            // every built-in start has refused the line.
2080            8 => {
2081                if self.try_open_table(container) {
2082                    StartResult::Leaf
2083                } else {
2084                    StartResult::None
2085                }
2086            }
2087
2088            _ => StartResult::None,
2089        }
2090    }
2091
2092    /// How many block starts `block_start` knows.
2093    const BLOCK_STARTS: usize = 9;
2094
2095    /// Incorporate one line into the tree: the three steps of Appendix A.
2096    pub fn incorporate_line(&mut self, ln: &str) {
2097        let mut all_matched = true;
2098        let mut container = self.doc;
2099
2100        // `last_line_length` still measures the previous line here.
2101        // Captured before anything can overwrite it (an HTML block closing
2102        // mid-line does) and installed as `prev_line_length` at whichever
2103        // exit updates `last_line_length`, so the two always describe
2104        // consecutive lines.
2105        let length_before_this_line = self.last_line_length;
2106
2107        self.oldtip = self.open_tip();
2108        self.offset = 0;
2109        self.column = 0;
2110        self.blank = false;
2111        self.partially_consumed_tab = false;
2112        self.line_number += 1;
2113        self.current_line.clear();
2114        self.current_line.push_str(ln);
2115        // The column anchor memoizes offsets into `current_line`; a new line
2116        // invalidates it. See `source_column`.
2117        self.col_anchor_offset = 0;
2118        self.col_anchor_chars = 0;
2119
2120        // Step 1: walk the open blocks, consuming continuation markers.
2121        // Stop at the first block that does not match; `container` is then
2122        // the last matched one.
2123        let mut last_child = self.tree.get(container).last_child;
2124        while let Some(child) = last_child {
2125            if !self.tree.get(child).open {
2126                break;
2127            }
2128            container = child;
2129            self.find_next_nonspace();
2130
2131            match self.continue_block(container) {
2132                ContinueResult::NotMatched => all_matched = false,
2133                // A fenced code block was closed by this line; nothing else
2134                // to do.
2135                ContinueResult::LineDone => return,
2136                ContinueResult::Matched => {}
2137            }
2138
2139            if !all_matched {
2140                if let Some(parent) = self.tree.get(container).parent {
2141                    container = parent;
2142                }
2143                break;
2144            }
2145
2146            last_child = self.tree.get(container).last_child;
2147        }
2148
2149        self.all_closed = container == self.oldtip;
2150        self.last_matched_container = container;
2151
2152        // Step 2: look for new block starts under the last matched
2153        // container, unless its lines are literal text, in which case there
2154        // is nothing to look for.
2155        let mut matched_leaf = verbatim(self.node_type(container));
2156
2157        while !matched_leaf {
2158            self.find_next_nonspace();
2159
2160            let special = if self.gfm_special {
2161                maybe_special_gfm(&self.current_line, self.next_nonspace)
2162            } else {
2163                maybe_special(&self.current_line, self.next_nonspace)
2164            };
2165            if !self.indented && !special {
2166                self.advance_next_nonspace();
2167                break;
2168            }
2169
2170            let mut i = 0;
2171            while i < Self::BLOCK_STARTS {
2172                match self.block_start(i, container) {
2173                    StartResult::Container => {
2174                        container = self.open_tip();
2175                        break;
2176                    }
2177                    StartResult::Leaf => {
2178                        container = self.open_tip();
2179                        matched_leaf = true;
2180                        break;
2181                    }
2182                    StartResult::None => i += 1,
2183                }
2184            }
2185
2186            if i == Self::BLOCK_STARTS {
2187                // Nothing matched: the rest of the line is plain text.
2188                self.advance_next_nonspace();
2189                break;
2190            }
2191        }
2192
2193        // Step 3: whatever is left of the line is text for the deepest open
2194        // block.
2195        if !self.all_closed && !self.blank && self.node_type(self.open_tip()) == NodeType::Paragraph
2196        {
2197            // Lazy continuation (section 5.1 rule 2): the markers are
2198            // missing but an open paragraph absorbs the line anyway, and
2199            // its containers stay open.
2200            self.add_line();
2201            self.prev_line_length = length_before_this_line;
2202            self.last_line_length = char_count(ln);
2203            return;
2204        }
2205
2206        self.close_unmatched_blocks();
2207
2208        if self.blank {
2209            if let Some(last) = self.tree.get(container).last_child {
2210                self.tree.get_mut(last).last_line_blank = true;
2211            }
2212        }
2213
2214        let t = self.node_type(container);
2215
2216        // A block quote line is never blank (it has a `>`), blank lines
2217        // inside fenced code do not affect list looseness, and an item's own
2218        // first blank line is part of the item, not a separator.
2219        let last_line_blank = self.blank && {
2220            let node = self.tree.get(container);
2221            !(t == NodeType::BlockQuote
2222                || (t == NodeType::CodeBlock && node.is_fenced)
2223                || (t == NodeType::Item
2224                    && node.first_child.is_none()
2225                    && node.sourcepos[0][0] == self.line_number))
2226        };
2227
2228        // Propagate up: a container whose last line was blank ends with a
2229        // blank line.
2230        let mut cont = Some(container);
2231        while let Some(id) = cont {
2232            let node = self.tree.get_mut(id);
2233            node.last_line_blank = last_line_blank;
2234            cont = node.parent;
2235        }
2236
2237        if accepts_lines(t) {
2238            self.add_line();
2239            // Section 4.6: HTML block types 1 to 5 end on the line that
2240            // contains their closing string, which may be the line that
2241            // opened them.
2242            if t == NodeType::HtmlBlock {
2243                let kind = self.html_block_type(container);
2244                if (1..=5).contains(&kind)
2245                    && html_block_closes(&self.current_line[self.offset..], kind)
2246                {
2247                    self.last_line_length = char_count(ln);
2248                    self.finalize(container, self.line_number);
2249                }
2250            }
2251        } else if self.offset < self.current_line.len() && !self.blank {
2252            // Nowhere else for the text to go: open a paragraph for it.
2253            self.add_child(NodeType::Paragraph, self.offset);
2254            self.advance_next_nonspace();
2255            self.add_line();
2256        }
2257
2258        self.prev_line_length = length_before_this_line;
2259        self.last_line_length = char_count(ln);
2260    }
2261
2262    /// Feed every line of `input` and finish. An empty document still
2263    /// incorporates one empty line, exactly as the historical split-based
2264    /// loop did: line count and sourcepos depend on it. Line cutting and
2265    /// section 2.3 NUL replacement both live in `segment_next_line`.
2266    pub fn parse(mut self, input: &str) -> (Tree, RefMap) {
2267        if input.is_empty() {
2268            self.incorporate_line("");
2269        } else {
2270            let mut pos = 0;
2271            while let Some(seg) = segment_next_line(input, pos) {
2272                self.incorporate_line(&seg.text);
2273                pos = seg.next;
2274            }
2275        }
2276        self.finish()
2277    }
2278
2279    /// Close every still-open block and stamp the parse-time `gfm` flag.
2280    /// `line_number` is the count of incorporated lines, so an incremental
2281    /// driver (one that feeds `incorporate_line` itself instead of calling
2282    /// `parse`) finishes with exactly the same finalization the batch loop
2283    /// gets.
2284    pub fn close_all(&mut self) {
2285        while let Some(tip) = self.tip {
2286            self.finalize(tip, self.line_number);
2287        }
2288        self.tree.get_mut(self.doc).gfm = self.options.gfm;
2289    }
2290
2291    /// [`BlockParser::close_all`], then the tree and the link reference
2292    /// map.
2293    pub fn finish(mut self) -> (Tree, RefMap) {
2294        self.close_all();
2295        (self.tree, self.refmap)
2296    }
2297}
2298
2299// --- GFM task list items ----------------------------------------------------
2300
2301/// The task list item marker: optional spaces, `[`, either a whitespace
2302/// character or `x`/`X`, `]`, and then at least one whitespace character
2303/// before any other content. Returns the character between the brackets
2304/// and the byte length of the whole marker.
2305///
2306/// The trailing whitespace is required by the extension ("...and at least
2307/// one whitespace character before any other content"), so `- [x]` with
2308/// nothing after it is an ordinary item whose text is `[x]`. It is matched
2309/// as a space or a tab rather than as any whitespace: a line ending there
2310/// would mean the content starts on the *next* line, and consuming it would
2311/// swallow the paragraph's first soft break.
2312pub fn task_list_marker(s: &str) -> Option<(u8, usize)> {
2313    let bytes = s.as_bytes();
2314    let mut i = 0;
2315    while i < bytes.len() && bytes[i] == b' ' {
2316        i += 1;
2317    }
2318    if i >= bytes.len() || bytes[i] != b'[' {
2319        return None;
2320    }
2321    i += 1;
2322    if i >= bytes.len() {
2323        return None;
2324    }
2325    let state = bytes[i];
2326    if state != b' ' && state != b'\t' && state != b'x' && state != b'X' {
2327        return None;
2328    }
2329    i += 1;
2330    if i >= bytes.len() || bytes[i] != b']' {
2331        return None;
2332    }
2333    i += 1;
2334
2335    let spaces = i;
2336    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
2337        i += 1;
2338    }
2339    if i == spaces {
2340        return None;
2341    }
2342    Some((state, i))
2343}
2344
2345/// Phase 1: build the block tree and collect link reference definitions.
2346/// Paragraph and heading text is left raw in `string_content` for phase 2.
2347pub fn parse_blocks(input: &str, options: Options) -> (Tree, RefMap) {
2348    BlockParser::new(options).parse(input)
2349}
2350
2351#[cfg(test)]
2352mod tests {
2353    use super::*;
2354
2355    #[test]
2356    fn atx_closing_sequences() {
2357        assert_eq!(strip_atx_closing("Hello ###"), "Hello");
2358        assert_eq!(strip_atx_closing("###"), "");
2359        assert_eq!(strip_atx_closing("Hello #x"), "Hello #x");
2360        assert_eq!(strip_atx_closing("Hello ###  "), "Hello");
2361        assert_eq!(strip_atx_closing("a ## b ##"), "a ## b");
2362        assert_eq!(strip_atx_closing("foo#"), "foo#");
2363        assert_eq!(strip_atx_closing("  ###  "), "");
2364        assert_eq!(strip_atx_closing(""), "");
2365    }
2366
2367    #[test]
2368    fn trailing_blank_runs() {
2369        assert_eq!(trailing_blank_run_start(b"a\n  \n"), 1);
2370        assert_eq!(trailing_blank_run_start(b"a\nb"), 3);
2371        assert_eq!(trailing_blank_run_start(b""), 0);
2372    }
2373
2374    /// How many arena slots a driver that releases each block it has
2375    /// written leaves, after `copies` copies of `unit`: the slots a block at
2376    /// the top gives back at its close, and those of the blocks the phase
2377    /// dropped, are filled again (tabnas/markdown#100).
2378    fn slots_after(unit: &str, copies: usize) -> usize {
2379        let mut bp = BlockParser::new(Options::default());
2380        bp.events = Some(Vec::new());
2381        let doc: String = unit.repeat(copies);
2382        let lines: Vec<&str> = doc.split_inclusive('\n').collect();
2383        for (i, line) in lines.iter().enumerate() {
2384            bp.incorporate_line(line.strip_suffix('\n').unwrap_or(line));
2385            if i + 1 == lines.len() {
2386                bp.close_all();
2387            }
2388            for event in bp.events.replace(Vec::new()).unwrap_or_default() {
2389                if let BlockEvent::Close(id) = event {
2390                    if bp.is_top_level(id) || bp.tree.get(id).parent.is_none() {
2391                        bp.release_block(id);
2392                    }
2393                }
2394            }
2395            for block in std::mem::take(&mut bp.dropped) {
2396                bp.release_block(block);
2397            }
2398        }
2399        bp.tree.len()
2400    }
2401
2402    #[test]
2403    fn a_driver_that_releases_written_blocks_keeps_the_arena_bounded() {
2404        for unit in [
2405            "Paragraph text.\n\n",
2406            "- one\n- two\n\n  more\n\npara\n\n",
2407            "> quote\n> - item\n\n",
2408            "Title\n=====\n\n",
2409            "| a | b |\n| - | - |\n| 1 | 2 |\n\n",
2410            "[x]: /url\n\n```\ncode\n```\n\n<div>\nhtml\n</div>\n\n***\n\n",
2411        ] {
2412            let few = slots_after(unit, 10);
2413            let many = slots_after(unit, 100);
2414            assert_eq!(
2415                few, many,
2416                "{unit:?}: {few} slots after 10 copies, {many} after 100"
2417            );
2418        }
2419    }
2420}