diff --git a/.github/scripts/check-production-line-limit.sh b/.github/scripts/check-production-line-limit.sh index 539b37cd37..4417f3231f 100755 --- a/.github/scripts/check-production-line-limit.sh +++ b/.github/scripts/check-production-line-limit.sh @@ -28,9 +28,9 @@ ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}" # path -> removal issue declare -A GRANDFATHERED=( - # 5,325 production lines when the guard landed; split tracked by - # https://github.com/developing-today/code/issues/4704 - ["pkgs/id/src/web/markdown.rs"]="https://github.com/developing-today/code/issues/4704" + # (empty: the last two entries were removed by their splits -- + # world_session/mod.rs by its #4717 split on main, web/markdown.rs + # by the #4704 split in this branch.) ) # Count production lines of one file: every line that is not part of diff --git a/.github/scripts/check-production-line-limit.test.sh b/.github/scripts/check-production-line-limit.test.sh index 2f72f585b5..d261bc5b11 100755 --- a/.github/scripts/check-production-line-limit.test.sh +++ b/.github/scripts/check-production-line-limit.test.sh @@ -27,12 +27,15 @@ gen() { # gen [test-lines] mkdir -p "$TMP/ok/pkgs/id/src/web" gen "$TMP/ok/pkgs/id/src/small.rs" 100 gen "$TMP/ok/pkgs/id/src/long_with_tests.rs" 100 5000 -# The real grandfathered path, over the limit: warning, not failure. -gen "$TMP/ok/pkgs/id/src/web/markdown.rs" 3000 +# The grandfather list is empty (world_session/mod.rs entry removed by +# its #4717 split on main; web/markdown.rs entry removed by the #4704 +# split), so the compliant tree carries no grandfathered file. If a +# future PR adds an entry, restore the fixture here: gen a 3000-line +# file at the grandfathered path and grep the guard output for +# "GRANDFATHERED ". bash "$SCRIPT" "$TMP/ok" >"$TMP/ok.out" -grep -q "GRANDFATHERED pkgs/id/src/web/markdown.rs" "$TMP/ok.out" grep -q "production-line-guard: OK" "$TMP/ok.out" -echo "pass: compliant tree passes, grandfather reported" +echo "pass: compliant tree passes" # Violating tree: one synthetic over-limit production file. mkdir -p "$TMP/bad/pkgs/id/src" diff --git a/doc/2026-11-11T03-19-54Z_refactor_markdown_module_split/2026-11-11T03-19-54Z_refactor_markdown_module_split.md b/doc/2026-11-11T03-19-54Z_refactor_markdown_module_split/2026-11-11T03-19-54Z_refactor_markdown_module_split.md new file mode 100644 index 0000000000..f6b06e1ffc --- /dev/null +++ b/doc/2026-11-11T03-19-54Z_refactor_markdown_module_split/2026-11-11T03-19-54Z_refactor_markdown_module_split.md @@ -0,0 +1,108 @@ +# Refactor record: split of `pkgs/id/src/web/markdown.rs` (#4704) + +## Request and intent + +Issue #4704: `pkgs/id/src/web/markdown.rs` held 6,273 production lines at +the split's base (5,325 when the F11.10 guard landed), far over the +2,500 production-line limit enforced by +`.github/scripts/check-production-line-limit.sh` (#1411). The file was +carried on the guard's grandfather list; the issue asks for a +behavior-preserving split into cohesive modules below the limit and +removal of only this file's grandfather entry in the same change. The +entries for #4715 (cli.rs), #4716 (web/routes), and #4717 +(world_session) are separate issues and are not this change's business. + +This record was written at review time (Codex finding on PR #8404 +noted the missing dated record). The decisions below are the ones the +split in PR #8404 actually implements; the module inventory in the +module header of `web/markdown.rs` carries the same map in brief. + +## Approach + +Split along the codec's existing pipeline seams, moving code verbatim — +no logic changes in the split commits. Anything a moved item referenced +across a new module boundary gained `pub(crate)` visibility, and the +root module re-exports the moved items, so the crate-visible and +public API surface is unchanged. + +## Module boundaries + +- `web/markdown/markdown_scan.rs` (1,282 production lines) — source + scans over raw markdown text: fence and HTML-block tracking, + container prefixes, and the footnote / link-reference source scans + that run before parsing. +- `web/markdown/parse_helpers.rs` (1,281 production lines) — parse-side + helpers: link reference definitions, footnote synthesis, destination + protection, and table code-span escapes. +- `web/markdown/prosemirror_json.rs` (1,479 production lines) — + ProseMirror JSON construction from the CommonMark AST + (`convert_node`, inline/list conversion, placement validation). +- `web/markdown/markdown_serialization.rs` (1,072 production lines) — + the save direction: `prosemirror_to_markdown` and its rendering + helpers, including hard-break placement normalization. +- `web/markdown.rs` (root, ~1,176 production lines) — keeps the public + API, `json_to_ast`, the module declarations and re-exports, and the + test module. + +Every resulting production file is at or below the 2,500-line limit. + +## Visibility decisions + +- Moved items are `pub(crate)` at most; nothing became `pub` that was + not already reachable through the root module's re-exports. The split + widens visibility only across the new intra-crate module boundaries, + never across the crate boundary. +- Helpers shared by exactly one consumer module moved with that + consumer (e.g. the fence-placeholder helpers live with serialization, + their only caller). Helpers used by the root's retained code stayed + reachable via the root's re-exports rather than duplicating code. + +## Guard changes + +- The `pkgs/id/src/web/markdown.rs` grandfather entry is removed from + `.github/scripts/check-production-line-limit.sh` in the same PR. +- The guard's contract-test example for a grandfathered path moved to + a path that remains grandfathered (originally `pkgs/id/src/cli.rs`, + #4715). + +## Verification (at split time) + +- `cargo check --lib --features web,sandbox,ssh,world` in `pkgs/id` — + clean (after the #8355 commit below). +- `cargo test --lib --features web web::markdown` — 266 passed, + 0 failed (the full existing markdown suite, unchanged). +- The line guard over the tree: no markdown file flagged; the guard's + contract tests (`check-production-line-limit.test.sh`) pass. + +Also in PR #8404, as a separate first commit: the one-character +`serve.rs` typo fix for #8355 (`_started_server_config`), which broke +every web+world build on the then-current main — the split's +verification could not compile without it. + +--- + +## 2026-11-11T03-19-54Z Update: merge with main and review record + +While PR #8404 waited, main moved: cli.rs was split for #4715 (its +grandfather entry removed), the identical #8355 typo fix landed as +85deec737d, and the #1002 blockquote blank-line fix added helpers and +a test inside the monolith. The PR branch merged main (afb8c9800e) +with these resolutions: + +- Guard list: both removals combined — only the #4717 + `world_session/mod.rs` entry remains. The contract-test grandfather + example now uses `pkgs/id/src/world_session/mod.rs`. +- The #1002 helpers (`is_blank_quote_line`, `is_quote_content_line`, + `strip_leading_blank_quote_lines`) and their `prosemirror_to_markdown` + call site were ported byte-identical into `markdown_serialization.rs` + (their consumer's module); the #1002 round-trip test and the test + module's `clippy::panic` allow were ported into the root test module; + main's panic-safe char read in `escape_code_span_pipes_in_line` was + ported into `parse_helpers.rs`. +- Re-verified after the merge: `cargo test --lib --features web + web::markdown` — 267 passed, 0 failed (266 + the ported #1002 test); + guard contract tests all pass; the guard over the merged tree flags + only the four over-limit files that current main itself already + fails on (fleet-queue `client.rs` and `turso_queue.rs`, id + `serve.rs` and `directory.rs`) — pre-existing on main, unchanged by + this PR. diff --git a/pkgs/id/src/web/markdown.rs b/pkgs/id/src/web/markdown.rs index 2ac59faf34..f198766bd5 100644 --- a/pkgs/id/src/web/markdown.rs +++ b/pkgs/id/src/web/markdown.rs @@ -247,5176 +247,16 @@ fn strip_quote_depth(line: &str, depth: usize) -> Option<&str> { Some(rest) } -/// Fence tracking for the source scans below: a fence opens with a -/// run of >= 3 backticks or tildes and closes only with a run of the -/// SAME character at least as long (CommonMark) -- a three-backtick -/// line inside a four-backtick block is content, not a close (Codex -/// P2 on the first #1565 cut, which toggled on any fence-shaped line). -#[derive(Default)] -struct FenceTracker { - open: Option<(char, usize)>, -} - -/// The line to feed the FenceTracker: a fence delimiter may sit -/// up to three columns in from its container's content edge -/// (CommonMark), but strip_container_prefixes leaves those columns -/// in place (`> ```` arrives as two leading spaces), and -/// FenceTracker::feed anchors the run at the first character -- so -/// an indented opening fence inside a blockquote was missed and -/// the "code" interior was scanned as live text (Codex P2 on -/// #1565's twenty-fourth cut). Removing up to three leading spaces -/// here keeps the four-column distinction: a line still indented -/// after this (or tab-led, which is four columns at column 0) -/// reaches the tracker space-led and opens no fence, exactly like -/// indented code. -fn fence_feed_line(line: &str) -> &str { - let spaces = line.chars().take_while(|&c| c == ' ').count().min(3); - &line[spaces..] -} - -impl FenceTracker { - /// Feed one line (already stripped of up to three leading - /// spaces). Returns true when the line is a fence delimiter. - fn feed(&mut self, stripped: &str) -> bool { - let ch = match stripped.chars().next() { - Some(c @ ('`' | '~')) => c, - _ => return false, - }; - let run = stripped.chars().take_while(|&c| c == ch).count(); - if run < 3 { - return false; - } - if self.open.is_none() && ch == '`' && stripped[run..].contains('`') { - // A backtick fence's info string cannot contain a - // backtick (CommonMark), so a line like ```a`b opens - // no fence at all (Codex P2 on #1565's eighth cut). - return false; - } - match self.open { - None => { - self.open = Some((ch, run)); - true - } - Some((open_ch, open_run)) => { - if ch == open_ch && run >= open_run && stripped[run..].trim().is_empty() { - self.open = None; - true - } else { - false - } - } - } - } - - fn in_fence(&self) -> bool { - self.open.is_some() - } - - /// Forget any open fence: a fence opened inside a container - /// ends implicitly when the container ends, with no closing - /// delimiter line (Codex P2 on #1565's tenth cut). - fn reset(&mut self) { - self.open = None; - } -} - -/// HTML-block tracking for the source scans below (Codex P2 on -/// #1565's second cut): comrak parses a raw HTML block -- a comment, -/// a script/pre/style/textarea element, a block-level tag, or a lone -/// complete tag -- as literal content until its CommonMark end -/// condition (the closing marker for comments/CDATA/PIs/tag-bodies, -/// a blank line for plain block tags). A definition-shaped line in -/// that interior is literal text, exactly as in a fence; without this -/// tracking the pre-scan synthesized a live footnote out of a -/// comment's interior and a save then moved it outside the comment. -#[derive(Default)] -struct HtmlBlockTracker { - /// What ends the open block: a literal closing marker, or a - /// blank line for block-tag (type 6/7) blocks. - end: Option, -} - -#[derive(Clone, Copy, PartialEq)] -enum HtmlBlockEnd { - Marker(&'static str), - BlankLine, -} - -/// The CommonMark type-6 block-level tag names. -const HTML_BLOCK_TAGS: &[&str] = &[ - "address", - "article", - "aside", - "base", - "basefont", - "blockquote", - "body", - "caption", - "center", - "col", - "colgroup", - "dd", - "details", - "dialog", - "dir", - "div", - "dl", - "dt", - "fieldset", - "figcaption", - "figure", - "footer", - "form", - "frame", - "frameset", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "head", - "header", - "hr", - "html", - "iframe", - "legend", - "li", - "link", - "main", - "menu", - "menuitem", - "nav", - "noframes", - "ol", - "optgroup", - "option", - "p", - "param", - "search", - "section", - "summary", - "table", - "tbody", - "td", - "tfoot", - "th", - "thead", - "title", - "tr", - "track", - "ul", -]; - -/// Whether `trimmed` (a whole line, both ends trimmed) is exactly -/// one complete HTML open or closing tag -- CommonMark type 7: a -/// tag name (a letter, then letters/digits/`-`), then for an open -/// tag any number of whitespace-separated attributes (a name, with -/// an optional `=` and an unquoted, single-quoted, or -/// double-quoted value), optional whitespace, an optional `/`, -/// and the final `>`. A closing tag is ``. Anything else angle-delimited is NOT a tag: -/// an autolink like `` (the `:` after the -/// name is not whitespace, `/`, or `>`), or a tag-shaped line with -/// junk where an attribute should be. Treating every -/// angle-delimited string as an HTML block opened a -/// blank-line-ended block on the autolink line and swallowed the -/// heading and the valid orphan definition after it (Codex P2 on -/// #1565's seventeenth cut). -fn is_complete_html_tag(trimmed: &str) -> bool { - let bytes = trimmed.as_bytes(); - if bytes.len() < 3 || bytes[0] != b'<' || bytes[bytes.len() - 1] != b'>' { - return false; - } - let inner = &trimmed[1..trimmed.len() - 1]; - let b = inner.as_bytes(); - let (closing, mut pos) = if b.first() == Some(&b'/') { - (true, 1) - } else { - (false, 0) - }; - if !b.get(pos).is_some_and(|c| c.is_ascii_alphabetic()) { - return false; - } - let name_start = pos; - pos += 1; - while b - .get(pos) - .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-') - { - pos += 1; - } - // Type 1 names never open a type 7 block with an OPENING tag - // (they are handled as marker-ended blocks above); a line - // naming one that reaches here did not match the type-1 - // boundary rule either. The exclusion applies only to opening - // tags: a complete CLOSING tag of any name opens a type-7 - // block, so `` makes the following definition-shaped - // line its literal interior -- rejecting it recovered that - // line as a live definition (Codex P2 on #1565's - // twenty-first cut). - if !closing - && ["script", "pre", "style", "textarea"] - .contains(&inner[name_start..pos].to_ascii_lowercase().as_str()) - { - return false; - } - if closing { - while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { - pos += 1; - } - return pos == inner.len(); - } - loop { - let ws_start = pos; - while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { - pos += 1; - } - let had_ws = pos > ws_start; - match b.get(pos) { - None => return true, - Some(b'/') => return pos + 1 == inner.len(), - Some(_) if had_ws => { - // Attribute name, then an optional `= value`. - if !b - .get(pos) - .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_' || *c == b':') - { - return false; - } - pos += 1; - while b.get(pos).is_some_and(|c| { - c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b':') - }) { - pos += 1; - } - let mut p2 = pos; - while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { - p2 += 1; - } - if b.get(p2) == Some(&b'=') { - p2 += 1; - while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { - p2 += 1; - } - match b.get(p2) { - Some(q @ (b'"' | b'\'')) => { - let q = *q; - p2 += 1; - while b.get(p2).is_some_and(|c| *c != q) { - p2 += 1; - } - if b.get(p2).is_none() { - return false; - } - p2 += 1; - } - Some(_) => { - let vstart = p2; - while b.get(p2).is_some_and(|c| { - !c.is_ascii_whitespace() - && !matches!(c, b'"' | b'\'' | b'=' | b'<' | b'>' | b'`') - }) { - p2 += 1; - } - if p2 == vstart { - return false; - } - } - None => return false, - } - pos = p2; - } - } - Some(_) => return false, - } - } -} - -impl HtmlBlockTracker { - fn in_html(&self) -> bool { - self.end.is_some() - } - - /// Forget any open block: a block opened inside a container - /// ends implicitly when the container ends, with no closing - /// line (Codex P2 on #1565's eleventh cut, mirroring - /// FenceTracker::reset). - fn reset(&mut self) { - self.end = None; - } - - /// Feed one line (already stripped of up to three leading - /// spaces). Returns true when the line belongs to an HTML block - /// (its opening line, interior, or closing line). - /// `may_open_type7` is the caller's paragraph context: a type-7 - /// block (a lone complete inline tag) cannot interrupt a - /// paragraph, so when the previous line is paragraph content - /// the caller passes false and a type-7 opening is refused - /// (Codex P2 on #1565's eighteenth cut). Types 1-6 can - /// interrupt a paragraph and are always eligible. - fn feed(&mut self, stripped: &str, may_open_type7: bool) -> bool { - if let Some(end) = self.end { - match end { - HtmlBlockEnd::Marker(marker) => { - if stripped.to_ascii_lowercase().contains(marker) { - self.end = None; - } - } - HtmlBlockEnd::BlankLine => { - if stripped.trim().is_empty() { - self.end = None; - } - } - } - return true; - } - let Some(rest) = stripped.strip_prefix('<') else { - return false; - }; - let lower = stripped.to_ascii_lowercase(); - // Marker-ended blocks (CommonMark types 1-5). The tag-named - // prefixes require a name boundary: `` is not a - // `
` block (nor `` a `"),
-            (""),
-            (""),
-            (""),
-        ] {
-            // The tag-named prefixes follow the CommonMark type-1
-            // boundary exactly: whitespace, '>', or end-of-line
-            // after the name. Anything else (`
`, ``)
-            // is a generic tag block ending at a blank line, not a
-            // marker-ended block (Codex P2 on #1565's tenth cut).
-            let boundary_ok = !prefix[1..].chars().all(|c| c.is_ascii_alphabetic())
-                || match lower.as_bytes().get(prefix.len()) {
-                    None => true,
-                    Some(b) => b.is_ascii_whitespace() || *b == b'>',
-                };
-            // CDATA is case-sensitive (CommonMark): only the
-            // exact uppercase `').
-            if !rest.contains('>') {
-                self.end = Some(HtmlBlockEnd::Marker(">"));
-            }
-            return true;
-        }
-        // Tag-ended blocks (types 6 and 7): a block-level tag, or a
-        // lone complete open/closing tag on the line.
-        let tag_body = rest.strip_prefix('/').unwrap_or(rest);
-        let tag_name: String = tag_body
-            .chars()
-            .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
-            .collect::()
-            .to_ascii_lowercase();
-        if tag_name.is_empty() {
-            return false;
-        }
-        if HTML_BLOCK_TAGS.contains(&tag_name.as_str())
-            && tag_name_boundary_ok(tag_body, tag_name.len())
-        {
-            self.end = Some(HtmlBlockEnd::BlankLine);
-            return true;
-        }
-        let trimmed = stripped.trim_end();
-        if is_complete_html_tag(trimmed) {
-            if !may_open_type7 {
-                return false;
-            }
-            self.end = Some(HtmlBlockEnd::BlankLine);
-            return true;
-        }
-        let _ = rest;
-        false
-    }
-}
-
-/// Strip block-container prefixes (blockquote `>`, list markers
-/// `-`/`*`/`+`/ordered) from a line, repeatedly, for fence detection:
-/// a fence opened inside a list item or blockquote still makes its
-/// content literal (Codex P2 on #1565's fourth cut -- `- ```` followed
-/// by an indented definition-shaped line parsed as code by comrak,
-/// but the scanner missed the opening fence behind the `- ` marker
-/// and recovered the interior line as a live definition).
-fn strip_container_prefixes(line: &str) -> &str {
-    let mut rest = line;
-    loop {
-        let t = rest.trim_start_matches(' ');
-        if let Some(r) = t.strip_prefix('>') {
-            rest = r.strip_prefix(' ').unwrap_or(r);
-            continue;
-        }
-        let bytes = t.as_bytes();
-        let marker_len = if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            Some(1)
-        } else {
-            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-            if digits >= 1
-                && digits <= 9
-                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-            {
-                Some(digits + 1)
-            } else {
-                None
-            }
-        };
-        let Some(marker_len) = marker_len else { break };
-        rest = strip_marker_padding(&t[marker_len..], marker_len);
-    }
-    rest
-}
-
-/// The content after a list marker, CommonMark-style: one to
-/// four columns of padding after the marker are the item's
-/// content indent and are stripped with the marker; FIVE or
-/// more columns mean the content is an indented code block
-/// whose indentation starts after a single padding column, so
-/// only that one column is stripped and the remaining
-/// indentation survives. Removing all the padding turned
-/// `-     ``` ` into a fence opener the document does not have,
-/// and the phantom fence then suppressed the valid reference
-/// definition after it (Codex P2 on #1565's twenty-first cut).
-fn strip_marker_padding(after: &str, marker_end_col: usize) -> &str {
-    let mut col = marker_end_col;
-    let mut end = 0;
-    for c in after.chars() {
-        match c {
-            ' ' => {
-                col += 1;
-                end += 1;
-            }
-            '\t' => {
-                col += 4 - (col % 4);
-                end += 1;
-            }
-            _ => break,
-        }
-    }
-    if col - marker_end_col > 4 {
-        // Keep all but the first padding character (spaces and
-        // tabs are one byte each, so this is a byte offset too).
-        &after[after.chars().next().map_or(0, |_| 1)..]
-    } else {
-        &after[end..]
-    }
-}
-
-/// The container structure of a recorded container prefix, as
-/// a string of marker kinds with all spacing removed: `> ` and
-/// `>` are the same blockquote level, so a fence opened under
-/// one spelling closes under the other (Codex P2 on #1565's
-/// nineteenth cut). Byte-exact prefix matching left such a
-/// fence open and suppressed the definitions after it.
-fn container_signature(prefix: &str) -> String {
-    let mut sig = String::new();
-    let mut rest = prefix;
-    loop {
-        let t = rest.trim_start_matches([' ', '\t']);
-        if let Some(r) = t.strip_prefix('>') {
-            sig.push('>');
-            rest = r;
-            continue;
-        }
-        let bytes = t.as_bytes();
-        if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            sig.push('*');
-            rest = &t[1..];
-            continue;
-        }
-        let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-        if digits >= 1
-            && digits <= 9
-            && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-            && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-        {
-            sig.push('#');
-            rest = &t[digits + 1..];
-            continue;
-        }
-        break;
-    }
-    sig
-}
-
-/// Strip at most `levels` container levels (blockquote `>`,
-/// list markers) from a line, mirroring
-/// strip_container_prefixes' per-level shapes.
-fn strip_container_levels(line: &str, levels: usize) -> &str {
-    let mut rest = line;
-    for _ in 0..levels {
-        let t = rest.trim_start_matches(' ');
-        if let Some(r) = t.strip_prefix('>') {
-            rest = r.strip_prefix(' ').unwrap_or(r);
-            continue;
-        }
-        let bytes = t.as_bytes();
-        let marker_len = if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            Some(1)
-        } else {
-            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-            if digits >= 1
-                && digits <= 9
-                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-            {
-                Some(digits + 1)
-            } else {
-                None
-            }
-        };
-        let Some(marker_len) = marker_len else { break };
-        rest = strip_marker_padding(&t[marker_len..], marker_len);
-    }
-    rest
-}
-
-/// Whether `stripped` (a line stripped of up to three leading
-/// spaces) carries the recorded container `prefix`, matched
-/// STRUCTURALLY rather than byte-for-byte: the line's own
-/// leading container levels (as many as the recorded prefix
-/// has) must have the same signature as the recorded prefix.
-fn carries_container_prefix(stripped: &str, prefix: &str) -> bool {
-    if prefix.is_empty() {
-        return false;
-    }
-    let levels = container_signature(prefix).chars().count();
-    if levels == 0 {
-        return false;
-    }
-    let own = &stripped[..stripped.len() - strip_container_levels(stripped, levels).len()];
-    !own.is_empty() && container_signature(own) == container_signature(prefix)
-}
-
-/// A footnote definition block found by the source pre-scan (#1565):
-/// its label and the block's verbatim source (the `[^label]:` line
-/// plus any indented continuation lines, trailing blank lines cut).
-struct FootnoteDefinitionBlock {
-    label: String,
-    source: String,
-    /// Zero-based line index of the definition's opening line, for
-    /// interleaving with other source segments in document order.
-    line: usize,
-}
-
-/// The label of a footnote definition starting on `line` (already
-/// stripped of up to three leading spaces), or `None` when the line
-/// does not start one. A definition opens as `[^label]:`.
-fn footnote_definition_label(line: &str) -> Option {
-    let rest = line.strip_prefix("[^")?;
-    // The label ends at the FIRST ']' and a ':' must follow it
-    // immediately. Searching for "]:" instead accepted `a]b` as the
-    // label of `[^a]b]: note` -- a definition comrak does not
-    // recognize, whose probe then looped recovery forever (Codex P1).
-    let close = rest.find(']')?;
-    if !rest[close + 1..].starts_with(':') {
-        return None;
-    }
-    let label = &rest[..close];
-    if label.is_empty() || label.contains('[') {
-        return None;
-    }
-    Some(label.to_string())
-}
-
-/// A thematic break: at least three of the same `-`, `*`, or `_`,
-/// spaces and tabs aside (CommonMark).
-fn is_thematic_break(stripped: &str) -> bool {
-    let compact: String = stripped
-        .chars()
-        .filter(|c| *c != ' ' && *c != '\t')
-        .collect();
-    let first = compact.chars().next();
-    compact.len() >= 3
-        && matches!(first, Some('-' | '*' | '_'))
-        && compact.chars().all(|c| Some(c) == first)
-}
-
-/// A setext heading underline: only `=`s (level 1) or `-`s (level 2).
-fn is_setext_underline(stripped: &str) -> bool {
-    let t = stripped.trim();
-    (!t.is_empty() && t.chars().all(|c| c == '=')) || (!t.is_empty() && t.chars().all(|c| c == '-'))
-}
-
-/// Whether a line starts a new block and so cannot be a lazy
-/// paragraph continuation of a footnote definition: another
-/// definition, an ATX heading, a fence, a blockquote, a thematic
-/// break, an HTML block opener, or a list/blockquote container line.
-/// Whether a line is an ATX heading: 1-6 `#`s followed by a
-/// space, a tab, or end-of-line (CommonMark). `#hashtag` is
-/// paragraph text, not a heading (Codex P2 on #1565's tenth cut).
-fn is_atx_heading(stripped: &str) -> bool {
-    let hashes = stripped.bytes().take_while(|&b| b == b'#').count();
-    (1..=6).contains(&hashes)
-        && matches!(
-            stripped.as_bytes().get(hashes),
-            None | Some(b' ') | Some(b'\t')
-        )
-}
-
-/// Whether the character after a block-level tag name is a valid
-/// name boundary: whitespace, `/`, `>`, or end-of-line (CommonMark
-/// type 6). `` has no boundary after `div`, so it is
-/// literal paragraph text, not an HTML block (Codex P2 on
-/// #1565's sixteenth cut).
-fn tag_name_boundary_ok(tag_body: &str, name_len: usize) -> bool {
-    matches!(
-        tag_body.as_bytes().get(name_len),
-        None | Some(b' ') | Some(b'\t') | Some(b'>') | Some(b'/')
-    )
-}
-
-/// Whether a line opens an HTML block that can INTERRUPT a
-/// paragraph (CommonMark types 1-6): a comment, a CDATA section,
-/// a processing instruction, a declaration, a script/pre/style/
-/// textarea element, or a block-level tag (opening or closing).
-/// A lone inline tag (``, ``) is type 7, which cannot
-/// interrupt a paragraph: as a footnote definition's next line it
-/// is a lazy continuation of the definition's paragraph, not a
-/// new block (Codex P2 on #1565's eleventh cut).
-fn is_html_block_start(stripped: &str) -> bool {
-    let Some(rest) = stripped.strip_prefix('<') else {
-        return false;
-    };
-    let lower = stripped.to_ascii_lowercase();
-    if lower.starts_with(" comments, and the split sibling lists this
-        // change emits are adjacent by construction - so on reparse the
-        // separator comes back as an HtmlBlock between the lists. It is
-        // a separator, not content: drop it when a neighbouring sibling
-        // is a list. An authored  comment NOT next to
-        // a list still converts exactly as before (an htmlBlock
-        // code_block, #982).
-        if is_end_list_separator(child)
-            && ((idx > 0 && matches!(children[idx - 1].data.borrow().value, NodeValue::List(_)))
-                || children
-                    .get(idx + 1)
-                    .is_some_and(|c| matches!(c.data.borrow().value, NodeValue::List(_))))
-        {
-            continue;
-        }
-        if matches!(child.data.borrow().value, NodeValue::List(_)) {
-            // #1370: a list converts to one or more sibling lists.
-            out.extend(convert_list_runs(child));
-        } else {
-            let converted = convert_node(child, &[]);
-            if !converted.is_null() {
-                out.push(converted);
-            }
-        }
-    }
-    out
-}
-
-/// True for the HtmlBlock comrak's renderer emits between adjacent
-/// lists (see collect_block_children).
-fn is_end_list_separator<'a>(node: &'a AstNode<'a>) -> bool {
-    match &node.data.borrow().value {
-        NodeValue::HtmlBlock(html) => html.literal.trim() == "",
-        _ => false,
-    }
-}
-
-/// Convert a comrak list node to one or more ProseMirror list nodes.
-///
-/// A pure list converts exactly as before (#997/#1036 attrs carried from
-/// the source list). #1370: a list mixing task items with plain items
-/// used to take its type from the first child only and convert the rest
-/// by their own kind, producing a `task_list` holding a `list_item` (or
-/// a plain list holding a `task_list_item`) - a shape the save-side
-/// placement validation and the editor schema both forbid, so the
-/// document could not be saved at all. Instead, group the items into
-/// runs of one kind and emit one sibling list per run, in source order.
-/// Ordered runs carry an `order` start offset by the items before them
-/// so numbering renders unchanged; `tight` is carried from the source
-/// list to every run. Placement validation and the editor schema are
-/// untouched: every emitted list is pure.
-/// #1380: the PM `delimiter` attr spelling for a comrak ordered-list
-/// delimiter (`.` vs `)`). The editor schema mirrors these spellings.
-fn delimiter_attr(delimiter: ListDelimType) -> &'static str {
-    match delimiter {
-        ListDelimType::Period => "period",
-        ListDelimType::Paren => "paren",
-    }
-}
-
-/// #1380: read the PM `delimiter` attr back to a comrak delimiter.
-/// Absent or unknown (legacy PM docs stored by the old codec, which
-/// dropped the delimiter) defaults to Period - exactly how the old
-/// codec saved every ordered list.
-fn delimiter_from_attrs(json: &Value) -> ListDelimType {
-    match json["attrs"]["delimiter"].as_str() {
-        Some("paren") => ListDelimType::Paren,
-        _ => ListDelimType::Period,
-    }
-}
-
-fn convert_list_runs<'a>(node: &'a AstNode<'a>) -> Vec {
-    let (list_type, start, tight, delimiter) = match &node.data.borrow().value {
-        NodeValue::List(list) => (list.list_type, list.start, list.tight, list.delimiter),
-        _ => return Vec::new(),
-    };
-    // (is_task, items before this run, converted items)
-    let mut runs: Vec<(bool, usize, Vec)> = Vec::new();
-    let mut seen = 0usize;
-    for child in node.children() {
-        let is_task = matches!(child.data.borrow().value, NodeValue::TaskItem(_));
-        let item = convert_node(child, &[]);
-        if item.is_null() {
-            continue;
-        }
-        match runs.last_mut() {
-            Some((kind, _, items)) if *kind == is_task => items.push(item),
-            _ => runs.push((is_task, seen, vec![item])),
-        }
-        seen += 1;
-    }
-    runs.into_iter()
-        .map(|(is_task, offset, content)| match (is_task, list_type) {
-            (true, ListType::Ordered) => json!({
-                "type": "task_list",
-                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
-                "content": content
-            }),
-            (true, ListType::Bullet) => json!({
-                "type": "task_list",
-                "attrs": {"tight": tight},
-                "content": content
-            }),
-            (false, ListType::Ordered) => json!({
-                "type": "ordered_list",
-                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
-                "content": content
-            }),
-            (false, ListType::Bullet) => json!({
-                "type": "bullet_list",
-                "attrs": {"tight": tight},
-                "content": content
-            }),
-        })
-        .collect()
-}
-
-/// Collect list item children of a list node.
-#[allow(dead_code)]
-fn collect_list_items<'a>(node: &'a AstNode<'a>) -> Vec {
-    node.children()
-        .map(|child| convert_node(child, &[]))
-        .filter(|v| !v.is_null())
-        .collect()
-}
-
-/// The literal of an `HtmlInline` node, if `node` is one.
-fn html_inline_literal<'a>(node: &'a AstNode<'a>) -> Option {
-    if let NodeValue::HtmlInline(html) = &node.data.borrow().value {
-        Some(html.clone())
-    } else {
-        None
-    }
-}
-
-/// Detect the split sized-linked-image sequence at the head of `children`
-/// (#893): an `` `HtmlInline`, an `` `HtmlInline`,
-/// and the closing `` `HtmlInline`. Comrak splits the HTML form the
-/// save direction emits for a sized linked image into those three sibling
-/// nodes; merged here they become one image node carrying `linkHref`, and
-/// neither anchor piece falls through as literal text. The closing tag is
-/// optional in the match (consumed when present) so a missing one cannot
-/// strand the opening tag as text either. Returns the merged image node
-/// and how many siblings it consumed.
-fn linked_image_sequence<'a>(children: &[&'a AstNode<'a>]) -> Option<(Value, usize)> {
-    if children.len() < 2 {
-        return None;
-    }
-    let (href, link_title) = parse_anchor_tag(&html_inline_literal(children[0])?)?;
-    let img = parse_img_tag(&html_inline_literal(children[1])?)?;
-    let consumed = if children.len() >= 3
-        && html_inline_literal(children[2]).is_some_and(|h| h.trim().eq_ignore_ascii_case(""))
-    {
-        3
-    } else {
-        2
-    };
-    Some((image_with_link(img, &href, link_title.as_deref()), consumed))
-}
-
-/// Collect inline children of a node, flattening nested mark wrappers.
-fn collect_inline_children<'a>(node: &'a AstNode<'a>, active_marks: &[Mark]) -> Vec {
-    let mut result = Vec::new();
-    let children: Vec<&AstNode<'a>> = node.children().collect();
-    let mut index = 0;
-
-    while index < children.len() {
-        // #893: merge a split  sequence before the pieces
-        // are converted individually (see linked_image_sequence).
-        if let Some((img, consumed)) = linked_image_sequence(&children[index..]) {
-            result.push(img);
-            index += consumed;
-            continue;
-        }
-
-        let child = children[index];
-        index += 1;
-        let child_data = child.data.borrow();
-
-        // Check if this is a mark wrapper (Emph, Strong, Link)
-        let is_mark_wrapper = matches!(
-            child_data.value,
-            NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough
-        );
-        drop(child_data);
-
-        let converted = convert_node(child, active_marks);
-        if is_mark_wrapper {
-            // Convert returns an array of children with marks applied
-            if let Some(arr) = converted.as_array() {
-                for item in arr {
-                    if !item.is_null() {
-                        result.push(item.clone());
-                    }
-                }
-            }
-        } else if !converted.is_null() {
-            result.push(converted);
-        }
-    }
-
-    result
-}
-
-/// Get all text content from a node and its descendants.
-fn get_text_content<'a>(node: &'a AstNode<'a>) -> String {
-    let mut text = String::new();
-    collect_text(node, &mut text);
-    text
-}
-
-/// Recursively collect text from a node.
-fn collect_text<'a>(node: &'a AstNode<'a>, text: &mut String) {
-    let data = node.data.borrow();
-
-    match &data.value {
-        NodeValue::Text(t) => text.push_str(t.as_ref()),
-        NodeValue::Code(c) => text.push_str(&c.literal),
-        NodeValue::SoftBreak => text.push(' '),
-        NodeValue::LineBreak => text.push('\n'),
-        _ => {
-            drop(data);
-            for child in node.children() {
-                collect_text(child, text);
-            }
-        }
-    }
-}
-
-/// #1417: serialize an image alt subtree back to markdown form.
-///
-/// The inverse of the save direction's alt re-parse: emphasis, strong,
-/// strikethrough, code spans and links keep their markup; literal text
-/// is escaped so characters that were literal in the source (e.g. an
-/// escaped `\\*`) stay literal when the stored form is re-parsed on
-/// save. Nested images/links inside an alt are serialized recursively,
-/// so a nested-link alt round-trips instead of flattening.
-fn get_alt_markdown<'a>(node: &'a AstNode<'a>) -> String {
-    let mut out = String::new();
-    for child in node.children() {
-        collect_alt_markdown(child, &mut out);
-    }
-    out
-}
-
-fn collect_alt_markdown<'a>(node: &'a AstNode<'a>, out: &mut String) {
-    let data = node.data.borrow();
-    match &data.value {
-        NodeValue::Text(t) => {
-            for ch in t.chars() {
-                if matches!(ch, '\\' | '*' | '_' | '`' | '[' | ']') {
-                    out.push('\\');
-                }
-                out.push(ch);
-            }
-        }
-        NodeValue::Code(c) => {
-            // Fence with one more backtick than the longest run inside.
-            let longest = c
-                .literal
-                .split(|ch| ch != '`')
-                .map(str::len)
-                .max()
-                .unwrap_or(0);
-            let fence = "`".repeat(longest + 1);
-            out.push_str(&fence);
-            if c.literal.starts_with('`') || c.literal.ends_with('`') {
-                out.push(' ');
-                out.push_str(&c.literal);
-                out.push(' ');
-            } else {
-                out.push_str(&c.literal);
-            }
-            out.push_str(&fence);
-        }
-        NodeValue::SoftBreak => out.push(' '),
-        NodeValue::LineBreak => out.push('\n'),
-        NodeValue::HtmlInline(html) => out.push_str(html),
-        NodeValue::Emph => {
-            drop(data);
-            out.push('*');
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push('*');
-        }
-        NodeValue::Strong => {
-            drop(data);
-            out.push_str("**");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("**");
-        }
-        NodeValue::Strikethrough => {
-            drop(data);
-            out.push_str("~~");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("~~");
-        }
-        NodeValue::Link(link) => {
-            let url = link.url.clone();
-            let title = link.title.clone();
-            drop(data);
-            out.push('[');
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("](");
-            out.push_str(&url);
-            if !title.is_empty() {
-                out.push_str(" \"");
-                out.push_str(&title.replace('"', "\\\""));
-                out.push_str("\"");
-            }
-            out.push(')');
-        }
-        NodeValue::Image(link) => {
-            let url = link.url.clone();
-            let title = link.title.clone();
-            drop(data);
-            out.push_str("![");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("](");
-            out.push_str(&url);
-            if !title.is_empty() {
-                out.push_str(" \"");
-                out.push_str(&title.replace('"', "\\\""));
-                out.push_str("\"");
-            }
-            out.push(')');
-        }
-        _ => {
-            drop(data);
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-        }
-    }
-}
-
-/// #1417: re-parse a stored markdown-form alt into inline AST nodes in
-/// `arena` (the save direction). Returns the paragraph's children,
-/// detached and ready to append under an Image node. Falls back to a
-/// single plain Text node when the alt does not parse to a paragraph
-/// (defensive; plain alts parse to exactly that anyway).
-fn alt_markdown_to_nodes<'a>(arena: &'a Arena<'a>, alt: &str) -> Vec<&'a AstNode<'a>> {
-    let options = commonmark_options();
-    let root = parse_document(arena, alt, &options);
-    if let Some(paragraph) = root
-        .children()
-        .find(|n| matches!(n.data.borrow().value, NodeValue::Paragraph))
-    {
-        let nodes: Vec<&'a AstNode<'a>> = paragraph.children().collect();
-        for n in &nodes {
-            n.detach();
-        }
-        if !nodes.is_empty() {
-            return nodes;
-        }
-    }
-    vec![&*arena.alloc(AstNode::from(NodeValue::Text(alt.to_owned().into())))]
-}
-
-/// Escape a value for a double-quoted HTML attribute (#873): `&` first, so
-/// the entities introduced here are not themselves re-escaped, then the
-/// quote that would terminate the value, and `<`.
-fn escape_attr_value(value: &str) -> String {
-    value
-        .replace('&', "&")
-        .replace('"', """)
-        .replace('<', "<")
-}
-
-/// Decode the entities [`escape_attr_value`] can emit (plus `>`/`'`
-/// and numeric single-quote) in one left-to-right pass, so `&quot;`
-/// decodes to the literal text `"`, never to `"`.
-fn decode_attr_entities(value: &str) -> String {
-    if !value.contains('&') {
-        return value.to_owned();
-    }
-    let mut out = String::with_capacity(value.len());
-    let mut rest = value;
-    while let Some(idx) = rest.find('&') {
-        out.push_str(&rest[..idx]);
-        let tail = &rest[idx..];
-        let (decoded, len) = if let Some(t) = tail.strip_prefix(""") {
-            ('"', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("&") {
-            ('&', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("<") {
-            ('<', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix(">") {
-            ('>', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("'") {
-            ('\'', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("'") {
-            ('\'', tail.len() - t.len())
-        } else {
-            out.push('&');
-            rest = &tail[1..];
-            continue;
-        };
-        out.push(decoded);
-        rest = &tail[len..];
-    }
-    out.push_str(rest);
-    out
-}
-
-/// Parse the attributes of an HTML tag, starting just past its ` std::collections::HashMap {
-    let bytes = html.as_bytes();
-    let mut pos = tag_len;
-    let mut map = std::collections::HashMap::new();
-    while pos < bytes.len() {
-        // Skip separators between attributes (whitespace, '/' of '/>').
-        while pos < bytes.len() && (bytes[pos].is_ascii_whitespace() || bytes[pos] == b'/') {
-            pos += 1;
-        }
-        if pos >= bytes.len() || bytes[pos] == b'>' {
-            break;
-        }
-        // Attribute name: up to '=', whitespace, '/' or '>'.
-        let name_start = pos;
-        while pos < bytes.len()
-            && !bytes[pos].is_ascii_whitespace()
-            && !matches!(bytes[pos], b'=' | b'/' | b'>')
-        {
-            pos += 1;
-        }
-        if pos == name_start {
-            break;
-        }
-        let name = html[name_start..pos].to_ascii_lowercase();
-        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
-            pos += 1;
-        }
-        let mut value = String::new();
-        if pos < bytes.len() && bytes[pos] == b'=' {
-            pos += 1;
-            while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
-                pos += 1;
-            }
-            if pos < bytes.len() && matches!(bytes[pos], b'"' | b'\'') {
-                let quote = bytes[pos];
-                pos += 1;
-                let value_start = pos;
-                while pos < bytes.len() && bytes[pos] != quote {
-                    pos += 1;
-                }
-                value = decode_attr_entities(&html[value_start..pos]);
-                if pos < bytes.len() {
-                    pos += 1; // closing quote
-                }
-            } else {
-                let value_start = pos;
-                while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b'>' {
-                    pos += 1;
-                }
-                value = decode_attr_entities(&html[value_start..pos]);
-            }
-        }
-        // First occurrence wins (HTML duplicate-attribute rule).
-        map.entry(name).or_insert(value);
-    }
-    map
-}
-
-/// Parse an `` width/height value into a pixel count (#2180,
-/// grammar pinned by triage task 3225). The whole stack is
-/// numeric-pixel -- the PM node stores a JSON number, the emitter
-/// writes bare integers, the editor renders `${width}px` -- so only
-/// lossless normalizations are accepted: trim surrounding
-/// whitespace, strip ONE trailing `px` suffix (ASCII
-/// case-insensitive), then the rest must be a pixel integer, where a
-/// decimal form counts only when its value is exactly integral
-/// (`200.0` -> 200, `200.5` refused). Percents, other units, and
-/// junk return `None`; the caller warns instead of dropping the
-/// value silently, as the pre-#2180 bare-`u64` parse did.
-fn parse_integral_decimal(raw: &str) -> Option {
-    let (negative, raw) = if let Some(raw) = raw.strip_prefix('-') {
-        (true, raw)
-    } else {
-        (false, raw.strip_prefix('+').unwrap_or(raw))
-    };
-
-    let (mantissa, exponent) = if let Some(index) = raw.find(|ch| matches!(ch, 'e' | 'E')) {
-        (&raw[..index], raw[index + 1..].parse::().ok()?)
-    } else {
-        (raw, 0)
-    };
-    let (integer, fractional) = mantissa.split_once('.').unwrap_or((mantissa, ""));
-    if integer.is_empty() && fractional.is_empty() {
-        return None;
-    }
-    if !integer.bytes().all(|byte| byte.is_ascii_digit())
-        || !fractional.bytes().all(|byte| byte.is_ascii_digit())
-    {
-        return None;
-    }
-
-    let mut digits = String::with_capacity(integer.len() + fractional.len());
-    digits.push_str(integer);
-    digits.push_str(fractional);
-    let significant = digits.trim_start_matches('0');
-    if significant.is_empty() {
-        // Keep the exact zero spellings accepted by the former float parser,
-        // including -0.0, without converting through f64.
-        return Some(0);
-    }
-
-    let fractional_digits = i32::try_from(fractional.len()).ok()?;
-    let scale = exponent.checked_sub(fractional_digits)?;
-    let integer = if scale >= 0 {
-        let trailing_zeroes = usize::try_from(scale).ok()?;
-        if significant.len().checked_add(trailing_zeroes)? > 20 {
-            return None;
-        }
-        let mut integer = String::with_capacity(significant.len() + trailing_zeroes);
-        integer.push_str(significant);
-        integer.push_str(&"0".repeat(trailing_zeroes));
-        integer.parse::().ok()?
-    } else {
-        let trailing_zeroes = usize::try_from(scale.checked_neg()?).ok()?;
-        if trailing_zeroes > significant.len() {
-            return None;
-        }
-        let split = significant.len() - trailing_zeroes;
-        if significant[split..].bytes().any(|byte| byte != b'0') {
-            return None;
-        }
-        significant[..split].parse::().ok()?
-    };
-
-    if negative && integer != 0 {
-        return None;
-    }
-    Some(integer)
-}
-
-fn parse_dimension(raw: &str) -> Option {
-    let trimmed = raw.trim();
-    // Byte-wise suffix check: slicing the string at len()-2 to test
-    // the suffix would panic when that offset falls inside a multibyte
-    // UTF-8 character (e.g. fullwidth digits). When the last two bytes
-    // are the ASCII bytes p/x, len()-2 is a char boundary, so the
-    // slice below is safe.
-    let bytes = trimmed.as_bytes();
-    let body = if bytes.len() >= 2 && bytes[bytes.len() - 2..].eq_ignore_ascii_case(b"px") {
-        &trimmed[..trimmed.len() - 2]
-    } else {
-        trimmed
-    };
-    if let Ok(n) = body.parse::() {
-        return Some(n);
-    }
-    parse_integral_decimal(body)
-}
-
-/// Parse an HTML `` tag and extract attributes into a `ProseMirror` image node.
-///
-/// Returns `Some(json)` if the input looks like ``, otherwise `None`.
-fn find_ascii_case_insensitive(haystack: &str, needle: &[u8]) -> Option {
-    haystack
-        .as_bytes()
-        .windows(needle.len())
-        .position(|candidate| candidate.eq_ignore_ascii_case(needle))
-}
-
-fn parse_img_tag(html: &str) -> Option {
-    let trimmed = html.trim();
-    let bytes = trimmed.as_bytes();
-    if !bytes
-        .get(..4)
-        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"'
-        )
-    {
-        return None;
-    }
-
-    let parsed = parse_tag_attrs(trimmed, 4);
-    let attr = |name: &str| parsed.get(name).map(String::as_str);
-
-    let src = sanitize_image_url(attr("src")?); // src is required
-    let mut attrs = json!({"src": src});
-
-    if let Some(alt) = attr("alt") {
-        attrs["alt"] = json!(alt);
-    }
-    if let Some(title) = attr("title") {
-        attrs["title"] = json!(title);
-    }
-    if let Some(w) = attr("width") {
-        match parse_dimension(w) {
-            Some(n) => attrs["width"] = json!(n),
-            None => tracing::warn!("dropping unsupported image width {w:?} in  import"),
-        }
-    }
-    if let Some(h) = attr("height") {
-        match parse_dimension(h) {
-            Some(n) => attrs["height"] = json!(n),
-            None => tracing::warn!("dropping unsupported image height {h:?} in  import"),
-        }
-    }
-
-    Some(json!({
-        "type": "image",
-        "attrs": attrs
-    }))
-}
-
-/// #5745: the allowed-scheme oracle for link URLs.
-///
-/// A link URL is safe iff, after removing the characters browsers strip
-/// while parsing a URL (TAB/LF/CR anywhere, leading C0 controls and
-/// spaces), it either has no scheme at all — a relative or internal
-/// reference, a fragment, a query, or a protocol-relative `//host/path`
-/// reference, none of which can name an executable scheme — or its
-/// scheme is exactly `http`, `https`, or `mailto` (case-insensitive).
-/// Everything else (`javascript:`, `data:`, `vbscript:`, any unknown
-/// scheme, and any obfuscation of those the stripping above exposes)
-/// is unsafe. This explicit allowed set is the oracle every link test
-/// for #5745 checks against; do not rely on browser sanitization.
-fn link_url_is_safe(url: &str) -> bool {
-    let probe: String = url
-        .chars()
-        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
-        .collect();
-    let probe = probe.trim_start_matches(|c: char| c.is_ascii_control() || c == ' ');
-    // A scheme exists only when a `:` precedes any `/`, `?`, or `#`.
-    let mut scheme_end = None;
-    for (i, c) in probe.char_indices() {
-        match c {
-            ':' => {
-                scheme_end = Some(i);
-                break;
-            }
-            '/' | '?' | '#' => break,
-            _ => {}
-        }
-    }
-    let Some(colon) = scheme_end else {
-        return true; // no scheme: relative / fragment / query / protocol-relative
-    };
-    let scheme = &probe[..colon];
-    let mut chars = scheme.chars();
-    let valid_scheme = !scheme.is_empty()
-        && chars.next().is_some_and(|c| c.is_ascii_alphabetic())
-        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
-    if !valid_scheme {
-        // A `:` in the first segment whose prefix is not a scheme
-        // (e.g. a relative path containing a colon) is not a scheme.
-        return true;
-    }
-    matches!(
-        scheme.to_ascii_lowercase().as_str(),
-        "http" | "https" | "mailto"
-    )
-}
-
-/// #5745: return `url` unchanged when [`link_url_is_safe`], else the
-/// inert fragment `"#"`. The link text and mark survive; only the
-/// executable target is removed, and `"#"` re-parses as a safe
-/// fragment, so sanitized documents are a stable round-trip fixpoint.
-fn sanitize_link_url(url: &str) -> String {
-    if link_url_is_safe(url) {
-        url.to_owned()
-    } else {
-        "#".to_owned()
-    }
-}
-
-/// #6364: the image-specific allowed-scheme oracle.
-///
-/// Image URLs allow relative/internal references and `http`/`https`, plus
-/// data URLs whose media type is one of the supported raster formats. SVG is
-/// deliberately excluded because it can contain active content. As with
-/// links, inspect the scheme after stripping TAB/LF/CR and leading C0
-/// controls/spaces so browser URL parsing cannot expose an obfuscated scheme.
-fn image_url_is_safe(url: &str) -> bool {
-    let probe: String = url
-        .chars()
-        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
-        .collect();
-    let probe = probe.trim_start_matches(|c: char| c.is_ascii_control() || c == ' ');
-
-    // A scheme exists only when a `:` precedes any `/`, `?`, or `#`.
-    let mut scheme_end = None;
-    for (i, c) in probe.char_indices() {
-        match c {
-            ':' => {
-                scheme_end = Some(i);
-                break;
-            }
-            '/' | '?' | '#' => break,
-            _ => {}
-        }
-    }
-    let Some(colon) = scheme_end else {
-        return true;
-    };
-
-    let scheme = &probe[..colon];
-    let mut chars = scheme.chars();
-    let valid_scheme = !scheme.is_empty()
-        && chars.next().is_some_and(|c| c.is_ascii_alphabetic())
-        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
-    if !valid_scheme {
-        // Match the link oracle: a colon in a segment that is not a valid
-        // scheme (for example a relative path) does not introduce a scheme.
-        return true;
-    }
-
-    let Some((raw_scheme, _)) = url.split_once(':') else {
-        return true;
-    };
-    if raw_scheme.chars().any(|c| matches!(c, '\t' | '\n' | '\r')) {
-        return false;
-    }
-
-    let scheme = scheme.to_ascii_lowercase();
-    match scheme.as_str() {
-        "http" | "https" => true,
-        "data" => {
-            // Reject control-character spellings in the scheme or data URL
-            // header, even if removing them would produce an allowed MIME
-            // type. Controls in the encoded payload do not affect the scheme
-            // or media type and are left untouched.
-            let Some((header, _)) = url.split_once(',') else {
-                return false;
-            };
-            if header.chars().any(|c| matches!(c, '\t' | '\n' | '\r')) {
-                return false;
-            }
-            let Some((metadata, _)) = probe[colon + 1..].split_once(',') else {
-                return false;
-            };
-            let media_type = metadata.split(';').next().unwrap_or_default();
-            matches!(
-                media_type.to_ascii_lowercase().as_str(),
-                "image/png"
-                    | "image/gif"
-                    | "image/jpeg"
-                    | "image/webp"
-                    | "image/avif"
-                    | "image/bmp"
-            )
-        }
-        _ => false,
-    }
-}
-
-/// #6364: return `url` unchanged for an allowed image URL, otherwise the
-/// inert fragment `#`. Keeping only the target neutralized preserves the
-/// image node and makes the sanitized document a stable round-trip fixpoint.
-fn sanitize_image_url(url: &str) -> String {
-    if image_url_is_safe(url) {
-        url.to_owned()
-    } else {
-        "#".to_owned()
-    }
-}
-
-/// Parse an HTML `` opening tag, returning its `href` and optional
-/// `title`. Returns `None` for anything else, including an anchor with no
-/// (or an empty) `href`.
-fn parse_anchor_tag(html: &str) -> Option<(String, Option)> {
-    let trimmed = html.trim();
-    let after_name = trimmed.as_bytes().get(2).copied()?;
-    if !trimmed
-        .as_bytes()
-        .get(..2)
-        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"')
-    {
-        return None;
-    }
-    let parsed = parse_tag_attrs(trimmed, 2);
-    let href = parsed.get("href")?;
-    if href.is_empty() {
-        return None;
-    }
-    let title = parsed.get("title").filter(|t| !t.is_empty()).cloned();
-    // #5745: a raw-HTML anchor wrapping an image gets the same
-    // allowed-scheme treatment as a Markdown link; an unsafe href is
-    // neutralized (not dropped, which would strand the raw anchor tag
-    // as a verbatim html_inline atom carrying the executable URL).
-    Some((sanitize_link_url(href), title))
-}
-
-/// Attach a wrapping anchor's link to an image node (#880/#893), in the
-/// same `linkHref`/`linkTitle` attrs the markdown `Image` arm produces.
-fn image_with_link(mut img: Value, href: &str, link_title: Option<&str>) -> Value {
-    img["attrs"]["linkHref"] = json!(href);
-    if let Some(title) = link_title {
-        img["attrs"]["linkTitle"] = json!(title);
-    }
-    img
-}
-
-/// Parse the combined `` form (#893) — the
-/// sized linked image emission when comrak keeps it in a single literal
-/// (e.g. an `HtmlBlock`) instead of splitting it into sibling `HtmlInline`
-/// nodes (that split form is merged in `collect_inline_children`).
-fn parse_linked_img_tag(html: &str) -> Option {
-    let trimmed = html.trim();
-    let (href, link_title) = parse_anchor_tag(trimmed)?;
-    let img_start = find_ascii_case_insensitive(trimmed, b"')
-        || find_ascii_case_insensitive(&trimmed[img_start..], b"").is_none()
-    {
-        return None;
-    }
-    let img = parse_img_tag(&trimmed[img_start..])?;
-    Some(image_with_link(img, &href, link_title.as_deref()))
-}
-
-/// Placement categories for the #1043 validation walk. A node whose type
-/// is not listed here is left to `json_to_ast`, which reports it as
-/// `ConversionError::UnknownType` — validation never masks that error.
-/// (`front_matter` is intentionally unlisted: its doc-first-child rule
-/// needs the child index, so `validate_placement` checks it directly.)
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum Placement {
-    /// Block-level node (`paragraph`, `table`, lists, …).
-    Block,
-    /// Inline node (`text`, `image`, `hard_break`, …).
-    Inline,
-    /// `list_item` — only legal directly inside a bullet/ordered list.
-    ListItem,
-    /// `task_list_item` — only legal directly inside a `task_list`.
-    TaskListItem,
-    /// `table_row` — only legal directly inside a `table`.
-    TableRow,
-    /// `table_header` / `table_cell` — only legal inside a `table_row`.
-    TableCell,
-}
-
-fn placement_of(node_type: &str) -> Option {
-    match node_type {
-        "paragraph"
-        | "heading"
-        | "blockquote"
-        | "code_block"
-        | "horizontal_rule"
-        | "bullet_list"
-        | "ordered_list"
-        | "task_list"
-        | "table"
-        | "footnote_definition" => Some(Placement::Block),
-        "text" | "image" | "hard_break" | "html_inline" | "footnote_reference" => {
-            Some(Placement::Inline)
-        }
-        "list_item" => Some(Placement::ListItem),
-        "task_list_item" => Some(Placement::TaskListItem),
-        "table_row" => Some(Placement::TableRow),
-        "table_header" | "table_cell" => Some(Placement::TableCell),
-        _ => None,
-    }
-}
-
-/// Whether a child of category `child` may appear directly inside a
-/// parent of type `parent`. Mirrors the comrak AST containment rules for
-/// the node kinds this codec emits, at the `ProseMirror` level.
-fn placement_allowed(parent: &str, child: Placement) -> bool {
-    match parent {
-        // The document and block containers hold blocks only.
-        "doc" | "blockquote" | "list_item" | "task_list_item" => child == Placement::Block,
-        // Inline containers hold inline content only.
-        "paragraph" | "heading" => child == Placement::Inline,
-        "bullet_list" | "ordered_list" => child == Placement::ListItem,
-        "task_list" => child == Placement::TaskListItem,
-        "table" => child == Placement::TableRow,
-        "table_row" => child == Placement::TableCell,
-        // PM table cells wrap blocks (unwrapped during conversion) and
-        // footnote definitions carry inline content on the PM side
-        // (re-wrapped during conversion, #945); both shapes are legal.
-        "table_header" | "table_cell" | "footnote_definition" => {
-            child == Placement::Block || child == Placement::Inline
-        }
-        "code_block" => false,
-        // Inline leaves and anything unlisted impose no child rules here;
-        // structural surprises inside them are json_to_ast's to report.
-        _ => true,
-    }
-}
-
-/// Validate block/inline placement over a `ProseMirror` document before
-/// conversion (#1043). `json_to_ast` places any known node type anywhere;
-/// a misplaced node (a `text` node directly under `doc`, a `paragraph`
-/// inside a `paragraph`, …) produces an ill-formed comrak AST that
-/// panics the formatter in debug builds and silently emits invalid
-/// markdown in release builds. Reject those documents up front with
-/// `ConversionError::MisplacedNode` instead.
-fn validate_placement(doc: &Value) -> Result<(), ConversionError> {
-    fn walk(
-        node: &Value,
-        parent: Option<&str>,
-        index_in_parent: Option,
-    ) -> Result<(), ConversionError> {
-        let Some(node_type) = node["type"].as_str() else {
-            // Missing type: json_to_ast reports MissingType; keep that
-            // error's precedence.
-            return Ok(());
-        };
-        // #1369: `front_matter` is legal only as the first child of `doc`
-        // (comrak only parses it there). Anything else is misplaced.
-        if node_type == "front_matter" {
-            let first_child_of_doc = parent == Some("doc") && index_in_parent == Some(0);
-            if !first_child_of_doc {
-                return Err(ConversionError::MisplacedNode {
-                    parent: parent.unwrap_or("").to_owned(),
-                    child: node_type.to_owned(),
-                });
-            }
-        } else if let Some(parent_type) = parent
-            && let Some(category) = placement_of(node_type)
-            && !placement_allowed(parent_type, category)
-        {
-            return Err(ConversionError::MisplacedNode {
-                parent: parent_type.to_owned(),
-                child: node_type.to_owned(),
-            });
-        }
-        // code_block content is literal text children only.
-        if node_type == "code_block" {
-            if let Some(content) = node["content"].as_array() {
-                for child in content {
-                    if child["type"].as_str() != Some("text") {
-                        return Err(ConversionError::MisplacedNode {
-                            parent: node_type.to_owned(),
-                            child: child["type"].as_str().unwrap_or("").to_owned(),
-                        });
-                    }
-                }
-            }
-            return Ok(());
-        }
-        // front_matter carries no PM child content (its payload is the
-        // `text` attr); nothing to recurse into.
-        if node_type == "front_matter" {
-            if node["content"].as_array().is_some_and(|c| !c.is_empty()) {
-                return Err(ConversionError::MisplacedNode {
-                    parent: node_type.to_owned(),
-                    child: "".to_owned(),
-                });
-            }
-            return Ok(());
-        }
-        if let Some(content) = node["content"].as_array() {
-            for (idx, child) in content.iter().enumerate() {
-                walk(child, Some(node_type), Some(idx))?;
-            }
-        }
-        Ok(())
-    }
-    walk(doc, None, None)
-}
-
-/// Convert `ProseMirror` JSON document to markdown text.
-///
-/// Unknown marks are skipped by design (#1045): marks outside the
-/// codec's vocabulary (`em`, `strong`, `strikethrough`, `link`, plus
-/// the `code` mark handled specially by `create_marked_text`) are
-/// dropped while the marked text itself is kept verbatim. This
-/// differs from unknown *nodes*, which return
-/// `ConversionError::UnknownType`, because an unknown inline style
-/// can be shed without corrupting the document text. Known marks
-/// render byte-identically whether or not unknown marks are present.
-///
-/// # Arguments
-///
-/// * `doc` - The `ProseMirror` JSON document.
-///
-/// # Returns
-///
-/// The markdown text, or an error if conversion fails.
-///
-/// # Errors
-///
-/// Returns `ConversionError` if the JSON structure is invalid.
-pub fn prosemirror_to_markdown(doc: &Value) -> Result {
-    validate_placement(doc)?;
-    let arena = Arena::new();
-    let root = json_to_ast(&arena, doc)?;
-    // #1418: hoist delimiter-mark edge spaces that a word character
-    // touches out of their wrappers, before rendering (see
-    // `hoist_delimiter_edge_spaces`).
-    hoist_delimiter_edge_spaces(&arena, root);
-    // #1496: force info-less code blocks inside blockquotes onto the
-    // renderer's fenced branch via a placeholder info string, stripped
-    // from the rendered output below (see
-    // `force_fenced_code_blocks_in_blockquotes`).
-    let fence_tokens = force_fenced_code_blocks_in_blockquotes(root);
-    // #1019: comrak's renderer percent-encodes a space in a link/image
-    // destination (`my notes.md` -> `my%20notes.md`) instead of emitting
-    // the <...> angle form, silently breaking relative file links and
-    // mutating the PM href on reparse. #1423: the same mangling hits the
-    // other whitespace characters — a tab is encoded to %09 and a newline
-    // destroys the link outright (`% `). The renderer has no angle-form
-    // option, so swap each whitespace-carrying destination for a unique
-    // placeholder before rendering and restore it as 
-    // afterwards.
-    let substitutions = substitute_spaced_destinations(root);
-    let mut output = String::new();
-    format_commonmark(root, &commonmark_options(), &mut output)?;
-    for (placeholder, raw) in substitutions {
-        output = output.replace(&placeholder, &format!("<{raw}>"));
-    }
-    for token in fence_tokens {
-        output = strip_fence_placeholder(&output, &token);
-    }
-    // #1002: collapse the renderer's stray blank lines at the top of a
-    // quote (see `strip_leading_blank_quote_lines`). Stripping runs first
-    // so a quote-leading GitHub alert marker becomes the quote's first
-    // content line for the restore below.
-    let output = strip_leading_blank_quote_lines(&output);
-    let output = restore_github_alert_markers(&output);
-    Ok(strip_end_list_separators(doc, &output))
-}
-
-/// Undo the CommonMark renderer's escaping of a GitHub alert marker when
-/// the marker is the first content of its blockquote. Markers elsewhere
-/// (for example, followed by words on the same line) remain ordinary
-/// escaped text. GitHub requires the marker to be the first thing in the
-/// blockquote.
-///
-/// The scan skips fenced code blocks and raw HTML blocks: those are
-/// literal content, so a line like `> \[\!NOTE\]` inside one is authored
-/// text, not a renderer-escaped marker, and rewriting it would silently
-/// change the code (Codex P2 on the first cut).
-fn restore_github_alert_markers(markdown: &str) -> String {
-    let mut output = String::with_capacity(markdown.len());
-    let mut quote_has_content = [false; 64];
-    let mut fence = FenceTracker::default();
-    let mut fence_depth: Option = None;
-    let mut html = HtmlBlockTracker::default();
-    let mut html_depth: Option = None;
-    let mut at_block_start = true;
-
-    for line in markdown.split_inclusive('\n') {
-        let content_start = line.trim_start_matches(' ');
-        let leading_spaces = line.len() - content_start.len();
-        let (depth, rest) = split_quote_prefix(content_start);
-
-        // Four columns of indentation is code, and the markers below only
-        // apply inside a blockquote. A quote nested deeper than the table
-        // is left untouched rather than risking an out-of-range walk.
-        if leading_spaces > 3 || depth >= quote_has_content.len() {
-            quote_has_content.fill(false);
-            fence.reset();
-            fence_depth = None;
-            html.reset();
-            html_depth = None;
-            output.push_str(line);
-            at_block_start = leading_spaces > 3 || rest.trim().is_empty();
-            continue;
-        }
-
-        // An open fence or HTML block owns every following line of its
-        // container, including lines that look like quote markers: that
-        // is exactly the literal-code case above.
-        if let Some(opened_at) = fence_depth {
-            match strip_quote_depth(content_start, opened_at) {
-                Some(body) => {
-                    fence.feed(fence_feed_line(body));
-                    if !fence.in_fence() {
-                        fence_depth = None;
-                    }
-                    output.push_str(line);
-                    at_block_start = false;
-                    continue;
-                }
-                None => {
-                    fence.reset();
-                    fence_depth = None;
-                }
-            }
-        }
-        if let Some(opened_at) = html_depth {
-            match strip_quote_depth(content_start, opened_at) {
-                Some(body) => {
-                    html.feed(body, at_block_start);
-                    if !html.in_html() {
-                        html_depth = None;
-                    }
-                    output.push_str(line);
-                    at_block_start = false;
-                    continue;
-                }
-                None => {
-                    html.reset();
-                    html_depth = None;
-                }
-            }
-        }
-
-        // A fence or HTML block opening on this line makes its interior
-        // literal from here on.
-        if fence.feed(fence_feed_line(rest)) {
-            fence_depth = Some(depth);
-            output.push_str(line);
-            at_block_start = false;
-            continue;
-        }
-        if html.feed(rest, at_block_start) {
-            html_depth = Some(depth);
-            output.push_str(line);
-            at_block_start = false;
-            continue;
-        }
-
-        // Nothing outside a blockquote can open an alert, and a line
-        // outside one ends every quote that was open.
-        if depth == 0 {
-            quote_has_content.fill(false);
-            output.push_str(line);
-            at_block_start = rest.trim().is_empty() || starts_new_block(rest);
-            continue;
-        }
-
-        for seen in quote_has_content.iter_mut().skip(depth + 1) {
-            *seen = false;
-        }
-
-        let trimmed = rest.trim();
-        // Comrak emits a hard break with a trailing backslash. Ignore that
-        // renderer syntax while recognizing the marker; the suffix is kept
-        // intact when replacing the escaped marker below.
-        let hardbreak = trimmed.ends_with('\\');
-        let marker_token = trimmed.strip_suffix('\\').unwrap_or(trimmed);
-        let marker = match marker_token {
-            r"\[\!NOTE\]" => Some("[!NOTE]"),
-            r"\[\!TIP\]" => Some("[!TIP]"),
-            r"\[\!IMPORTANT\]" => Some("[!IMPORTANT]"),
-            r"\[\!WARNING\]" => Some("[!WARNING]"),
-            r"\[\!CAUTION\]" => Some("[!CAUTION]"),
-            _ => None,
-        };
-        // A marker only opens an alert when nothing above it in the
-        // quote -- at any depth -- has content yet. Marking ancestors
-        // when a deeper line carries content keeps the marker of a
-        // later paragraph in an outer quote escaped (Codex P2).
-        let quote_is_empty = depth > 0 && !quote_has_content[..=depth].iter().any(|seen| *seen);
-        if quote_is_empty
-            && !rest.starts_with(' ')
-            && !rest.starts_with('\t')
-            && let Some(marker) = marker
-        {
-            let marker_start = line.find(marker_token).unwrap_or(0);
-            let marker_end = marker_start + marker_token.len();
-            output.push_str(&line[..marker_start]);
-            output.push_str(marker);
-            let suffix = &line[marker_end..];
-            output.push_str(if hardbreak {
-                suffix.strip_prefix('\\').unwrap_or(suffix)
-            } else {
-                suffix
-            });
-            for seen in quote_has_content.iter_mut().take(depth + 1).skip(1) {
-                *seen = true;
-            }
-        } else {
-            output.push_str(line);
-            if !trimmed.is_empty() {
-                for seen in quote_has_content.iter_mut().take(depth + 1).skip(1) {
-                    *seen = true;
-                }
-            }
-        }
-        at_block_start = trimmed.is_empty() || starts_new_block(rest);
-    }
-
-    output
-}
-
-/// The start number a PM list renders with in Markdown, when it
-/// renders as an ordered list: ordered_list always (attrs.order,
-/// default 1); a task_list only when it carries attrs.order (#1370
-/// ordered task runs render as `1. [ ]`). Bullet-rendering lists and
-/// non-lists return None.
-fn ordered_start(node: &Value) -> Option {
-    let order = node["attrs"]["order"].as_u64();
-    match node["type"].as_str() {
-        Some("ordered_list") => Some(order.unwrap_or(1)),
-        Some("task_list") => order,
-        _ => None,
-    }
-}
-
-fn list_kind(node: &Value) -> Option<&str> {
-    match node["type"].as_str() {
-        Some(k @ ("bullet_list" | "ordered_list" | "task_list")) => Some(k),
-        _ => None,
-    }
-}
-
-/// The tightness a PM list effectively renders with: the stored
-/// `attrs.tight` when present; for a legacy task_list without the
-/// attribute, the same inference json_to_ast applies (loose if any
-/// item has more than one block child, else tight); bullet/ordered
-/// lists without the attribute render loose (json_to_ast defaults
-/// them to false). Boundary decisions in collect_boundary_kinds must
-/// use this, not the raw attribute: comparing raw attrs mistook a
-/// legacy tight task list for loose (CodeRabbit review, PR #3258).
-fn effective_tight(node: &Value) -> bool {
-    if let Some(tight) = node["attrs"]["tight"].as_bool() {
-        return tight;
-    }
-    if node["type"].as_str() == Some("task_list") {
-        return !node["content"].as_array().is_some_and(|items| {
-            items.iter().any(|item| {
-                item["content"]
-                    .as_array()
-                    .is_some_and(|blocks| blocks.len() > 1)
-            })
-        });
-    }
-    false
-}
-
-/// #1397: comrak's renderer separates adjacent list siblings with an
-/// `` comment - renderer-internal markup that lands in
-/// the user's file. Where the two lists are of DIFFERENT PM kinds the
-/// comment is the only thing keeping them apart, and it is not needed:
-/// a change of list type ends a list on reparse all by itself (and the
-/// #1370 parse-side split rebuilds task/plain runs), so the separator
-/// line is dropped and the lists sit directly adjacent in the text -
-/// tight lists stay tight, loose lists keep their blank lines. Where
-/// the kinds are the SAME (two ordered lists, two task lists) dropping
-/// it would merge the lists and lose restart/order information, so the
-/// separator stays for those pairs. It also stays for a DIFFERENT-kind
-/// pair that renders as the same ordered Markdown list (an ordered_list
-/// next to a task_list carrying `attrs.order`, or vice versa) when the
-/// second list does not start exactly where the first list's numbering
-/// ends: merging those on reparse renumbers the second run and loses
-/// its restart (Codex review, PR #3258). If the lines found in the output
-/// do not line up one-to-one with the boundaries computed from the doc,
-/// the output is returned untouched.
-/// The fence run a rendered line opens or closes, if any: returns the
-/// fence character and the remainder of the line starting at the run.
-/// List-marker prefixes are stripped first (blockquote `>` markers and
-/// indentation, then bullet / ordered / task-checkbox markers, repeated
-/// for nested items), because a code block that is a list item's first
-/// block renders its opening fence immediately after the marker
-/// (`- ``` `). Plain lines return their own trimmed remainder.
-fn list_fence_rest(line: &str) -> Option<(char, &str)> {
-    let mut rest = line.trim_start_matches(['>', ' ']).trim_start();
-    loop {
-        let mut stripped = false;
-        for marker in ["- ", "+ ", "* ", "[ ] ", "[x] ", "[X] "] {
-            if let Some(r) = rest.strip_prefix(marker) {
-                rest = r.trim_start();
-                stripped = true;
-                break;
-            }
-        }
-        if stripped {
-            continue;
-        }
-        let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count();
-        if digits > 0 {
-            let after = &rest[digits..];
-            for marker in [". ", ") "] {
-                if let Some(r) = after.strip_prefix(marker) {
-                    rest = r.trim_start();
-                    stripped = true;
-                    break;
-                }
-            }
-        }
-        if !stripped {
-            break;
-        }
-    }
-    if rest.starts_with("```") {
-        Some(('`', rest))
-    } else if rest.starts_with("~~~") {
-        Some(('~', rest))
-    } else {
-        None
-    }
-}
-
-/// Whether a list's first item renders empty (no text, no block content
-/// beyond empty paragraphs): an empty list item cannot interrupt a
-/// paragraph under CommonMark, whatever its marker (Codex review,
-/// PR #3258: `- a\n\n1.\n2. b` saved without the blank reparsed the
-/// empty `1.` as lazy continuation text and lost the ordered list).
-fn list_starts_with_empty_item(list: &Value) -> bool {
-    let Some(first) = list["content"].as_array().and_then(|items| items.first()) else {
-        return false;
-    };
-    fn node_is_empty(node: &Value) -> bool {
-        if node["text"].as_str().is_some_and(|t| !t.trim().is_empty()) {
-            return false;
-        }
-        match node["type"].as_str() {
-            Some("paragraph" | "list_item" | "task_list_item" | "text") | None => {}
-            Some(_) => return false,
-        }
-        node["content"]
-            .as_array()
-            .is_none_or(|parts| parts.iter().all(node_is_empty))
-    }
-    node_is_empty(first)
-}
-
-fn strip_end_list_separators(doc: &Value, output: &str) -> String {
-    // Recompute with kinds: the drop decision needs them, so collect
-    // (prev_kind, kind, tight_pair, merge_safe, needs_blank) tuples
-    // alongside.
-    let mut kinds: Vec<(String, String, bool, bool, bool)> = Vec::new();
-    collect_boundary_kinds(doc, &mut kinds);
-    if kinds.is_empty() {
-        return output.to_string();
-    }
-    let is_separator_line =
-        |line: &str| line.trim_start_matches(['>', ' ']).trim() == "";
-    let is_blank_line = |line: &str| line.trim_start_matches(['>', ' ']).trim().is_empty();
-    let lines: Vec<&str> = output.lines().collect();
-    // Codex review, PR #3258: a separator-looking line inside a fenced
-    // code block is authored content, not renderer markup - it must
-    // neither count toward the boundary correspondence nor be dropped.
-    // Track fence state (``` / ~~~, optionally blockquote-prefixed) and
-    // only treat lines outside fences as separators.
-    let mut in_fence = false;
-    let mut fence_char = '`';
-    let mut fence_len = 0usize;
-    // Codex review, PR #3258: raw HTML blocks are literal content too.
-    // A backtick-only line inside one (e.g. a 
wrapping a ``` line) - // is not a fence opener, and a separator-looking line inside the - // block is authored HTML, not renderer markup. Track HTML block - // state (CommonMark: the block runs until a blank line; an HTML - // comment block runs until its --> closer) and exclude its lines - // from both fence tracking and separator counting. - let mut in_html = false; - let mut html_is_comment = false; - let mut is_separator: Vec = Vec::with_capacity(lines.len()); - for line in &lines { - let html_probe = line.trim_start_matches(['>', ' ']).trim(); - if in_html { - is_separator.push(false); - if html_is_comment { - if html_probe.contains("-->") { - in_html = false; - html_is_comment = false; - } - } else if html_probe.is_empty() { - in_html = false; - } - continue; - } - if !in_fence && !is_separator_line(line) { - let second = html_probe.chars().nth(1); - let opens_html = html_probe.starts_with('<') - && second.is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '/' | '!' | '?')); - if opens_html { - is_separator.push(false); - if html_probe.starts_with("") { - in_html = true; - html_is_comment = true; - } - } else { - in_html = true; - } - continue; - } - } - // Codex review, PR #3258: a fence can open immediately after a - // list marker (a list item whose first block is a code block - // renders as `- ``` `): strip any list-marker prefixes (bullet, - // ordered, task checkbox, nested) before looking for the fence - // run, or the opener is missed, the fence's literal content is - // counted as a separator, and the closing fence is mistaken - // for an opener that hides the real separator. - let fence_rest = list_fence_rest(line); - let fence_marker = fence_rest.map(|(c, _)| c); - match fence_marker { - Some(c) if !in_fence => { - in_fence = true; - fence_char = c; - fence_len = fence_rest - .map(|(_, rest)| rest.chars().take_while(|&ch| ch == c).count()) - .unwrap_or(0); - is_separator.push(false); - } - // CodeRabbit review, PR #3258: a fence closes only on a - // BARE run of the fence character at least as long as the - // opener. A content line such as ```rust starts with the - // marker but is not a closer; ending the fence there let a - // separator-looking line later in the code block be counted - // (and dropped) as renderer markup, losing authored lines. - Some(c) - if c == fence_char - && fence_rest.is_some_and(|(_, rest)| { - rest.trim_end().chars().all(|ch| ch == c) - && rest.trim_end().len() >= fence_len - }) => - { - in_fence = false; - is_separator.push(false); - } - _ => is_separator.push(!in_fence && is_separator_line(line)), - } - } - let found = is_separator.iter().filter(|b| **b).count(); - if found != kinds.len() { - return output.to_string(); - } - let mut boundary = kinds.iter(); - let mut kept: Vec<&str> = Vec::with_capacity(lines.len()); - let mut idx = 0; - while idx < lines.len() { - let line = lines[idx]; - if is_separator[idx] { - match boundary.next() { - Some((a, b, tight_pair, merge_safe, needs_blank)) if a != b && *merge_safe => { - // Drop the separator. The renderer also puts a blank - // line on each side of it; with the comment gone, - // blanks between the lists would fuse them into ONE - // loose list on reparse. A tight pair keeps no blank - // line at all; a loose pair keeps exactly one. A - // needs_blank pair also keeps exactly one: an ordered - // list starting above 1 cannot interrupt the previous - // item's paragraph, so with no blank line at all its - // first line reparses as a lazy continuation and the - // list is lost (Codex review, PR #3258). - let prev_blank = kept.last().is_some_and(|l| is_blank_line(l)); - let next_blank = lines.get(idx + 1).is_some_and(|l| is_blank_line(l)); - if prev_blank && next_blank { - if *tight_pair && !*needs_blank { - kept.pop(); - } - idx += 1; // skip the following blank line too - } - } - _ => kept.push(line), - } - } else { - kept.push(line); - } - idx += 1; - } - let mut out = kept.join("\n"); - if output.ends_with('\n') { - out.push('\n'); - } - out -} - -/// (prev PM kind, PM kind, both tight, merge-safe, needs-blank) for every list -/// adjacency in the doc, in render order, interleaved with authored -/// htmlBlocks (recorded as ("", "", false, false, false) so they consume a -/// separator-line slot but are never dropped - see -/// strip_end_list_separators' caller contract). Merge-safe is false -/// only when dropping the separator would merge two ordered-rendering -/// lists whose numbering does not continue across the boundary. -fn collect_boundary_kinds(node: &Value, out: &mut Vec<(String, String, bool, bool, bool)>) { - let Some(content) = node["content"].as_array() else { - return; - }; - let mut prev_list: Option<&Value> = None; - // Effective tight of the current consecutive bullet_list run's - // FIRST list (the tight json_to_ast's coalesce renders with). - let mut bullet_run_tight: Option = None; - for child in content { - let kind = list_kind(child); - if let (Some(prev), Some(kind)) = (prev_list, kind) - && !(list_kind(prev) == Some("bullet_list") && kind == "bullet_list") - { - // Codex review, PR #3258: when prev is a bullet_list that - // json_to_ast coalesced with earlier bullet siblings, the - // rendered list carries the FIRST sibling's tight, so the - // boundary must compare that effective tightness - the last - // original sibling's attr can differ and silently loosens - // the following run on reparse. - let prev_tight = if list_kind(prev) == Some("bullet_list") { - bullet_run_tight.unwrap_or_else(|| effective_tight(prev)) - } else { - effective_tight(prev) - }; - let child_tight = effective_tight(child); - let tight_pair = prev_tight && child_tight; - // Two lists that both render as ordered Markdown merge into - // one list on reparse if the separator goes; the merge is - // lossless only when the second list starts exactly where - // the first list's numbering ends (start + item count), so - // convert_list_runs recomputes the same run orders. - let ordered_merge_safe = match (ordered_start(prev), ordered_start(child)) { - (Some(prev_start), Some(next_start)) => { - let prev_count = prev["content"].as_array().map_or(0, |c| c.len()) as u64; - // attrs.order comes from the request's PM JSON; a - // crafted start near u64::MAX must not overflow the - // sum (debug builds panic, release builds wrap and - // could drop a separator that should stay). - prev_start.checked_add(prev_count) == Some(next_start) - } - _ => true, - }; - // Codex review, PR #3258: two lists that render as the same - // Markdown list family (bullet-rendering: bullet_list and - // order-less task_list; ordered-rendering: ordered_list and - // ordered task_list) merge into ONE list on reparse when the - // separator drops, and convert_list_runs then copies one - // run's tight onto both. When their tight attributes differ - // that silently loosens/tightens a run and breaks the save - // fixpoint, so the separator stays. Different families split - // on reparse by marker type and keep their own tightness. - let renders_ordered = |n: &Value| ordered_start(n).is_some(); - let tight_differs = prev_tight != child_tight; - let tight_merge_safe = - !(renders_ordered(prev) == renders_ordered(child) && tight_differs); - let merge_safe = ordered_merge_safe && tight_merge_safe; - // Codex review, PR #3258: an ordered-rendering list that - // starts above 1 cannot interrupt a paragraph, so when the - // previous list does not itself render ordered, the boundary - // must keep a blank line or the second list's first line - // reparses as a lazy continuation of the previous item. - // The empty-item guard (below) applies only across - // different rendered list families: within one family the - // two runs reparse as a single list, where an empty sibling - // item needs no blank - keeping one would loosen the merged - // list and break the save fixpoint (Codex review, PR #3258). - let needs_blank = (matches!(ordered_start(child), Some(start) if start != 1) - && ordered_start(prev).is_none()) - || (list_starts_with_empty_item(child) - && renders_ordered(prev) != renders_ordered(child)); - out.push(( - list_kind(prev).unwrap_or_default().to_string(), - kind.to_string(), - tight_pair, - merge_safe, - needs_blank, - )); - } - if child["type"].as_str() == Some("code_block") - && child["attrs"]["htmlBlock"].as_bool() == Some(true) - && child["content"].as_array().is_some_and(|parts| { - parts - .iter() - .filter_map(|n| n["text"].as_str()) - .collect::() - .trim() - == "" - }) - { - out.push((String::new(), String::new(), false, false, false)); - } - // Codex review, PR #3258: lists inside a table cell are - // flattened to text by append_table_cell_child and emit no - // separator, so boundaries collected there have no line in - // the output to correspond to - skip the cell's subtree. - if !matches!(child["type"].as_str(), Some("table_header" | "table_cell")) { - collect_boundary_kinds(child, out); - } - if kind.is_some() { - if kind == Some("bullet_list") { - if prev_list.is_none_or(|p| list_kind(p) != Some("bullet_list")) { - bullet_run_tight = Some(effective_tight(child)); - } - } else { - bullet_run_tight = None; - } - prev_list = Some(child); - } else { - prev_list = None; - bullet_run_tight = None; - } - } -} - - -/// Whether a node value is a delimiter-mark wrapper (#1418): the -/// marks whose markdown spelling is a delimiter run (`*`/`**`/`~~`) -/// subject to CommonMark flanking rules. Link (bracket syntax) and -/// code (backtick syntax) tolerate edge spaces and are excluded. -fn is_delimiter_wrapper(value: &NodeValue) -> bool { - matches!( - value, - NodeValue::Emph | NodeValue::Strong | NodeValue::Strikethrough - ) -} - -/// The first text leaf of a mark chain, descending first children -/// through mark wrappers (#1418). `None` when the first inline is -/// anything else (an image or html node is a different mechanism — -/// #1407/#1412 — and keeps the legacy behaviour). -fn first_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> { - let mut current = node; - loop { - let child = current.first_child()?; - let value = child.data.borrow().value.clone(); - match value { - NodeValue::Text(_) => return Some(child), - _ if is_mark_wrapper(&value) => current = child, - _ => return None, - } - } -} - -/// The last text leaf of a mark chain; mirror of `first_text_leaf`. -fn last_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> { - let mut current = node; - loop { - let child = current.last_child()?; - let value = child.data.borrow().value.clone(); - match value { - NodeValue::Text(_) => return Some(child), - _ if is_mark_wrapper(&value) => current = child, - _ => return None, - } - } -} - -/// The last character a node renders as inline content (#1418): -/// text/code literals verbatim, breaks as whitespace, mark wrappers -/// by their last inline descendant. Anything else yields `None` -/// (treated as a non-word neighbour). -fn last_rendered_char(node: &AstNode<'_>) -> Option { - match &node.data.borrow().value { - NodeValue::Text(literal) => literal.to_string().chars().last(), - NodeValue::Code(code) => code.literal.chars().last(), - NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'), - value if is_mark_wrapper(value) => node.last_child().and_then(last_rendered_char), - _ => None, - } -} - -/// The first character a node renders as; mirror of -/// `last_rendered_char`. -fn first_rendered_char(node: &AstNode<'_>) -> Option { - match &node.data.borrow().value { - NodeValue::Text(literal) => literal.to_string().chars().next(), - NodeValue::Code(code) => code.literal.chars().next(), - NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'), - value if is_mark_wrapper(value) => node.first_child().and_then(first_rendered_char), - _ => None, - } -} - -fn is_word_char(c: char) -> bool { - c.is_alphanumeric() || c == '_' -} - -/// Whether the inline character immediately before `node` is a word -/// character (#1418), climbing through mark-wrapper ancestors while -/// `node` sits at their leading edge. No rendered neighbour (block -/// boundary) is not a word character. -fn preceded_by_word_char(node: &AstNode<'_>) -> bool { - let mut current = node; - loop { - if let Some(prev) = current.previous_sibling() { - return last_rendered_char(prev).is_some_and(is_word_char); - } - match current.parent() { - Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent, - _ => return false, - } - } -} - -/// Whether the inline character immediately after `node` is a word -/// character; mirror of `preceded_by_word_char`. -fn followed_by_word_char(node: &AstNode<'_>) -> bool { - let mut current = node; - loop { - if let Some(next) = current.next_sibling() { - return first_rendered_char(next).is_some_and(is_word_char); - } - match current.parent() { - Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent, - _ => return false, - } - } -} - -/// Replace a text leaf's literal, detaching the leaf (and any mark -/// wrappers it leaves childless) when the replacement is empty -/// (#1418: a span whose whole text was edge spaces). -fn set_text_leaf_text(leaf: &AstNode<'_>, new_text: &str) { - if !new_text.is_empty() { - leaf.data.borrow_mut().value = NodeValue::Text(new_text.to_owned().into()); - return; - } - let mut current = leaf.parent(); - leaf.detach(); - while let Some(node) = current { - if !is_mark_wrapper(&node.data.borrow().value) || node.first_child().is_some() { - break; - } - current = node.parent(); - node.detach(); - } -} - -/// Hoist one edge of one delimiter wrapper (#1418): move its leading -/// (or trailing) spaces to a plain text node just outside the wrapper -/// — but still inside any outer non-delimiter wrapper such as a link, -/// which is exactly the sibling position next to this wrapper — when -/// a word character touches the wrapper on that side. -fn hoist_one_edge<'a>(arena: &'a Arena<'a>, wrapper: &'a AstNode<'a>, leading: bool) { - let touches_word = if leading { - preceded_by_word_char(wrapper) - } else { - followed_by_word_char(wrapper) - }; - if !touches_word { - return; - } - let Some(leaf) = (if leading { - first_text_leaf(wrapper) - } else { - last_text_leaf(wrapper) - }) else { - return; - }; - let text = match &leaf.data.borrow().value { - NodeValue::Text(literal) => literal.to_string(), - _ => return, - }; - let spaces_len = if leading { - text.len() - text.trim_start_matches(' ').len() - } else { - text.len() - text.trim_end_matches(' ').len() - }; - if spaces_len == 0 { - return; - } - let (spaces, rest) = if leading { - (text[..spaces_len].to_owned(), text[spaces_len..].to_owned()) - } else { - ( - text[text.len() - spaces_len..].to_owned(), - text[..text.len() - spaces_len].to_owned(), - ) - }; - // Insert the hoisted spaces while the wrapper is still attached: - // shrinking the leaf afterwards may detach the wrapper itself - // (a span whose whole text was edge spaces), and the space node - // must stay at the wrapper's position when that happens. - let space_node = arena.alloc(AstNode::from(NodeValue::Text(spaces.into()))); - if leading { - wrapper.insert_before(space_node); - } else { - wrapper.insert_after(space_node); - } - set_text_leaf_text(leaf, &rest); -} - -/// #1418: a delimiter-mark span whose text starts or ends with a -/// space saves with that space inside the delimiters, and comrak -/// renders it as an ` ` entity (`a* b*`). When a word -/// character touches the span on that side, the emitted form fails -/// CommonMark flanking rules on reparse and the mark is destroyed. -/// Hoist such edge spaces out of the delimiter wrappers so the saved -/// form reparses with the mark intact; the space becomes unmarked, -/// which renders identically. Edges a word character does not touch -/// (paragraph boundaries, space/punctuation neighbours, spans padded -/// on both edges) keep the ` ` form, which round-trips as-is. -/// Working on the converted AST — after #968's chain merging — means -/// only true span edges are considered: an edge space shared with a -/// neighbouring run of the same span is interior here, not an edge. -fn hoist_delimiter_edge_spaces<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>) { - let wrappers: Vec<&AstNode<'a>> = root - .descendants() - .filter(|node| is_delimiter_wrapper(&node.data.borrow().value)) - .collect(); - // Reverse document order: inner wrappers before their outers (a - // space hoisted out of an inner wrapper may still sit at the - // outer wrapper's edge and be hoisted again by its turn), and a - // wrapper's own leading edge before its trailing edge. - for wrapper in wrappers.into_iter().rev() { - hoist_one_edge(arena, wrapper, true); - hoist_one_edge(arena, wrapper, false); - } -} - -/// #1496: comrak's CommonMark renderer emits an info-less code block -/// as an INDENTED block whenever it can (its fenced branch requires a -/// non-empty info string, the global `prefer_fenced` option, or a few -/// literal edge cases). Inside a blockquote the indented form drops -/// the quote prefix for every following sibling, so the saved file -/// reparses as two blockquotes and everything after the code block -/// leaves the quote. Give each info-less code block inside a -/// blockquote a placeholder info string so the renderer takes the -/// fenced branch, and return the placeholders for stripping from the -/// rendered output — the same placeholder-and-restore pattern as -/// `substitute_spaced_destinations`. Code blocks outside blockquotes -/// are fenced by the global `prefer_fenced` render option (#954); this -/// placeholder is kept as belt-and-braces for the quoted shape. -fn force_fenced_code_blocks_in_blockquotes<'a>(root: &'a AstNode<'a>) -> Vec { - let mut tokens: Vec = Vec::new(); - let mut stack: Vec<(&AstNode<'a>, bool)> = vec![(root, false)]; - while let Some((node, ancestor_is_blockquote)) = stack.pop() { - let in_blockquote = - ancestor_is_blockquote || matches!(node.data.borrow().value, NodeValue::BlockQuote); - for child in node.children() { - stack.push((child, in_blockquote)); - } - if !in_blockquote { - continue; - } - let mut data = node.data.borrow_mut(); - if let NodeValue::CodeBlock(code_block) = &mut data.value - && code_block.info.is_empty() - { - // The trailing `-end` keeps placeholders prefix-free - // (`-1-end` is not a prefix of `-10-end`); restoration is - // positional regardless (see `strip_fence_placeholder`). - let token = format!("idweb-blockquote-fence-{}-end", tokens.len()); - code_block.info.clone_from(&token); - tokens.push(token); - } - } - tokens -} - -/// Remove a #1496 fence placeholder from rendered output — ONLY at -/// its generated fence-info position: a run of >= 3 backticks -/// immediately before the placeholder and a newline immediately after -/// it (the renderer's fence line shape). A plain `str::replace` would -/// also strip the placeholder text anywhere else it occurs (user prose, -/// code content) and, with prefix-sharing placeholders, corrupt -/// neighbouring blocks' info strings (Codex review on PR #3770). -fn strip_fence_placeholder(output: &str, token: &str) -> String { - let mut result = String::with_capacity(output.len()); - let mut rest = output; - while let Some(pos) = rest.find(token) { - let before = &rest[..pos]; - let after = &rest[pos + token.len()..]; - let fence_run = before.chars().rev().take_while(|c| *c == '`').count(); - if fence_run >= 3 && after.starts_with('\n') { - result.push_str(before); - rest = after; - } else { - result.push_str(&rest[..pos + token.len()]); - rest = after; - } - } - result.push_str(rest); - result -} - -/// Whether a rendered line is a blank blockquote line: up to 3 leading -/// spaces (CommonMark still reads the `>` as a quote marker; 4+ spaces -/// would be indented code), then only `>` markers and whitespace -/// (`>`, `> `, `> > `). A list-item quote opener (`- > `) is NOT one — -/// it carries the list marker, so the list-nested single-blank shape -/// is out of scope here. -fn is_blank_quote_line(line: &str) -> bool { - let indent = line.bytes().take_while(|&b| b == b' ').count(); - if indent > 3 { - return false; - } - let rest = &line[indent..]; - rest.contains('>') - && rest.chars().all(|c| c == '>' || c == ' ' || c == '\t') -} - -/// Whether a rendered line is quoted content (as opposed to a blank -/// quote line or a non-quote line): a `>` marker with non-blank text -/// after it (`> text`, `> ```rust`, `> | a |`, `> -----`). -fn is_quote_content_line(line: &str) -> bool { - let indent = line.bytes().take_while(|&b| b == b' ').count(); - if indent > 3 { - return false; - } - line[indent..] - .strip_prefix('>') - .is_some_and(|after| !after.trim().is_empty()) -} - -/// #1002: comrak's CommonMark renderer emits blank `> ` lines before a -/// blockquote's first child when that child is a fenced code block, a -/// table, a thematic break, or an HTML block — two at top level, so the -/// first save of any such quote pollutes the file (the PM document is -/// correct throughout and the output is already a fixpoint). Drop those -/// leading blanks from the rendered output, at the start of EVERY quote -/// run (start of file or right after a non-quote line, so a second -/// quote after a blank line is covered too). Blank lines BETWEEN blocks -/// inside a quote are the required separators and are kept: anything -/// after the run's first content line passes through untouched, as does -/// an all-blank run (a lone `>` with no quoted content). -fn strip_leading_blank_quote_lines(output: &str) -> String { - let lines: Vec<&str> = output.split('\n').collect(); - let mut result: Vec<&str> = Vec::with_capacity(lines.len()); - let mut at_quote_start = true; - let mut i = 0; - while i < lines.len() { - if at_quote_start && is_blank_quote_line(lines[i]) { - let mut j = i + 1; - while j < lines.len() && is_blank_quote_line(lines[j]) { - j += 1; - } - if j < lines.len() && is_quote_content_line(lines[j]) { - i = j; - continue; - } - } - result.push(lines[i]); - at_quote_start = !is_blank_quote_line(lines[i]) && !is_quote_content_line(lines[i]); - i += 1; - } - result.join("\n") -} - -/// Replace every link/image destination containing whitespace (space, -/// tab, newline, …) with a unique placeholder token, returning -/// (placeholder, raw destination) pairs for restoration after rendering -/// (#1019, #1423). The token is a valid bare destination (no whitespace -/// or characters comrak encodes), so the renderer emits it verbatim -/// exactly where the destination belongs. Reference-style links flow -/// through here too: comrak resolves a reference definition into the -/// referencing link's `url`, and the PM model stores that href directly, -/// so no separate definition path exists in this codec. -fn substitute_spaced_destinations<'a>(root: &'a AstNode<'a>) -> Vec<(String, String)> { - let mut substitutions: Vec<(String, String)> = Vec::new(); - let mut stack: Vec<&AstNode<'a>> = vec![root]; - while let Some(node) = stack.pop() { - stack.extend(node.children()); - let mut data = node.data.borrow_mut(); - let url = match &mut data.value { - NodeValue::Link(link) | NodeValue::Image(link) => &mut link.url, - _ => continue, - }; - if !url.contains(char::is_whitespace) { - continue; - } - if let Some(index) = substitutions - .iter() - .position(|(_, raw)| raw.as_str() == url.as_str()) - { - *url = substitutions[index].0.clone(); - } else { - let placeholder = format!( - "idweb-spaced-destination-{}-placeholder", - substitutions.len() - ); - let raw = std::mem::take(url); - *url = placeholder.clone(); - substitutions.push((placeholder, raw)); - } - } - substitutions -} - -/// Whether a converted AST node is block-level (as opposed to inline). -/// Used by the footnote_definition save path (#1031) to tell carried -/// block children apart from legacy inline children. -fn is_block_node(node: &AstNode<'_>) -> bool { - matches!( - node.data.borrow().value, - NodeValue::Paragraph - | NodeValue::Heading(_) - | NodeValue::BlockQuote - | NodeValue::List(_) - | NodeValue::Item(_) - | NodeValue::TaskItem(_) - | NodeValue::CodeBlock(_) - | NodeValue::HtmlBlock(_) - | NodeValue::ThematicBreak - | NodeValue::FrontMatter(_) - | NodeValue::Table(_) - | NodeValue::FootnoteDefinition(_) - ) -} - -/// Convert `ProseMirror` JSON to comrak AST. -/// Whether a JSON node is a `text` node carrying no marks (#1420). -/// Marked runs protect their edge spaces with the marked-span mechanism -/// (#1418); unmarked runs have no such protection, so the save direction -/// normalizes their edge whitespace instead (see -/// `normalize_inline_child_json`). -fn is_unmarked_text_json(node: &Value) -> bool { - node["type"].as_str() == Some("text") - && node["marks"] - .as_array() - .is_none_or(|marks| marks.is_empty()) -} - -/// Whether a JSON node is a `hard_break` — the boundary between two -/// rendered lines inside one block (#1420). -fn is_hard_break_json(node: &Value) -> bool { - node["type"].as_str() == Some("hard_break") -} - -/// Whether an unmarked text node renders as nothing but edge whitespace -/// (empty, or spaces/tabs only). Such a node never shields a neighbour's -/// edge from the line boundary: at a line edge its own whitespace is -/// normalized away too, and mid-line it is a separator either way (#1420). -fn is_whitespace_only_text_json(node: &Value) -> bool { - is_unmarked_text_json(node) - && node["text"] - .as_str() - .unwrap_or("") - .chars() - .all(|c| c == ' ' || c == '\t') -} - -/// Whether a hard break has no rendered content after it before the -/// block ends. Whitespace-only text and further breaks do not make a -/// trailing break interior content. This is the placement boundary for -/// #1388: CommonMark cannot spell a break after the last content of a -/// block, so normalize it away before building the comrak AST. -fn hard_break_is_trailing(content: &[Value], idx: usize) -> bool { - content[idx + 1..] - .iter() - .all(|sibling| is_hard_break_json(sibling) || is_whitespace_only_text_json(sibling)) -} - -/// Apply the save-side hard-break placement policy for a block's inline -/// children (#1388, transferring the #1492 placements): a hard break at -/// block end is dropped explicitly (the renderer silently drops it); a -/// heading is single-line CommonMark content, so an interior break -/// degrades to a space instead of becoming an unspellable backslash-newline. -/// Other interior paragraph breaks retain their existing LineBreak form. -fn normalize_hard_break_placement(node_type: &str, content: &[Value]) -> Vec { - if !matches!(node_type, "heading" | "paragraph") { - return content.to_vec(); - } - - let mut normalized = Vec::with_capacity(content.len()); - for (idx, child) in content.iter().enumerate() { - if !is_hard_break_json(child) { - normalized.push(child.clone()); - continue; - } - if hard_break_is_trailing(content, idx) { - continue; - } - if node_type == "heading" { - normalized.push(json!({"type": "text", "text": " "})); - } else { - normalized.push(child.clone()); - } - } - normalized -} - -/// Whether scanning `siblings` (in render order) reaches a line edge — -/// the start/end of the block or a `hard_break` — before any content -/// that renders something (#1420). -fn reaches_line_edge(siblings: impl Iterator) -> bool { - for sibling in siblings { - if is_hard_break_json(&sibling) { - return true; - } - if !is_whitespace_only_text_json(&sibling) { - return false; - } - } - true -} - -/// #1420: normalize one inline child of a block before conversion. -/// -/// Unmarked text runs are written verbatim on save, but CommonMark -/// reparse strips edge whitespace (up to 3 leading spaces per line, -/// trailing spaces ignored) and deletes a whitespace-only paragraph -/// outright, so the saved file and the reopened doc disagreed. The -/// pinned policy is normalize-at-save: trim an unmarked run's leading -/// spaces when it sits at a line start (block start or just after a -/// `hard_break`) and its trailing spaces when it sits at a line end -/// (block end or just before a `hard_break`), so the first saved file -/// is already the fixpoint. A whitespace-only run at a line edge -/// becomes an empty text node, so a whitespace-only paragraph saves as -/// an EMPTY paragraph instead of vanishing text. Interior runs (word -/// separators between words/marks) and marked runs are untouched. -fn normalize_inline_child_json(content: &[Value], idx: usize) -> std::borrow::Cow<'_, Value> { - let child = &content[idx]; - if !is_unmarked_text_json(child) { - return std::borrow::Cow::Borrowed(child); - } - let trim_start = reaches_line_edge(content[..idx].iter().rev().cloned()); - let trim_end = reaches_line_edge(content[idx + 1..].iter().cloned()); - if !trim_start && !trim_end { - return std::borrow::Cow::Borrowed(child); - } - let text = child["text"].as_str().unwrap_or(""); - let mut normalized = text; - if trim_start { - normalized = normalized.trim_start_matches([' ', '\t']); - } - if trim_end { - normalized = normalized.trim_end_matches([' ', '\t']); - } - if normalized == text { - return std::borrow::Cow::Borrowed(child); - } - let mut owned = child.clone(); - owned["text"] = json!(normalized); - std::borrow::Cow::Owned(owned) -} - +mod markdown_scan; +mod markdown_serialization; +mod parse_helpers; +mod prosemirror_json; + +pub(crate) use markdown_scan::*; +pub use markdown_serialization::prosemirror_to_markdown; +pub(crate) use markdown_serialization::*; +pub(crate) use parse_helpers::*; +pub(crate) use prosemirror_json::*; fn json_to_ast<'a>(arena: &'a Arena<'a>, json: &Value) -> Result<&'a AstNode<'a>, ConversionError> { let node_type = json["type"].as_str().ok_or(ConversionError::MissingType)?; diff --git a/pkgs/id/src/web/markdown/markdown_scan.rs b/pkgs/id/src/web/markdown/markdown_scan.rs new file mode 100644 index 0000000000..7acd6c9035 --- /dev/null +++ b/pkgs/id/src/web/markdown/markdown_scan.rs @@ -0,0 +1,1283 @@ +//! Source-scanning helpers for the Markdown -> ProseMirror conversion: +//! fence/HTML-block tracking, container prefixes, and footnote/link +//! reference source scans. Split out of `markdown.rs` for #4704. + +use super::*; + +/// Fence tracking for the source scans below: a fence opens with a +/// run of >= 3 backticks or tildes and closes only with a run of the +/// SAME character at least as long (CommonMark) -- a three-backtick +/// line inside a four-backtick block is content, not a close (Codex +/// P2 on the first #1565 cut, which toggled on any fence-shaped line). +#[derive(Default)] +pub(crate) struct FenceTracker { + pub(crate) open: Option<(char, usize)>, +} + +/// The line to feed the FenceTracker: a fence delimiter may sit +/// up to three columns in from its container's content edge +/// (CommonMark), but strip_container_prefixes leaves those columns +/// in place (`> ```` arrives as two leading spaces), and +/// FenceTracker::feed anchors the run at the first character -- so +/// an indented opening fence inside a blockquote was missed and +/// the "code" interior was scanned as live text (Codex P2 on +/// #1565's twenty-fourth cut). Removing up to three leading spaces +/// here keeps the four-column distinction: a line still indented +/// after this (or tab-led, which is four columns at column 0) +/// reaches the tracker space-led and opens no fence, exactly like +/// indented code. +pub(crate) fn fence_feed_line(line: &str) -> &str { + let spaces = line.chars().take_while(|&c| c == ' ').count().min(3); + &line[spaces..] +} + +impl FenceTracker { + /// Feed one line (already stripped of up to three leading + /// spaces). Returns true when the line is a fence delimiter. + pub(crate) fn feed(&mut self, stripped: &str) -> bool { + let ch = match stripped.chars().next() { + Some(c @ ('`' | '~')) => c, + _ => return false, + }; + let run = stripped.chars().take_while(|&c| c == ch).count(); + if run < 3 { + return false; + } + if self.open.is_none() && ch == '`' && stripped[run..].contains('`') { + // A backtick fence's info string cannot contain a + // backtick (CommonMark), so a line like ```a`b opens + // no fence at all (Codex P2 on #1565's eighth cut). + return false; + } + match self.open { + None => { + self.open = Some((ch, run)); + true + } + Some((open_ch, open_run)) => { + if ch == open_ch && run >= open_run && stripped[run..].trim().is_empty() { + self.open = None; + true + } else { + false + } + } + } + } + + pub(crate) fn in_fence(&self) -> bool { + self.open.is_some() + } + + /// Forget any open fence: a fence opened inside a container + /// ends implicitly when the container ends, with no closing + /// delimiter line (Codex P2 on #1565's tenth cut). + pub(crate) fn reset(&mut self) { + self.open = None; + } +} + +/// HTML-block tracking for the source scans below (Codex P2 on +/// #1565's second cut): comrak parses a raw HTML block -- a comment, +/// a script/pre/style/textarea element, a block-level tag, or a lone +/// complete tag -- as literal content until its CommonMark end +/// condition (the closing marker for comments/CDATA/PIs/tag-bodies, +/// a blank line for plain block tags). A definition-shaped line in +/// that interior is literal text, exactly as in a fence; without this +/// tracking the pre-scan synthesized a live footnote out of a +/// comment's interior and a save then moved it outside the comment. +#[derive(Default)] +pub(crate) struct HtmlBlockTracker { + /// What ends the open block: a literal closing marker, or a + /// blank line for block-tag (type 6/7) blocks. + pub(crate) end: Option, +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum HtmlBlockEnd { + Marker(&'static str), + BlankLine, +} + +/// The CommonMark type-6 block-level tag names. +pub(crate) const HTML_BLOCK_TAGS: &[&str] = &[ + "address", + "article", + "aside", + "base", + "basefont", + "blockquote", + "body", + "caption", + "center", + "col", + "colgroup", + "dd", + "details", + "dialog", + "dir", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hr", + "html", + "iframe", + "legend", + "li", + "link", + "main", + "menu", + "menuitem", + "nav", + "noframes", + "ol", + "optgroup", + "option", + "p", + "param", + "search", + "section", + "summary", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "title", + "tr", + "track", + "ul", +]; + +/// Whether `trimmed` (a whole line, both ends trimmed) is exactly +/// one complete HTML open or closing tag -- CommonMark type 7: a +/// tag name (a letter, then letters/digits/`-`), then for an open +/// tag any number of whitespace-separated attributes (a name, with +/// an optional `=` and an unquoted, single-quoted, or +/// double-quoted value), optional whitespace, an optional `/`, +/// and the final `>`. A closing tag is ``. Anything else angle-delimited is NOT a tag: +/// an autolink like `` (the `:` after the +/// name is not whitespace, `/`, or `>`), or a tag-shaped line with +/// junk where an attribute should be. Treating every +/// angle-delimited string as an HTML block opened a +/// blank-line-ended block on the autolink line and swallowed the +/// heading and the valid orphan definition after it (Codex P2 on +/// #1565's seventeenth cut). +pub(crate) fn is_complete_html_tag(trimmed: &str) -> bool { + let bytes = trimmed.as_bytes(); + if bytes.len() < 3 || bytes[0] != b'<' || bytes[bytes.len() - 1] != b'>' { + return false; + } + let inner = &trimmed[1..trimmed.len() - 1]; + let b = inner.as_bytes(); + let (closing, mut pos) = if b.first() == Some(&b'/') { + (true, 1) + } else { + (false, 0) + }; + if !b.get(pos).is_some_and(|c| c.is_ascii_alphabetic()) { + return false; + } + let name_start = pos; + pos += 1; + while b + .get(pos) + .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-') + { + pos += 1; + } + // Type 1 names never open a type 7 block with an OPENING tag + // (they are handled as marker-ended blocks above); a line + // naming one that reaches here did not match the type-1 + // boundary rule either. The exclusion applies only to opening + // tags: a complete CLOSING tag of any name opens a type-7 + // block, so `
` makes the following definition-shaped + // line its literal interior -- rejecting it recovered that + // line as a live definition (Codex P2 on #1565's + // twenty-first cut). + if !closing + && ["script", "pre", "style", "textarea"] + .contains(&inner[name_start..pos].to_ascii_lowercase().as_str()) + { + return false; + } + if closing { + while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { + pos += 1; + } + return pos == inner.len(); + } + loop { + let ws_start = pos; + while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { + pos += 1; + } + let had_ws = pos > ws_start; + match b.get(pos) { + None => return true, + Some(b'/') => return pos + 1 == inner.len(), + Some(_) if had_ws => { + // Attribute name, then an optional `= value`. + if !b + .get(pos) + .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_' || *c == b':') + { + return false; + } + pos += 1; + while b.get(pos).is_some_and(|c| { + c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b':') + }) { + pos += 1; + } + let mut p2 = pos; + while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { + p2 += 1; + } + if b.get(p2) == Some(&b'=') { + p2 += 1; + while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { + p2 += 1; + } + match b.get(p2) { + Some(q @ (b'"' | b'\'')) => { + let q = *q; + p2 += 1; + while b.get(p2).is_some_and(|c| *c != q) { + p2 += 1; + } + if b.get(p2).is_none() { + return false; + } + p2 += 1; + } + Some(_) => { + let vstart = p2; + while b.get(p2).is_some_and(|c| { + !c.is_ascii_whitespace() + && !matches!(c, b'"' | b'\'' | b'=' | b'<' | b'>' | b'`') + }) { + p2 += 1; + } + if p2 == vstart { + return false; + } + } + None => return false, + } + pos = p2; + } + } + Some(_) => return false, + } + } +} + +impl HtmlBlockTracker { + pub(crate) fn in_html(&self) -> bool { + self.end.is_some() + } + + /// Forget any open block: a block opened inside a container + /// ends implicitly when the container ends, with no closing + /// line (Codex P2 on #1565's eleventh cut, mirroring + /// FenceTracker::reset). + pub(crate) fn reset(&mut self) { + self.end = None; + } + + /// Feed one line (already stripped of up to three leading + /// spaces). Returns true when the line belongs to an HTML block + /// (its opening line, interior, or closing line). + /// `may_open_type7` is the caller's paragraph context: a type-7 + /// block (a lone complete inline tag) cannot interrupt a + /// paragraph, so when the previous line is paragraph content + /// the caller passes false and a type-7 opening is refused + /// (Codex P2 on #1565's eighteenth cut). Types 1-6 can + /// interrupt a paragraph and are always eligible. + pub(crate) fn feed(&mut self, stripped: &str, may_open_type7: bool) -> bool { + if let Some(end) = self.end { + match end { + HtmlBlockEnd::Marker(marker) => { + if stripped.to_ascii_lowercase().contains(marker) { + self.end = None; + } + } + HtmlBlockEnd::BlankLine => { + if stripped.trim().is_empty() { + self.end = None; + } + } + } + return true; + } + let Some(rest) = stripped.strip_prefix('<') else { + return false; + }; + let lower = stripped.to_ascii_lowercase(); + // Marker-ended blocks (CommonMark types 1-5). The tag-named + // prefixes require a name boundary: `` is not a + // `
` block (nor `` a `"),
+            (""),
+            (""),
+            (""),
+        ] {
+            // The tag-named prefixes follow the CommonMark type-1
+            // boundary exactly: whitespace, '>', or end-of-line
+            // after the name. Anything else (`
`, ``)
+            // is a generic tag block ending at a blank line, not a
+            // marker-ended block (Codex P2 on #1565's tenth cut).
+            let boundary_ok = !prefix[1..].chars().all(|c| c.is_ascii_alphabetic())
+                || match lower.as_bytes().get(prefix.len()) {
+                    None => true,
+                    Some(b) => b.is_ascii_whitespace() || *b == b'>',
+                };
+            // CDATA is case-sensitive (CommonMark): only the
+            // exact uppercase `').
+            if !rest.contains('>') {
+                self.end = Some(HtmlBlockEnd::Marker(">"));
+            }
+            return true;
+        }
+        // Tag-ended blocks (types 6 and 7): a block-level tag, or a
+        // lone complete open/closing tag on the line.
+        let tag_body = rest.strip_prefix('/').unwrap_or(rest);
+        let tag_name: String = tag_body
+            .chars()
+            .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
+            .collect::()
+            .to_ascii_lowercase();
+        if tag_name.is_empty() {
+            return false;
+        }
+        if HTML_BLOCK_TAGS.contains(&tag_name.as_str())
+            && tag_name_boundary_ok(tag_body, tag_name.len())
+        {
+            self.end = Some(HtmlBlockEnd::BlankLine);
+            return true;
+        }
+        let trimmed = stripped.trim_end();
+        if is_complete_html_tag(trimmed) {
+            if !may_open_type7 {
+                return false;
+            }
+            self.end = Some(HtmlBlockEnd::BlankLine);
+            return true;
+        }
+        let _ = rest;
+        false
+    }
+}
+
+/// Strip block-container prefixes (blockquote `>`, list markers
+/// `-`/`*`/`+`/ordered) from a line, repeatedly, for fence detection:
+/// a fence opened inside a list item or blockquote still makes its
+/// content literal (Codex P2 on #1565's fourth cut -- `- ```` followed
+/// by an indented definition-shaped line parsed as code by comrak,
+/// but the scanner missed the opening fence behind the `- ` marker
+/// and recovered the interior line as a live definition).
+pub(crate) fn strip_container_prefixes(line: &str) -> &str {
+    let mut rest = line;
+    loop {
+        let t = rest.trim_start_matches(' ');
+        if let Some(r) = t.strip_prefix('>') {
+            rest = r.strip_prefix(' ').unwrap_or(r);
+            continue;
+        }
+        let bytes = t.as_bytes();
+        let marker_len = if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            Some(1)
+        } else {
+            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+            if digits >= 1
+                && digits <= 9
+                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+            {
+                Some(digits + 1)
+            } else {
+                None
+            }
+        };
+        let Some(marker_len) = marker_len else { break };
+        rest = strip_marker_padding(&t[marker_len..], marker_len);
+    }
+    rest
+}
+
+/// The content after a list marker, CommonMark-style: one to
+/// four columns of padding after the marker are the item's
+/// content indent and are stripped with the marker; FIVE or
+/// more columns mean the content is an indented code block
+/// whose indentation starts after a single padding column, so
+/// only that one column is stripped and the remaining
+/// indentation survives. Removing all the padding turned
+/// `-     ``` ` into a fence opener the document does not have,
+/// and the phantom fence then suppressed the valid reference
+/// definition after it (Codex P2 on #1565's twenty-first cut).
+pub(crate) fn strip_marker_padding(after: &str, marker_end_col: usize) -> &str {
+    let mut col = marker_end_col;
+    let mut end = 0;
+    for c in after.chars() {
+        match c {
+            ' ' => {
+                col += 1;
+                end += 1;
+            }
+            '\t' => {
+                col += 4 - (col % 4);
+                end += 1;
+            }
+            _ => break,
+        }
+    }
+    if col - marker_end_col > 4 {
+        // Keep all but the first padding character (spaces and
+        // tabs are one byte each, so this is a byte offset too).
+        &after[after.chars().next().map_or(0, |_| 1)..]
+    } else {
+        &after[end..]
+    }
+}
+
+/// The container structure of a recorded container prefix, as
+/// a string of marker kinds with all spacing removed: `> ` and
+/// `>` are the same blockquote level, so a fence opened under
+/// one spelling closes under the other (Codex P2 on #1565's
+/// nineteenth cut). Byte-exact prefix matching left such a
+/// fence open and suppressed the definitions after it.
+pub(crate) fn container_signature(prefix: &str) -> String {
+    let mut sig = String::new();
+    let mut rest = prefix;
+    loop {
+        let t = rest.trim_start_matches([' ', '\t']);
+        if let Some(r) = t.strip_prefix('>') {
+            sig.push('>');
+            rest = r;
+            continue;
+        }
+        let bytes = t.as_bytes();
+        if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            sig.push('*');
+            rest = &t[1..];
+            continue;
+        }
+        let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+        if digits >= 1
+            && digits <= 9
+            && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+            && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+        {
+            sig.push('#');
+            rest = &t[digits + 1..];
+            continue;
+        }
+        break;
+    }
+    sig
+}
+
+/// Strip at most `levels` container levels (blockquote `>`,
+/// list markers) from a line, mirroring
+/// strip_container_prefixes' per-level shapes.
+pub(crate) fn strip_container_levels(line: &str, levels: usize) -> &str {
+    let mut rest = line;
+    for _ in 0..levels {
+        let t = rest.trim_start_matches(' ');
+        if let Some(r) = t.strip_prefix('>') {
+            rest = r.strip_prefix(' ').unwrap_or(r);
+            continue;
+        }
+        let bytes = t.as_bytes();
+        let marker_len = if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            Some(1)
+        } else {
+            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+            if digits >= 1
+                && digits <= 9
+                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+            {
+                Some(digits + 1)
+            } else {
+                None
+            }
+        };
+        let Some(marker_len) = marker_len else { break };
+        rest = strip_marker_padding(&t[marker_len..], marker_len);
+    }
+    rest
+}
+
+/// Whether `stripped` (a line stripped of up to three leading
+/// spaces) carries the recorded container `prefix`, matched
+/// STRUCTURALLY rather than byte-for-byte: the line's own
+/// leading container levels (as many as the recorded prefix
+/// has) must have the same signature as the recorded prefix.
+pub(crate) fn carries_container_prefix(stripped: &str, prefix: &str) -> bool {
+    if prefix.is_empty() {
+        return false;
+    }
+    let levels = container_signature(prefix).chars().count();
+    if levels == 0 {
+        return false;
+    }
+    let own = &stripped[..stripped.len() - strip_container_levels(stripped, levels).len()];
+    !own.is_empty() && container_signature(own) == container_signature(prefix)
+}
+
+/// A footnote definition block found by the source pre-scan (#1565):
+/// its label and the block's verbatim source (the `[^label]:` line
+/// plus any indented continuation lines, trailing blank lines cut).
+pub(crate) struct FootnoteDefinitionBlock {
+    pub(crate) label: String,
+    pub(crate) source: String,
+    /// Zero-based line index of the definition's opening line, for
+    /// interleaving with other source segments in document order.
+    pub(crate) line: usize,
+}
+
+/// The label of a footnote definition starting on `line` (already
+/// stripped of up to three leading spaces), or `None` when the line
+/// does not start one. A definition opens as `[^label]:`.
+pub(crate) fn footnote_definition_label(line: &str) -> Option {
+    let rest = line.strip_prefix("[^")?;
+    // The label ends at the FIRST ']' and a ':' must follow it
+    // immediately. Searching for "]:" instead accepted `a]b` as the
+    // label of `[^a]b]: note` -- a definition comrak does not
+    // recognize, whose probe then looped recovery forever (Codex P1).
+    let close = rest.find(']')?;
+    if !rest[close + 1..].starts_with(':') {
+        return None;
+    }
+    let label = &rest[..close];
+    if label.is_empty() || label.contains('[') {
+        return None;
+    }
+    Some(label.to_string())
+}
+
+/// A thematic break: at least three of the same `-`, `*`, or `_`,
+/// spaces and tabs aside (CommonMark).
+pub(crate) fn is_thematic_break(stripped: &str) -> bool {
+    let compact: String = stripped
+        .chars()
+        .filter(|c| *c != ' ' && *c != '\t')
+        .collect();
+    let first = compact.chars().next();
+    compact.len() >= 3
+        && matches!(first, Some('-' | '*' | '_'))
+        && compact.chars().all(|c| Some(c) == first)
+}
+
+/// A setext heading underline: only `=`s (level 1) or `-`s (level 2).
+pub(crate) fn is_setext_underline(stripped: &str) -> bool {
+    let t = stripped.trim();
+    (!t.is_empty() && t.chars().all(|c| c == '=')) || (!t.is_empty() && t.chars().all(|c| c == '-'))
+}
+
+/// Whether a line starts a new block and so cannot be a lazy
+/// paragraph continuation of a footnote definition: another
+/// definition, an ATX heading, a fence, a blockquote, a thematic
+/// break, an HTML block opener, or a list/blockquote container line.
+/// Whether a line is an ATX heading: 1-6 `#`s followed by a
+/// space, a tab, or end-of-line (CommonMark). `#hashtag` is
+/// paragraph text, not a heading (Codex P2 on #1565's tenth cut).
+pub(crate) fn is_atx_heading(stripped: &str) -> bool {
+    let hashes = stripped.bytes().take_while(|&b| b == b'#').count();
+    (1..=6).contains(&hashes)
+        && matches!(
+            stripped.as_bytes().get(hashes),
+            None | Some(b' ') | Some(b'\t')
+        )
+}
+
+/// Whether the character after a block-level tag name is a valid
+/// name boundary: whitespace, `/`, `>`, or end-of-line (CommonMark
+/// type 6). `` has no boundary after `div`, so it is
+/// literal paragraph text, not an HTML block (Codex P2 on
+/// #1565's sixteenth cut).
+pub(crate) fn tag_name_boundary_ok(tag_body: &str, name_len: usize) -> bool {
+    matches!(
+        tag_body.as_bytes().get(name_len),
+        None | Some(b' ') | Some(b'\t') | Some(b'>') | Some(b'/')
+    )
+}
+
+/// Whether a line opens an HTML block that can INTERRUPT a
+/// paragraph (CommonMark types 1-6): a comment, a CDATA section,
+/// a processing instruction, a declaration, a script/pre/style/
+/// textarea element, or a block-level tag (opening or closing).
+/// A lone inline tag (``, ``) is type 7, which cannot
+/// interrupt a paragraph: as a footnote definition's next line it
+/// is a lazy continuation of the definition's paragraph, not a
+/// new block (Codex P2 on #1565's eleventh cut).
+pub(crate) fn is_html_block_start(stripped: &str) -> bool {
+    let Some(rest) = stripped.strip_prefix('<') else {
+        return false;
+    };
+    let lower = stripped.to_ascii_lowercase();
+    if lower.starts_with("` comment - renderer-internal markup that lands in
+/// the user's file. Where the two lists are of DIFFERENT PM kinds the
+/// comment is the only thing keeping them apart, and it is not needed:
+/// a change of list type ends a list on reparse all by itself (and the
+/// #1370 parse-side split rebuilds task/plain runs), so the separator
+/// line is dropped and the lists sit directly adjacent in the text -
+/// tight lists stay tight, loose lists keep their blank lines. Where
+/// the kinds are the SAME (two ordered lists, two task lists) dropping
+/// it would merge the lists and lose restart/order information, so the
+/// separator stays for those pairs. It also stays for a DIFFERENT-kind
+/// pair that renders as the same ordered Markdown list (an ordered_list
+/// next to a task_list carrying `attrs.order`, or vice versa) when the
+/// second list does not start exactly where the first list's numbering
+/// ends: merging those on reparse renumbers the second run and loses
+/// its restart (Codex review, PR #3258). If the lines found in the output
+/// do not line up one-to-one with the boundaries computed from the doc,
+/// the output is returned untouched.
+/// The fence run a rendered line opens or closes, if any: returns the
+/// fence character and the remainder of the line starting at the run.
+/// List-marker prefixes are stripped first (blockquote `>` markers and
+/// indentation, then bullet / ordered / task-checkbox markers, repeated
+/// for nested items), because a code block that is a list item's first
+/// block renders its opening fence immediately after the marker
+/// (`- ``` `). Plain lines return their own trimmed remainder.
+pub(crate) fn list_fence_rest(line: &str) -> Option<(char, &str)> {
+    let mut rest = line.trim_start_matches(['>', ' ']).trim_start();
+    loop {
+        let mut stripped = false;
+        for marker in ["- ", "+ ", "* ", "[ ] ", "[x] ", "[X] "] {
+            if let Some(r) = rest.strip_prefix(marker) {
+                rest = r.trim_start();
+                stripped = true;
+                break;
+            }
+        }
+        if stripped {
+            continue;
+        }
+        let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count();
+        if digits > 0 {
+            let after = &rest[digits..];
+            for marker in [". ", ") "] {
+                if let Some(r) = after.strip_prefix(marker) {
+                    rest = r.trim_start();
+                    stripped = true;
+                    break;
+                }
+            }
+        }
+        if !stripped {
+            break;
+        }
+    }
+    if rest.starts_with("```") {
+        Some(('`', rest))
+    } else if rest.starts_with("~~~") {
+        Some(('~', rest))
+    } else {
+        None
+    }
+}
+
+/// Whether a list's first item renders empty (no text, no block content
+/// beyond empty paragraphs): an empty list item cannot interrupt a
+/// paragraph under CommonMark, whatever its marker (Codex review,
+/// PR #3258: `- a\n\n1.\n2. b` saved without the blank reparsed the
+/// empty `1.` as lazy continuation text and lost the ordered list).
+pub(crate) fn list_starts_with_empty_item(list: &Value) -> bool {
+    let Some(first) = list["content"].as_array().and_then(|items| items.first()) else {
+        return false;
+    };
+    pub(crate) fn node_is_empty(node: &Value) -> bool {
+        if node["text"].as_str().is_some_and(|t| !t.trim().is_empty()) {
+            return false;
+        }
+        match node["type"].as_str() {
+            Some("paragraph" | "list_item" | "task_list_item" | "text") | None => {}
+            Some(_) => return false,
+        }
+        node["content"]
+            .as_array()
+            .is_none_or(|parts| parts.iter().all(node_is_empty))
+    }
+    node_is_empty(first)
+}
+
+pub(crate) fn strip_end_list_separators(doc: &Value, output: &str) -> String {
+    // Recompute with kinds: the drop decision needs them, so collect
+    // (prev_kind, kind, tight_pair, merge_safe, needs_blank) tuples
+    // alongside.
+    let mut kinds: Vec<(String, String, bool, bool, bool)> = Vec::new();
+    collect_boundary_kinds(doc, &mut kinds);
+    if kinds.is_empty() {
+        return output.to_string();
+    }
+    let is_separator_line =
+        |line: &str| line.trim_start_matches(['>', ' ']).trim() == "";
+    let is_blank_line = |line: &str| line.trim_start_matches(['>', ' ']).trim().is_empty();
+    let lines: Vec<&str> = output.lines().collect();
+    // Codex review, PR #3258: a separator-looking line inside a fenced
+    // code block is authored content, not renderer markup - it must
+    // neither count toward the boundary correspondence nor be dropped.
+    // Track fence state (``` / ~~~, optionally blockquote-prefixed) and
+    // only treat lines outside fences as separators.
+    let mut in_fence = false;
+    let mut fence_char = '`';
+    let mut fence_len = 0usize;
+    // Codex review, PR #3258: raw HTML blocks are literal content too.
+    // A backtick-only line inside one (e.g. a 
wrapping a ``` line) + // is not a fence opener, and a separator-looking line inside the + // block is authored HTML, not renderer markup. Track HTML block + // state (CommonMark: the block runs until a blank line; an HTML + // comment block runs until its --> closer) and exclude its lines + // from both fence tracking and separator counting. + let mut in_html = false; + let mut html_is_comment = false; + let mut is_separator: Vec = Vec::with_capacity(lines.len()); + for line in &lines { + let html_probe = line.trim_start_matches(['>', ' ']).trim(); + if in_html { + is_separator.push(false); + if html_is_comment { + if html_probe.contains("-->") { + in_html = false; + html_is_comment = false; + } + } else if html_probe.is_empty() { + in_html = false; + } + continue; + } + if !in_fence && !is_separator_line(line) { + let second = html_probe.chars().nth(1); + let opens_html = html_probe.starts_with('<') + && second.is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '/' | '!' | '?')); + if opens_html { + is_separator.push(false); + if html_probe.starts_with("") { + in_html = true; + html_is_comment = true; + } + } else { + in_html = true; + } + continue; + } + } + // Codex review, PR #3258: a fence can open immediately after a + // list marker (a list item whose first block is a code block + // renders as `- ``` `): strip any list-marker prefixes (bullet, + // ordered, task checkbox, nested) before looking for the fence + // run, or the opener is missed, the fence's literal content is + // counted as a separator, and the closing fence is mistaken + // for an opener that hides the real separator. + let fence_rest = list_fence_rest(line); + let fence_marker = fence_rest.map(|(c, _)| c); + match fence_marker { + Some(c) if !in_fence => { + in_fence = true; + fence_char = c; + fence_len = fence_rest + .map(|(_, rest)| rest.chars().take_while(|&ch| ch == c).count()) + .unwrap_or(0); + is_separator.push(false); + } + // CodeRabbit review, PR #3258: a fence closes only on a + // BARE run of the fence character at least as long as the + // opener. A content line such as ```rust starts with the + // marker but is not a closer; ending the fence there let a + // separator-looking line later in the code block be counted + // (and dropped) as renderer markup, losing authored lines. + Some(c) + if c == fence_char + && fence_rest.is_some_and(|(_, rest)| { + rest.trim_end().chars().all(|ch| ch == c) + && rest.trim_end().len() >= fence_len + }) => + { + in_fence = false; + is_separator.push(false); + } + _ => is_separator.push(!in_fence && is_separator_line(line)), + } + } + let found = is_separator.iter().filter(|b| **b).count(); + if found != kinds.len() { + return output.to_string(); + } + let mut boundary = kinds.iter(); + let mut kept: Vec<&str> = Vec::with_capacity(lines.len()); + let mut idx = 0; + while idx < lines.len() { + let line = lines[idx]; + if is_separator[idx] { + match boundary.next() { + Some((a, b, tight_pair, merge_safe, needs_blank)) if a != b && *merge_safe => { + // Drop the separator. The renderer also puts a blank + // line on each side of it; with the comment gone, + // blanks between the lists would fuse them into ONE + // loose list on reparse. A tight pair keeps no blank + // line at all; a loose pair keeps exactly one. A + // needs_blank pair also keeps exactly one: an ordered + // list starting above 1 cannot interrupt the previous + // item's paragraph, so with no blank line at all its + // first line reparses as a lazy continuation and the + // list is lost (Codex review, PR #3258). + let prev_blank = kept.last().is_some_and(|l| is_blank_line(l)); + let next_blank = lines.get(idx + 1).is_some_and(|l| is_blank_line(l)); + if prev_blank && next_blank { + if *tight_pair && !*needs_blank { + kept.pop(); + } + idx += 1; // skip the following blank line too + } + } + _ => kept.push(line), + } + } else { + kept.push(line); + } + idx += 1; + } + let mut out = kept.join("\n"); + if output.ends_with('\n') { + out.push('\n'); + } + out +} + +/// (prev PM kind, PM kind, both tight, merge-safe, needs-blank) for every list +/// adjacency in the doc, in render order, interleaved with authored +/// htmlBlocks (recorded as ("", "", false, false, false) so they consume a +/// separator-line slot but are never dropped - see +/// strip_end_list_separators' caller contract). Merge-safe is false +/// only when dropping the separator would merge two ordered-rendering +/// lists whose numbering does not continue across the boundary. +pub(crate) fn collect_boundary_kinds( + node: &Value, + out: &mut Vec<(String, String, bool, bool, bool)>, +) { + let Some(content) = node["content"].as_array() else { + return; + }; + let mut prev_list: Option<&Value> = None; + // Effective tight of the current consecutive bullet_list run's + // FIRST list (the tight json_to_ast's coalesce renders with). + let mut bullet_run_tight: Option = None; + for child in content { + let kind = list_kind(child); + if let (Some(prev), Some(kind)) = (prev_list, kind) + && !(list_kind(prev) == Some("bullet_list") && kind == "bullet_list") + { + // Codex review, PR #3258: when prev is a bullet_list that + // json_to_ast coalesced with earlier bullet siblings, the + // rendered list carries the FIRST sibling's tight, so the + // boundary must compare that effective tightness - the last + // original sibling's attr can differ and silently loosens + // the following run on reparse. + let prev_tight = if list_kind(prev) == Some("bullet_list") { + bullet_run_tight.unwrap_or_else(|| effective_tight(prev)) + } else { + effective_tight(prev) + }; + let child_tight = effective_tight(child); + let tight_pair = prev_tight && child_tight; + // Two lists that both render as ordered Markdown merge into + // one list on reparse if the separator goes; the merge is + // lossless only when the second list starts exactly where + // the first list's numbering ends (start + item count), so + // convert_list_runs recomputes the same run orders. + let ordered_merge_safe = match (ordered_start(prev), ordered_start(child)) { + (Some(prev_start), Some(next_start)) => { + let prev_count = prev["content"].as_array().map_or(0, |c| c.len()) as u64; + // attrs.order comes from the request's PM JSON; a + // crafted start near u64::MAX must not overflow the + // sum (debug builds panic, release builds wrap and + // could drop a separator that should stay). + prev_start.checked_add(prev_count) == Some(next_start) + } + _ => true, + }; + // Codex review, PR #3258: two lists that render as the same + // Markdown list family (bullet-rendering: bullet_list and + // order-less task_list; ordered-rendering: ordered_list and + // ordered task_list) merge into ONE list on reparse when the + // separator drops, and convert_list_runs then copies one + // run's tight onto both. When their tight attributes differ + // that silently loosens/tightens a run and breaks the save + // fixpoint, so the separator stays. Different families split + // on reparse by marker type and keep their own tightness. + let renders_ordered = |n: &Value| ordered_start(n).is_some(); + let tight_differs = prev_tight != child_tight; + let tight_merge_safe = + !(renders_ordered(prev) == renders_ordered(child) && tight_differs); + let merge_safe = ordered_merge_safe && tight_merge_safe; + // Codex review, PR #3258: an ordered-rendering list that + // starts above 1 cannot interrupt a paragraph, so when the + // previous list does not itself render ordered, the boundary + // must keep a blank line or the second list's first line + // reparses as a lazy continuation of the previous item. + // The empty-item guard (below) applies only across + // different rendered list families: within one family the + // two runs reparse as a single list, where an empty sibling + // item needs no blank - keeping one would loosen the merged + // list and break the save fixpoint (Codex review, PR #3258). + let needs_blank = (matches!(ordered_start(child), Some(start) if start != 1) + && ordered_start(prev).is_none()) + || (list_starts_with_empty_item(child) + && renders_ordered(prev) != renders_ordered(child)); + out.push(( + list_kind(prev).unwrap_or_default().to_string(), + kind.to_string(), + tight_pair, + merge_safe, + needs_blank, + )); + } + if child["type"].as_str() == Some("code_block") + && child["attrs"]["htmlBlock"].as_bool() == Some(true) + && child["content"].as_array().is_some_and(|parts| { + parts + .iter() + .filter_map(|n| n["text"].as_str()) + .collect::() + .trim() + == "" + }) + { + out.push((String::new(), String::new(), false, false, false)); + } + // Codex review, PR #3258: lists inside a table cell are + // flattened to text by append_table_cell_child and emit no + // separator, so boundaries collected there have no line in + // the output to correspond to - skip the cell's subtree. + if !matches!(child["type"].as_str(), Some("table_header" | "table_cell")) { + collect_boundary_kinds(child, out); + } + if kind.is_some() { + if kind == Some("bullet_list") { + if prev_list.is_none_or(|p| list_kind(p) != Some("bullet_list")) { + bullet_run_tight = Some(effective_tight(child)); + } + } else { + bullet_run_tight = None; + } + prev_list = Some(child); + } else { + prev_list = None; + bullet_run_tight = None; + } + } +} + +/// Whether a node value is a delimiter-mark wrapper (#1418): the +/// marks whose markdown spelling is a delimiter run (`*`/`**`/`~~`) +/// subject to CommonMark flanking rules. Link (bracket syntax) and +/// code (backtick syntax) tolerate edge spaces and are excluded. +pub(crate) fn is_delimiter_wrapper(value: &NodeValue) -> bool { + matches!( + value, + NodeValue::Emph | NodeValue::Strong | NodeValue::Strikethrough + ) +} + +/// The first text leaf of a mark chain, descending first children +/// through mark wrappers (#1418). `None` when the first inline is +/// anything else (an image or html node is a different mechanism — +/// #1407/#1412 — and keeps the legacy behaviour). +pub(crate) fn first_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> { + let mut current = node; + loop { + let child = current.first_child()?; + let value = child.data.borrow().value.clone(); + match value { + NodeValue::Text(_) => return Some(child), + _ if is_mark_wrapper(&value) => current = child, + _ => return None, + } + } +} + +/// The last text leaf of a mark chain; mirror of `first_text_leaf`. +pub(crate) fn last_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> { + let mut current = node; + loop { + let child = current.last_child()?; + let value = child.data.borrow().value.clone(); + match value { + NodeValue::Text(_) => return Some(child), + _ if is_mark_wrapper(&value) => current = child, + _ => return None, + } + } +} + +/// The last character a node renders as inline content (#1418): +/// text/code literals verbatim, breaks as whitespace, mark wrappers +/// by their last inline descendant. Anything else yields `None` +/// (treated as a non-word neighbour). +pub(crate) fn last_rendered_char(node: &AstNode<'_>) -> Option { + match &node.data.borrow().value { + NodeValue::Text(literal) => literal.to_string().chars().last(), + NodeValue::Code(code) => code.literal.chars().last(), + NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'), + value if is_mark_wrapper(value) => node.last_child().and_then(last_rendered_char), + _ => None, + } +} + +/// The first character a node renders as; mirror of +/// `last_rendered_char`. +pub(crate) fn first_rendered_char(node: &AstNode<'_>) -> Option { + match &node.data.borrow().value { + NodeValue::Text(literal) => literal.to_string().chars().next(), + NodeValue::Code(code) => code.literal.chars().next(), + NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'), + value if is_mark_wrapper(value) => node.first_child().and_then(first_rendered_char), + _ => None, + } +} + +pub(crate) fn is_word_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +/// Whether the inline character immediately before `node` is a word +/// character (#1418), climbing through mark-wrapper ancestors while +/// `node` sits at their leading edge. No rendered neighbour (block +/// boundary) is not a word character. +pub(crate) fn preceded_by_word_char(node: &AstNode<'_>) -> bool { + let mut current = node; + loop { + if let Some(prev) = current.previous_sibling() { + return last_rendered_char(prev).is_some_and(is_word_char); + } + match current.parent() { + Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent, + _ => return false, + } + } +} + +/// Whether the inline character immediately after `node` is a word +/// character; mirror of `preceded_by_word_char`. +pub(crate) fn followed_by_word_char(node: &AstNode<'_>) -> bool { + let mut current = node; + loop { + if let Some(next) = current.next_sibling() { + return first_rendered_char(next).is_some_and(is_word_char); + } + match current.parent() { + Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent, + _ => return false, + } + } +} + +/// Replace a text leaf's literal, detaching the leaf (and any mark +/// wrappers it leaves childless) when the replacement is empty +/// (#1418: a span whose whole text was edge spaces). +pub(crate) fn set_text_leaf_text(leaf: &AstNode<'_>, new_text: &str) { + if !new_text.is_empty() { + leaf.data.borrow_mut().value = NodeValue::Text(new_text.to_owned().into()); + return; + } + let mut current = leaf.parent(); + leaf.detach(); + while let Some(node) = current { + if !is_mark_wrapper(&node.data.borrow().value) || node.first_child().is_some() { + break; + } + current = node.parent(); + node.detach(); + } +} + +/// Hoist one edge of one delimiter wrapper (#1418): move its leading +/// (or trailing) spaces to a plain text node just outside the wrapper +/// — but still inside any outer non-delimiter wrapper such as a link, +/// which is exactly the sibling position next to this wrapper — when +/// a word character touches the wrapper on that side. +pub(crate) fn hoist_one_edge<'a>(arena: &'a Arena<'a>, wrapper: &'a AstNode<'a>, leading: bool) { + let touches_word = if leading { + preceded_by_word_char(wrapper) + } else { + followed_by_word_char(wrapper) + }; + if !touches_word { + return; + } + let Some(leaf) = (if leading { + first_text_leaf(wrapper) + } else { + last_text_leaf(wrapper) + }) else { + return; + }; + let text = match &leaf.data.borrow().value { + NodeValue::Text(literal) => literal.to_string(), + _ => return, + }; + let spaces_len = if leading { + text.len() - text.trim_start_matches(' ').len() + } else { + text.len() - text.trim_end_matches(' ').len() + }; + if spaces_len == 0 { + return; + } + let (spaces, rest) = if leading { + (text[..spaces_len].to_owned(), text[spaces_len..].to_owned()) + } else { + ( + text[text.len() - spaces_len..].to_owned(), + text[..text.len() - spaces_len].to_owned(), + ) + }; + // Insert the hoisted spaces while the wrapper is still attached: + // shrinking the leaf afterwards may detach the wrapper itself + // (a span whose whole text was edge spaces), and the space node + // must stay at the wrapper's position when that happens. + let space_node = arena.alloc(AstNode::from(NodeValue::Text(spaces.into()))); + if leading { + wrapper.insert_before(space_node); + } else { + wrapper.insert_after(space_node); + } + set_text_leaf_text(leaf, &rest); +} + +/// #1418: a delimiter-mark span whose text starts or ends with a +/// space saves with that space inside the delimiters, and comrak +/// renders it as an ` ` entity (`a* b*`). When a word +/// character touches the span on that side, the emitted form fails +/// CommonMark flanking rules on reparse and the mark is destroyed. +/// Hoist such edge spaces out of the delimiter wrappers so the saved +/// form reparses with the mark intact; the space becomes unmarked, +/// which renders identically. Edges a word character does not touch +/// (paragraph boundaries, space/punctuation neighbours, spans padded +/// on both edges) keep the ` ` form, which round-trips as-is. +/// Working on the converted AST — after #968's chain merging — means +/// only true span edges are considered: an edge space shared with a +/// neighbouring run of the same span is interior here, not an edge. +pub(crate) fn hoist_delimiter_edge_spaces<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>) { + let wrappers: Vec<&AstNode<'a>> = root + .descendants() + .filter(|node| is_delimiter_wrapper(&node.data.borrow().value)) + .collect(); + // Reverse document order: inner wrappers before their outers (a + // space hoisted out of an inner wrapper may still sit at the + // outer wrapper's edge and be hoisted again by its turn), and a + // wrapper's own leading edge before its trailing edge. + for wrapper in wrappers.into_iter().rev() { + hoist_one_edge(arena, wrapper, true); + hoist_one_edge(arena, wrapper, false); + } +} + +/// #1496: comrak's CommonMark renderer emits an info-less code block +/// as an INDENTED block whenever it can (its fenced branch requires a +/// non-empty info string, the global `prefer_fenced` option, or a few +/// literal edge cases). Inside a blockquote the indented form drops +/// the quote prefix for every following sibling, so the saved file +/// reparses as two blockquotes and everything after the code block +/// leaves the quote. Give each info-less code block inside a +/// blockquote a placeholder info string so the renderer takes the +/// fenced branch, and return the placeholders for stripping from the +/// rendered output — the same placeholder-and-restore pattern as +/// `substitute_spaced_destinations`. Code blocks outside blockquotes +/// are fenced by the global `prefer_fenced` render option (#954); this +/// placeholder is kept as belt-and-braces for the quoted shape. +pub(crate) fn force_fenced_code_blocks_in_blockquotes<'a>(root: &'a AstNode<'a>) -> Vec { + let mut tokens: Vec = Vec::new(); + let mut stack: Vec<(&AstNode<'a>, bool)> = vec![(root, false)]; + while let Some((node, ancestor_is_blockquote)) = stack.pop() { + let in_blockquote = + ancestor_is_blockquote || matches!(node.data.borrow().value, NodeValue::BlockQuote); + for child in node.children() { + stack.push((child, in_blockquote)); + } + if !in_blockquote { + continue; + } + let mut data = node.data.borrow_mut(); + if let NodeValue::CodeBlock(code_block) = &mut data.value + && code_block.info.is_empty() + { + // The trailing `-end` keeps placeholders prefix-free + // (`-1-end` is not a prefix of `-10-end`); restoration is + // positional regardless (see `strip_fence_placeholder`). + let token = format!("idweb-blockquote-fence-{}-end", tokens.len()); + code_block.info.clone_from(&token); + tokens.push(token); + } + } + tokens +} + +/// Remove a #1496 fence placeholder from rendered output — ONLY at +/// its generated fence-info position: a run of >= 3 backticks +/// immediately before the placeholder and a newline immediately after +/// it (the renderer's fence line shape). A plain `str::replace` would +/// also strip the placeholder text anywhere else it occurs (user prose, +/// code content) and, with prefix-sharing placeholders, corrupt +/// neighbouring blocks' info strings (Codex review on PR #3770). +pub(crate) fn strip_fence_placeholder(output: &str, token: &str) -> String { + let mut result = String::with_capacity(output.len()); + let mut rest = output; + while let Some(pos) = rest.find(token) { + let before = &rest[..pos]; + let after = &rest[pos + token.len()..]; + let fence_run = before.chars().rev().take_while(|c| *c == '`').count(); + if fence_run >= 3 && after.starts_with('\n') { + result.push_str(before); + rest = after; + } else { + result.push_str(&rest[..pos + token.len()]); + rest = after; + } + } + result.push_str(rest); + result +} + +/// Whether a rendered line is a blank blockquote line: up to 3 leading +/// spaces (CommonMark still reads the `>` as a quote marker; 4+ spaces +/// would be indented code), then only `>` markers and whitespace +/// (`>`, `> `, `> > `). A list-item quote opener (`- > `) is NOT one — +/// it carries the list marker, so the list-nested single-blank shape +/// is out of scope here. +fn is_blank_quote_line(line: &str) -> bool { + let indent = line.bytes().take_while(|&b| b == b' ').count(); + if indent > 3 { + return false; + } + let rest = &line[indent..]; + rest.contains('>') + && rest.chars().all(|c| c == '>' || c == ' ' || c == '\t') +} + +/// Whether a rendered line is quoted content (as opposed to a blank +/// quote line or a non-quote line): a `>` marker with non-blank text +/// after it (`> text`, `> ```rust`, `> | a |`, `> -----`). +fn is_quote_content_line(line: &str) -> bool { + let indent = line.bytes().take_while(|&b| b == b' ').count(); + if indent > 3 { + return false; + } + line[indent..] + .strip_prefix('>') + .is_some_and(|after| !after.trim().is_empty()) +} + +/// #1002: comrak's CommonMark renderer emits blank `> ` lines before a +/// blockquote's first child when that child is a fenced code block, a +/// table, a thematic break, or an HTML block — two at top level, so the +/// first save of any such quote pollutes the file (the PM document is +/// correct throughout and the output is already a fixpoint). Drop those +/// leading blanks from the rendered output, at the start of EVERY quote +/// run (start of file or right after a non-quote line, so a second +/// quote after a blank line is covered too). Blank lines BETWEEN blocks +/// inside a quote are the required separators and are kept: anything +/// after the run's first content line passes through untouched, as does +/// an all-blank run (a lone `>` with no quoted content). +fn strip_leading_blank_quote_lines(output: &str) -> String { + let lines: Vec<&str> = output.split('\n').collect(); + let mut result: Vec<&str> = Vec::with_capacity(lines.len()); + let mut at_quote_start = true; + let mut i = 0; + while i < lines.len() { + if at_quote_start && is_blank_quote_line(lines[i]) { + let mut j = i + 1; + while j < lines.len() && is_blank_quote_line(lines[j]) { + j += 1; + } + if j < lines.len() && is_quote_content_line(lines[j]) { + i = j; + continue; + } + } + result.push(lines[i]); + at_quote_start = !is_blank_quote_line(lines[i]) && !is_quote_content_line(lines[i]); + i += 1; + } + result.join("\n") +} + +/// Replace every link/image destination containing whitespace (space, +/// tab, newline, …) with a unique placeholder token, returning +/// (placeholder, raw destination) pairs for restoration after rendering +/// (#1019, #1423). The token is a valid bare destination (no whitespace +/// or characters comrak encodes), so the renderer emits it verbatim +/// exactly where the destination belongs. Reference-style links flow +/// through here too: comrak resolves a reference definition into the +/// referencing link's `url`, and the PM model stores that href directly, +/// so no separate definition path exists in this codec. +pub(crate) fn substitute_spaced_destinations<'a>(root: &'a AstNode<'a>) -> Vec<(String, String)> { + let mut substitutions: Vec<(String, String)> = Vec::new(); + let mut stack: Vec<&AstNode<'a>> = vec![root]; + while let Some(node) = stack.pop() { + stack.extend(node.children()); + let mut data = node.data.borrow_mut(); + let url = match &mut data.value { + NodeValue::Link(link) | NodeValue::Image(link) => &mut link.url, + _ => continue, + }; + if !url.contains(char::is_whitespace) { + continue; + } + if let Some(index) = substitutions + .iter() + .position(|(_, raw)| raw.as_str() == url.as_str()) + { + *url = substitutions[index].0.clone(); + } else { + let placeholder = format!( + "idweb-spaced-destination-{}-placeholder", + substitutions.len() + ); + let raw = std::mem::take(url); + *url = placeholder.clone(); + substitutions.push((placeholder, raw)); + } + } + substitutions +} + +/// Whether a converted AST node is block-level (as opposed to inline). +/// Used by the footnote_definition save path (#1031) to tell carried +/// block children apart from legacy inline children. +pub(crate) fn is_block_node(node: &AstNode<'_>) -> bool { + matches!( + node.data.borrow().value, + NodeValue::Paragraph + | NodeValue::Heading(_) + | NodeValue::BlockQuote + | NodeValue::List(_) + | NodeValue::Item(_) + | NodeValue::TaskItem(_) + | NodeValue::CodeBlock(_) + | NodeValue::HtmlBlock(_) + | NodeValue::ThematicBreak + | NodeValue::FrontMatter(_) + | NodeValue::Table(_) + | NodeValue::FootnoteDefinition(_) + ) +} + +/// Convert `ProseMirror` JSON to comrak AST. +/// Whether a JSON node is a `text` node carrying no marks (#1420). +/// Marked runs protect their edge spaces with the marked-span mechanism +/// (#1418); unmarked runs have no such protection, so the save direction +/// normalizes their edge whitespace instead (see +/// `normalize_inline_child_json`). +pub(crate) fn is_unmarked_text_json(node: &Value) -> bool { + node["type"].as_str() == Some("text") + && node["marks"] + .as_array() + .is_none_or(|marks| marks.is_empty()) +} + +/// Whether a JSON node is a `hard_break` — the boundary between two +/// rendered lines inside one block (#1420). +pub(crate) fn is_hard_break_json(node: &Value) -> bool { + node["type"].as_str() == Some("hard_break") +} + +/// Whether an unmarked text node renders as nothing but edge whitespace +/// (empty, or spaces/tabs only). Such a node never shields a neighbour's +/// edge from the line boundary: at a line edge its own whitespace is +/// normalized away too, and mid-line it is a separator either way (#1420). +pub(crate) fn is_whitespace_only_text_json(node: &Value) -> bool { + is_unmarked_text_json(node) + && node["text"] + .as_str() + .unwrap_or("") + .chars() + .all(|c| c == ' ' || c == '\t') +} + +/// Whether a hard break has no rendered content after it before the +/// block ends. Whitespace-only text and further breaks do not make a +/// trailing break interior content. This is the placement boundary for +/// #1388: CommonMark cannot spell a break after the last content of a +/// block, so normalize it away before building the comrak AST. +pub(crate) fn hard_break_is_trailing(content: &[Value], idx: usize) -> bool { + content[idx + 1..] + .iter() + .all(|sibling| is_hard_break_json(sibling) || is_whitespace_only_text_json(sibling)) +} + +/// Apply the save-side hard-break placement policy for a block's inline +/// children (#1388, transferring the #1492 placements): a hard break at +/// block end is dropped explicitly (the renderer silently drops it); a +/// heading is single-line CommonMark content, so an interior break +/// degrades to a space instead of becoming an unspellable backslash-newline. +/// Other interior paragraph breaks retain their existing LineBreak form. +pub(crate) fn normalize_hard_break_placement(node_type: &str, content: &[Value]) -> Vec { + if !matches!(node_type, "heading" | "paragraph") { + return content.to_vec(); + } + + let mut normalized = Vec::with_capacity(content.len()); + for (idx, child) in content.iter().enumerate() { + if !is_hard_break_json(child) { + normalized.push(child.clone()); + continue; + } + if hard_break_is_trailing(content, idx) { + continue; + } + if node_type == "heading" { + normalized.push(json!({"type": "text", "text": " "})); + } else { + normalized.push(child.clone()); + } + } + normalized +} + +/// Whether scanning `siblings` (in render order) reaches a line edge — +/// the start/end of the block or a `hard_break` — before any content +/// that renders something (#1420). +pub(crate) fn reaches_line_edge(siblings: impl Iterator) -> bool { + for sibling in siblings { + if is_hard_break_json(&sibling) { + return true; + } + if !is_whitespace_only_text_json(&sibling) { + return false; + } + } + true +} + +/// #1420: normalize one inline child of a block before conversion. +/// +/// Unmarked text runs are written verbatim on save, but CommonMark +/// reparse strips edge whitespace (up to 3 leading spaces per line, +/// trailing spaces ignored) and deletes a whitespace-only paragraph +/// outright, so the saved file and the reopened doc disagreed. The +/// pinned policy is normalize-at-save: trim an unmarked run's leading +/// spaces when it sits at a line start (block start or just after a +/// `hard_break`) and its trailing spaces when it sits at a line end +/// (block end or just before a `hard_break`), so the first saved file +/// is already the fixpoint. A whitespace-only run at a line edge +/// becomes an empty text node, so a whitespace-only paragraph saves as +/// an EMPTY paragraph instead of vanishing text. Interior runs (word +/// separators between words/marks) and marked runs are untouched. +pub(crate) fn normalize_inline_child_json( + content: &[Value], + idx: usize, +) -> std::borrow::Cow<'_, Value> { + let child = &content[idx]; + if !is_unmarked_text_json(child) { + return std::borrow::Cow::Borrowed(child); + } + let trim_start = reaches_line_edge(content[..idx].iter().rev().cloned()); + let trim_end = reaches_line_edge(content[idx + 1..].iter().cloned()); + if !trim_start && !trim_end { + return std::borrow::Cow::Borrowed(child); + } + let text = child["text"].as_str().unwrap_or(""); + let mut normalized = text; + if trim_start { + normalized = normalized.trim_start_matches([' ', '\t']); + } + if trim_end { + normalized = normalized.trim_end_matches([' ', '\t']); + } + if normalized == text { + return std::borrow::Cow::Borrowed(child); + } + let mut owned = child.clone(); + owned["text"] = json!(normalized); + std::borrow::Cow::Owned(owned) +} diff --git a/pkgs/id/src/web/markdown/parse_helpers.rs b/pkgs/id/src/web/markdown/parse_helpers.rs new file mode 100644 index 0000000000..69db0a19f4 --- /dev/null +++ b/pkgs/id/src/web/markdown/parse_helpers.rs @@ -0,0 +1,1285 @@ +//! Parse-side helpers for the Markdown -> ProseMirror conversion: +//! link reference definitions, footnote synthesis, and destination +//! protection. Split out of `markdown.rs` for #4704. + +use super::*; + +/// Append a PM `footnote_definition` node for every definition in +/// `markdown` that the comrak conversion did not already carry (#1565). +/// A label comrak emitted a node for is referenced (or at least +/// carried) and is left exactly as today; only the definitions comrak +/// dropped are synthesized, in source order, at the end of the doc. +/// The document's link reference definitions (`[label]: dest` lines, +/// footnote definitions excluded), verbatim, for the synthesis probe: +/// a reference-style link inside an unreferenced footnote resolves +/// against definitions elsewhere in the document, and a probe without +/// them converts the link to literal text (Codex P2). +/// The text after a link reference definition's destination, given +/// everything after its `]:` (accumulated across the definition's +/// lines). None while the destination itself is still incomplete -- +/// nothing collected yet, or an unterminated angle destination. +pub(crate) fn link_reference_definition_title_text(after: &str) -> Option<&str> { + let text = after.trim(); + if text.is_empty() { + return None; + } + let rest = if let Some(inner) = text.strip_prefix('<') { + // The destination ends at the first UNESCAPED '>': an + // escaped `\>` is destination text, and ending there left + // the remainder to be read as (invalid) trailing title + // text, dropping a valid definition (Codex P2 on #1565's + // twenty-first cut). + let pos = find_unescaped(inner, '>')?; + &inner[pos + 1..] + } else { + let end = text.find(char::is_whitespace).unwrap_or(text.len()); + &text[end..] + }; + Some(rest.trim_start()) +} + +/// The byte index of the first occurrence of `target` in `s` +/// outside a backslash escape (same escape rule as +/// contains_unescaped). +pub(crate) fn find_unescaped(s: &str, target: char) -> Option { + let mut escaped = false; + for (i, c) in s.char_indices() { + if escaped { + escaped = false; + continue; + } + if c == '\\' { + escaped = true; + continue; + } + if c == target { + return Some(i); + } + } + None +} + +/// Whether `s` contains `closer` outside a backslash escape: a +/// `\x` pair makes `x` literal text, and a `\\` pair is a +/// literal backslash, so the character after it counts again. +pub(crate) fn contains_unescaped(s: &str, closer: char) -> bool { + let mut escaped = false; + for c in s.chars() { + if escaped { + escaped = false; + continue; + } + if c == '\\' { + escaped = true; + continue; + } + if c == closer { + return true; + } + } + false +} + +/// Whether a link reference definition needs more lines: its +/// destination has not arrived yet, or a title that was started +/// (double quote, single quote, or open paren) has not closed +/// (Codex P2 on #1565's seventh cut -- definitions legitimately +/// span lines, with the destination or the title on a following +/// line). +pub(crate) fn link_reference_definition_needs_more(after: &str) -> bool { + let Some(title) = link_reference_definition_title_text(after) else { + return true; + }; + if title.is_empty() { + return false; + } + let closer = match title.as_bytes()[0] { + b'"' => '"', + 0x27 => 0x27 as char, + b'(' => ')', + _ => return false, + }; + // An ESCAPED delimiter is title text, not the closer: in + // `"first \"quoted` the title is still open, and treating it + // as complete stopped collection before the closing line, so + // the probe received an unterminated definition and the + // recovered footnote lost its link (Codex P2 on #1565's + // seventeenth cut). + !contains_unescaped(&title[1..], closer) +} + +/// Whether an accumulated candidate is a VALID link reference +/// definition: a destination is present and whatever follows it +/// is empty or a complete title. `link_reference_definition_title_text` +/// alone returns Some for ANY trailing text, including a bare word +/// (`[bad]: /bad extra`), which is not a title at all -- such a +/// line is no definition, and the lines around it stay one +/// paragraph (Codex P2 on #1565's twentieth cut). +pub(crate) fn link_reference_definition_is_valid(after: &str) -> bool { + // The destination itself must be syntactically valid, not + // merely followed by an empty or complete title: `/bad(` has + // an unmatched parenthesis, so the line is no definition at + // all, the definition-shaped line after it stays paragraph + // text, and synthesis must not promote it (Codex P2 on + // #1565's twenty-fourth cut). + if !link_reference_destination_is_valid(after) { + return false; + } + let Some(title) = link_reference_definition_title_text(after) else { + return false; + }; + if title.is_empty() { + return true; + } + // A complete title must END the definition: text after the + // closing delimiter (`[bad]: /bad "title" extra`) is not a + // title at all, and accepting it collected the next line as + // its own definition out of what is really one paragraph + // (Codex P2 on #1565's twenty-second cut). + let closer = match title.as_bytes()[0] { + b'"' => '"', + 0x27 => '\'', + b'(' => ')', + _ => return false, + }; + match find_unescaped(&title[1..], closer) { + Some(end) => { + // A parenthesized title cannot contain an unescaped + // `(`: `(a(b)` is not a title, so the candidate is + // no definition and the following definition-shaped + // line stays paragraph text instead of being + // promoted on its own (Codex P2 on #1565's + // twenty-ninth cut). + !(closer == ')' && contains_unescaped(&title[1..1 + end], '(')) + && title[end + 2..].trim().is_empty() + } + None => false, + } +} + +/// Whether the destination at the start of the accumulated +/// after-colon text is syntactically a link destination: an +/// angle destination ends at its unescaped `>` with no unescaped +/// `<` or line ending inside; a bare destination is non-empty, +/// contains no control characters, and keeps its parentheses +/// balanced (escapes exempt) -- the CommonMark destination +/// grammar. `/bad(` fails the balance check even though nothing +/// follows it, which the title-only validation above accepted. +pub(crate) fn link_reference_destination_is_valid(after: &str) -> bool { + let text = after.trim(); + if text.is_empty() { + return false; + } + if let Some(inner) = text.strip_prefix('<') { + let Some(pos) = find_unescaped(inner, '>') else { + return false; + }; + let dest = &inner[..pos]; + // A title after an angle destination must be separated + // from the closing `>` by whitespace: `"title"` + // has no separator, so the candidate is no definition at + // all and the lines around it stay one paragraph (Codex + // P2 on #1565's twenty-ninth cut). + let rest = &inner[pos + 1..]; + let separated = rest.is_empty() || rest.starts_with(char::is_whitespace); + return separated && !dest.contains('\n') && !contains_unescaped(dest, '<'); + } + let end = text.find(char::is_whitespace).unwrap_or(text.len()); + let dest = &text[..end]; + if dest.is_empty() { + return false; + } + let mut depth = 0usize; + let mut escaped = false; + for c in dest.chars() { + if escaped { + escaped = false; + continue; + } + match c { + '\\' => escaped = true, + '(' => depth += 1, + ')' => { + if depth == 0 { + return false; + } + depth -= 1; + } + c if c.is_control() => return false, + _ => {} + } + } + depth == 0 +} + +/// Whether anything follows the destination in the accumulated +/// after-colon text (a title, complete or still arriving). +pub(crate) fn link_reference_definition_has_title(after: &str) -> bool { + link_reference_definition_title_text(after).is_some_and(|t| !t.is_empty()) +} + +/// Whether a stripped line opens a link reference definition +/// (`[label]:`), footnote definitions excluded by the caller. +/// The index of the first UNESCAPED `]` in `s`: a `\]` inside +/// a reference label is label text, not the label's end (Codex +/// P2 on #1565's twelfth cut). Shared by the shape check and the +/// collector's destination extraction so they can never disagree +/// about where the label ends. +pub(crate) fn find_label_close(s: &str) -> Option { + let mut escaped = false; + for (i, c) in s.char_indices() { + if escaped { + escaped = false; + continue; + } + if c == '\\' { + escaped = true; + continue; + } + if c == ']' { + return Some(i); + } + } + None +} + +/// The closing bracket of a valid link reference label. CommonMark +/// labels cannot be empty/whitespace-only, contain an unescaped opening +/// bracket, or exceed 999 characters. Keeping this check with the shape +/// check prevents a malformed `[]:` candidate from splitting a paragraph +/// and promoting the next definition during synthesis (Codex P2 on +/// #1565's twenty-fifth cut). +pub(crate) fn link_reference_definition_label_close(s: &str) -> Option { + if !s.starts_with('[') { + return None; + } + let close = find_label_close(s)?; + let label = &s[1..close]; + if label.trim().is_empty() || label.chars().count() > 999 { + return None; + } + let mut escaped = false; + for c in label.chars() { + if escaped { + escaped = false; + continue; + } + match c { + '\\' => escaped = true, + '[' => return None, + _ => {} + } + } + Some(close) +} + +pub(crate) fn is_link_reference_definition_start(stripped: &str) -> bool { + match link_reference_definition_label_close(stripped) { + Some(close) => stripped[close + 1..].starts_with(':'), + None => false, + } +} + +pub(crate) fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { + let mut fence = FenceTracker::default(); + let mut fence_prefix = String::new(); + let mut html_prefix = String::new(); + let mut html = HtmlBlockTracker::default(); + let mut defs = Vec::new(); + // A link reference definition is only a definition where it can + // START a block: a definition-shaped line continuing a paragraph + // is paragraph text, and promoting it into the synthesis context + // would resolve references the document itself does not honor + // (Codex P2 on #1565's fifth cut). Track block-start eligibility: + // blank lines, headings, fences, HTML blocks, list/blockquote + // lines and other definitions leave the next line block-eligible; + // paragraph text does not. + let mut at_block_start = true; + // Inside a footnote definition's block (until a blank line or + // a new block starter), a reference-shaped line is the + // footnote's own lazy continuation, not a standalone + // definition: collecting it would make the synthesis context + // resolve as a link what the document keeps literal (Codex + // P2 on #1565's twelfth cut). + let mut in_footnote_block = false; + let lines: Vec<&str> = markdown.lines().collect(); + let mut i = 0; + while i < lines.len() { + let line = lines[i]; + // Indentation in COLUMNS: a tab advances to the next + // multiple of 4, so a tab-indented line is indented code + // (indent 4), not a paragraph line at indent 0 (Codex P2 + // on #1565's sixteenth cut). + let indent = { + let mut col = 0usize; + for c in line.chars() { + match c { + ' ' => col += 1, + '\t' => col += 4 - (col % 4), + _ => break, + } + } + col + }; + let stripped = line.trim_start_matches(' '); + if is_blank_line(stripped) { + // A blank line ENDS a blank-line-terminated HTML block; + // the tracker must see it or it suppresses every later + // definition (Codex P2 on #1565's sixth cut). + // A fully blank line carries no container prefix, so a + // container-scoped HTML block is over (eleventh cut). + if html.in_html() && html_prefix.contains('>') { + html.reset(); + html_prefix.clear(); + } + html.feed(stripped, true); + in_footnote_block = false; + at_block_start = true; + i += 1; + continue; + } + // An already-open HTML block sees every line, however + // indented: an indented closing marker still closes it, + // and gating this feed on indent left the tracker open + // forever, suppressing every later definition (Codex P2 + // on #1565's seventh cut). The indent limit applies only + // to recognizing an OPENING line. + let container_stripped = strip_container_prefixes(stripped); + // While an HTML block is open, feed it lines relative to + // the container it opened in: a blank line inside a + // blockquote is just `>` once spaces are stripped, and + // feeding that literal line kept the tracker open past the + // block's end, suppressing what follows it (Codex P2 on + // #1565's ninth cut). Mirrors fence_prefix below. + // (The recorded prefix's exact bytes vary -- `> ` vs `>` + // on a blank quote line -- so relativity is computed by + // re-stripping this line's own container prefixes.) + // An HTML block opened inside a blockquote ends implicitly + // when the container ends, exactly like a fence (tenth + // cut): a following line carrying no container prefix at + // all is outside the quote, so a marker-ended block (a + // comment) is over even without its closing marker (Codex + // P2 on #1565's eleventh cut: `> comments, and the split sibling lists this + // change emits are adjacent by construction - so on reparse the + // separator comes back as an HtmlBlock between the lists. It is + // a separator, not content: drop it when a neighbouring sibling + // is a list. An authored comment NOT next to + // a list still converts exactly as before (an htmlBlock + // code_block, #982). + if is_end_list_separator(child) + && ((idx > 0 && matches!(children[idx - 1].data.borrow().value, NodeValue::List(_))) + || children + .get(idx + 1) + .is_some_and(|c| matches!(c.data.borrow().value, NodeValue::List(_)))) + { + continue; + } + if matches!(child.data.borrow().value, NodeValue::List(_)) { + // #1370: a list converts to one or more sibling lists. + out.extend(convert_list_runs(child)); + } else { + let converted = convert_node(child, &[]); + if !converted.is_null() { + out.push(converted); + } + } + } + out +} + +/// True for the HtmlBlock comrak's renderer emits between adjacent +/// lists (see collect_block_children). +pub(crate) fn is_end_list_separator<'a>(node: &'a AstNode<'a>) -> bool { + match &node.data.borrow().value { + NodeValue::HtmlBlock(html) => html.literal.trim() == "", + _ => false, + } +} + +/// Convert a comrak list node to one or more ProseMirror list nodes. +/// +/// A pure list converts exactly as before (#997/#1036 attrs carried from +/// the source list). #1370: a list mixing task items with plain items +/// used to take its type from the first child only and convert the rest +/// by their own kind, producing a `task_list` holding a `list_item` (or +/// a plain list holding a `task_list_item`) - a shape the save-side +/// placement validation and the editor schema both forbid, so the +/// document could not be saved at all. Instead, group the items into +/// runs of one kind and emit one sibling list per run, in source order. +/// Ordered runs carry an `order` start offset by the items before them +/// so numbering renders unchanged; `tight` is carried from the source +/// list to every run. Placement validation and the editor schema are +/// untouched: every emitted list is pure. +/// #1380: the PM `delimiter` attr spelling for a comrak ordered-list +/// delimiter (`.` vs `)`). The editor schema mirrors these spellings. +pub(crate) fn delimiter_attr(delimiter: ListDelimType) -> &'static str { + match delimiter { + ListDelimType::Period => "period", + ListDelimType::Paren => "paren", + } +} + +/// #1380: read the PM `delimiter` attr back to a comrak delimiter. +/// Absent or unknown (legacy PM docs stored by the old codec, which +/// dropped the delimiter) defaults to Period - exactly how the old +/// codec saved every ordered list. +pub(crate) fn delimiter_from_attrs(json: &Value) -> ListDelimType { + match json["attrs"]["delimiter"].as_str() { + Some("paren") => ListDelimType::Paren, + _ => ListDelimType::Period, + } +} + +pub(crate) fn convert_list_runs<'a>(node: &'a AstNode<'a>) -> Vec { + let (list_type, start, tight, delimiter) = match &node.data.borrow().value { + NodeValue::List(list) => (list.list_type, list.start, list.tight, list.delimiter), + _ => return Vec::new(), + }; + // (is_task, items before this run, converted items) + let mut runs: Vec<(bool, usize, Vec)> = Vec::new(); + let mut seen = 0usize; + for child in node.children() { + let is_task = matches!(child.data.borrow().value, NodeValue::TaskItem(_)); + let item = convert_node(child, &[]); + if item.is_null() { + continue; + } + match runs.last_mut() { + Some((kind, _, items)) if *kind == is_task => items.push(item), + _ => runs.push((is_task, seen, vec![item])), + } + seen += 1; + } + runs.into_iter() + .map(|(is_task, offset, content)| match (is_task, list_type) { + (true, ListType::Ordered) => json!({ + "type": "task_list", + "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)}, + "content": content + }), + (true, ListType::Bullet) => json!({ + "type": "task_list", + "attrs": {"tight": tight}, + "content": content + }), + (false, ListType::Ordered) => json!({ + "type": "ordered_list", + "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)}, + "content": content + }), + (false, ListType::Bullet) => json!({ + "type": "bullet_list", + "attrs": {"tight": tight}, + "content": content + }), + }) + .collect() +} + +/// Collect list item children of a list node. +#[allow(dead_code)] +pub(crate) fn collect_list_items<'a>(node: &'a AstNode<'a>) -> Vec { + node.children() + .map(|child| convert_node(child, &[])) + .filter(|v| !v.is_null()) + .collect() +} + +/// The literal of an `HtmlInline` node, if `node` is one. +pub(crate) fn html_inline_literal<'a>(node: &'a AstNode<'a>) -> Option { + if let NodeValue::HtmlInline(html) = &node.data.borrow().value { + Some(html.clone()) + } else { + None + } +} + +/// Detect the split sized-linked-image sequence at the head of `children` +/// (#893): an `` `HtmlInline`, an `` `HtmlInline`, +/// and the closing `` `HtmlInline`. Comrak splits the HTML form the +/// save direction emits for a sized linked image into those three sibling +/// nodes; merged here they become one image node carrying `linkHref`, and +/// neither anchor piece falls through as literal text. The closing tag is +/// optional in the match (consumed when present) so a missing one cannot +/// strand the opening tag as text either. Returns the merged image node +/// and how many siblings it consumed. +pub(crate) fn linked_image_sequence<'a>(children: &[&'a AstNode<'a>]) -> Option<(Value, usize)> { + if children.len() < 2 { + return None; + } + let (href, link_title) = parse_anchor_tag(&html_inline_literal(children[0])?)?; + let img = parse_img_tag(&html_inline_literal(children[1])?)?; + let consumed = if children.len() >= 3 + && html_inline_literal(children[2]).is_some_and(|h| h.trim().eq_ignore_ascii_case("")) + { + 3 + } else { + 2 + }; + Some((image_with_link(img, &href, link_title.as_deref()), consumed)) +} + +/// Collect inline children of a node, flattening nested mark wrappers. +pub(crate) fn collect_inline_children<'a>( + node: &'a AstNode<'a>, + active_marks: &[Mark], +) -> Vec { + let mut result = Vec::new(); + let children: Vec<&AstNode<'a>> = node.children().collect(); + let mut index = 0; + + while index < children.len() { + // #893: merge a split sequence before the pieces + // are converted individually (see linked_image_sequence). + if let Some((img, consumed)) = linked_image_sequence(&children[index..]) { + result.push(img); + index += consumed; + continue; + } + + let child = children[index]; + index += 1; + let child_data = child.data.borrow(); + + // Check if this is a mark wrapper (Emph, Strong, Link) + let is_mark_wrapper = matches!( + child_data.value, + NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough + ); + drop(child_data); + + let converted = convert_node(child, active_marks); + if is_mark_wrapper { + // Convert returns an array of children with marks applied + if let Some(arr) = converted.as_array() { + for item in arr { + if !item.is_null() { + result.push(item.clone()); + } + } + } + } else if !converted.is_null() { + result.push(converted); + } + } + + result +} + +/// Get all text content from a node and its descendants. +pub(crate) fn get_text_content<'a>(node: &'a AstNode<'a>) -> String { + let mut text = String::new(); + collect_text(node, &mut text); + text +} + +/// Recursively collect text from a node. +pub(crate) fn collect_text<'a>(node: &'a AstNode<'a>, text: &mut String) { + let data = node.data.borrow(); + + match &data.value { + NodeValue::Text(t) => text.push_str(t.as_ref()), + NodeValue::Code(c) => text.push_str(&c.literal), + NodeValue::SoftBreak => text.push(' '), + NodeValue::LineBreak => text.push('\n'), + _ => { + drop(data); + for child in node.children() { + collect_text(child, text); + } + } + } +} + +/// #1417: serialize an image alt subtree back to markdown form. +/// +/// The inverse of the save direction's alt re-parse: emphasis, strong, +/// strikethrough, code spans and links keep their markup; literal text +/// is escaped so characters that were literal in the source (e.g. an +/// escaped `\\*`) stay literal when the stored form is re-parsed on +/// save. Nested images/links inside an alt are serialized recursively, +/// so a nested-link alt round-trips instead of flattening. +pub(crate) fn get_alt_markdown<'a>(node: &'a AstNode<'a>) -> String { + let mut out = String::new(); + for child in node.children() { + collect_alt_markdown(child, &mut out); + } + out +} + +pub(crate) fn collect_alt_markdown<'a>(node: &'a AstNode<'a>, out: &mut String) { + let data = node.data.borrow(); + match &data.value { + NodeValue::Text(t) => { + for ch in t.chars() { + if matches!(ch, '\\' | '*' | '_' | '`' | '[' | ']') { + out.push('\\'); + } + out.push(ch); + } + } + NodeValue::Code(c) => { + // Fence with one more backtick than the longest run inside. + let longest = c + .literal + .split(|ch| ch != '`') + .map(str::len) + .max() + .unwrap_or(0); + let fence = "`".repeat(longest + 1); + out.push_str(&fence); + if c.literal.starts_with('`') || c.literal.ends_with('`') { + out.push(' '); + out.push_str(&c.literal); + out.push(' '); + } else { + out.push_str(&c.literal); + } + out.push_str(&fence); + } + NodeValue::SoftBreak => out.push(' '), + NodeValue::LineBreak => out.push('\n'), + NodeValue::HtmlInline(html) => out.push_str(html), + NodeValue::Emph => { + drop(data); + out.push('*'); + for child in node.children() { + collect_alt_markdown(child, out); + } + out.push('*'); + } + NodeValue::Strong => { + drop(data); + out.push_str("**"); + for child in node.children() { + collect_alt_markdown(child, out); + } + out.push_str("**"); + } + NodeValue::Strikethrough => { + drop(data); + out.push_str("~~"); + for child in node.children() { + collect_alt_markdown(child, out); + } + out.push_str("~~"); + } + NodeValue::Link(link) => { + let url = link.url.clone(); + let title = link.title.clone(); + drop(data); + out.push('['); + for child in node.children() { + collect_alt_markdown(child, out); + } + out.push_str("]("); + out.push_str(&url); + if !title.is_empty() { + out.push_str(" \""); + out.push_str(&title.replace('"', "\\\"")); + out.push_str("\""); + } + out.push(')'); + } + NodeValue::Image(link) => { + let url = link.url.clone(); + let title = link.title.clone(); + drop(data); + out.push_str("!["); + for child in node.children() { + collect_alt_markdown(child, out); + } + out.push_str("]("); + out.push_str(&url); + if !title.is_empty() { + out.push_str(" \""); + out.push_str(&title.replace('"', "\\\"")); + out.push_str("\""); + } + out.push(')'); + } + _ => { + drop(data); + for child in node.children() { + collect_alt_markdown(child, out); + } + } + } +} + +/// #1417: re-parse a stored markdown-form alt into inline AST nodes in +/// `arena` (the save direction). Returns the paragraph's children, +/// detached and ready to append under an Image node. Falls back to a +/// single plain Text node when the alt does not parse to a paragraph +/// (defensive; plain alts parse to exactly that anyway). +pub(crate) fn alt_markdown_to_nodes<'a>(arena: &'a Arena<'a>, alt: &str) -> Vec<&'a AstNode<'a>> { + let options = commonmark_options(); + let root = parse_document(arena, alt, &options); + if let Some(paragraph) = root + .children() + .find(|n| matches!(n.data.borrow().value, NodeValue::Paragraph)) + { + let nodes: Vec<&'a AstNode<'a>> = paragraph.children().collect(); + for n in &nodes { + n.detach(); + } + if !nodes.is_empty() { + return nodes; + } + } + vec![&*arena.alloc(AstNode::from(NodeValue::Text(alt.to_owned().into())))] +} + +/// Escape a value for a double-quoted HTML attribute (#873): `&` first, so +/// the entities introduced here are not themselves re-escaped, then the +/// quote that would terminate the value, and `<`. +pub(crate) fn escape_attr_value(value: &str) -> String { + value + .replace('&', "&") + .replace('"', """) + .replace('<', "<") +} + +/// Decode the entities [`escape_attr_value`] can emit (plus `>`/`'` +/// and numeric single-quote) in one left-to-right pass, so `&quot;` +/// decodes to the literal text `"`, never to `"`. +pub(crate) fn decode_attr_entities(value: &str) -> String { + if !value.contains('&') { + return value.to_owned(); + } + let mut out = String::with_capacity(value.len()); + let mut rest = value; + while let Some(idx) = rest.find('&') { + out.push_str(&rest[..idx]); + let tail = &rest[idx..]; + let (decoded, len) = if let Some(t) = tail.strip_prefix(""") { + ('"', tail.len() - t.len()) + } else if let Some(t) = tail.strip_prefix("&") { + ('&', tail.len() - t.len()) + } else if let Some(t) = tail.strip_prefix("<") { + ('<', tail.len() - t.len()) + } else if let Some(t) = tail.strip_prefix(">") { + ('>', tail.len() - t.len()) + } else if let Some(t) = tail.strip_prefix("'") { + ('\'', tail.len() - t.len()) + } else if let Some(t) = tail.strip_prefix("'") { + ('\'', tail.len() - t.len()) + } else { + out.push('&'); + rest = &tail[1..]; + continue; + }; + out.push(decoded); + rest = &tail[len..]; + } + out.push_str(rest); + out +} + +/// Parse the attributes of an HTML tag, starting just past its ` std::collections::HashMap { + let bytes = html.as_bytes(); + let mut pos = tag_len; + let mut map = std::collections::HashMap::new(); + while pos < bytes.len() { + // Skip separators between attributes (whitespace, '/' of '/>'). + while pos < bytes.len() && (bytes[pos].is_ascii_whitespace() || bytes[pos] == b'/') { + pos += 1; + } + if pos >= bytes.len() || bytes[pos] == b'>' { + break; + } + // Attribute name: up to '=', whitespace, '/' or '>'. + let name_start = pos; + while pos < bytes.len() + && !bytes[pos].is_ascii_whitespace() + && !matches!(bytes[pos], b'=' | b'/' | b'>') + { + pos += 1; + } + if pos == name_start { + break; + } + let name = html[name_start..pos].to_ascii_lowercase(); + while pos < bytes.len() && bytes[pos].is_ascii_whitespace() { + pos += 1; + } + let mut value = String::new(); + if pos < bytes.len() && bytes[pos] == b'=' { + pos += 1; + while pos < bytes.len() && bytes[pos].is_ascii_whitespace() { + pos += 1; + } + if pos < bytes.len() && matches!(bytes[pos], b'"' | b'\'') { + let quote = bytes[pos]; + pos += 1; + let value_start = pos; + while pos < bytes.len() && bytes[pos] != quote { + pos += 1; + } + value = decode_attr_entities(&html[value_start..pos]); + if pos < bytes.len() { + pos += 1; // closing quote + } + } else { + let value_start = pos; + while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b'>' { + pos += 1; + } + value = decode_attr_entities(&html[value_start..pos]); + } + } + // First occurrence wins (HTML duplicate-attribute rule). + map.entry(name).or_insert(value); + } + map +} + +/// Parse an `` width/height value into a pixel count (#2180, +/// grammar pinned by triage task 3225). The whole stack is +/// numeric-pixel -- the PM node stores a JSON number, the emitter +/// writes bare integers, the editor renders `${width}px` -- so only +/// lossless normalizations are accepted: trim surrounding +/// whitespace, strip ONE trailing `px` suffix (ASCII +/// case-insensitive), then the rest must be a pixel integer, where a +/// decimal form counts only when its value is exactly integral +/// (`200.0` -> 200, `200.5` refused). Percents, other units, and +/// junk return `None`; the caller warns instead of dropping the +/// value silently, as the pre-#2180 bare-`u64` parse did. +pub(crate) fn parse_integral_decimal(raw: &str) -> Option { + let (negative, raw) = if let Some(raw) = raw.strip_prefix('-') { + (true, raw) + } else { + (false, raw.strip_prefix('+').unwrap_or(raw)) + }; + + let (mantissa, exponent) = if let Some(index) = raw.find(|ch| matches!(ch, 'e' | 'E')) { + (&raw[..index], raw[index + 1..].parse::().ok()?) + } else { + (raw, 0) + }; + let (integer, fractional) = mantissa.split_once('.').unwrap_or((mantissa, "")); + if integer.is_empty() && fractional.is_empty() { + return None; + } + if !integer.bytes().all(|byte| byte.is_ascii_digit()) + || !fractional.bytes().all(|byte| byte.is_ascii_digit()) + { + return None; + } + + let mut digits = String::with_capacity(integer.len() + fractional.len()); + digits.push_str(integer); + digits.push_str(fractional); + let significant = digits.trim_start_matches('0'); + if significant.is_empty() { + // Keep the exact zero spellings accepted by the former float parser, + // including -0.0, without converting through f64. + return Some(0); + } + + let fractional_digits = i32::try_from(fractional.len()).ok()?; + let scale = exponent.checked_sub(fractional_digits)?; + let integer = if scale >= 0 { + let trailing_zeroes = usize::try_from(scale).ok()?; + if significant.len().checked_add(trailing_zeroes)? > 20 { + return None; + } + let mut integer = String::with_capacity(significant.len() + trailing_zeroes); + integer.push_str(significant); + integer.push_str(&"0".repeat(trailing_zeroes)); + integer.parse::().ok()? + } else { + let trailing_zeroes = usize::try_from(scale.checked_neg()?).ok()?; + if trailing_zeroes > significant.len() { + return None; + } + let split = significant.len() - trailing_zeroes; + if significant[split..].bytes().any(|byte| byte != b'0') { + return None; + } + significant[..split].parse::().ok()? + }; + + if negative && integer != 0 { + return None; + } + Some(integer) +} + +pub(crate) fn parse_dimension(raw: &str) -> Option { + let trimmed = raw.trim(); + // Byte-wise suffix check: slicing the string at len()-2 to test + // the suffix would panic when that offset falls inside a multibyte + // UTF-8 character (e.g. fullwidth digits). When the last two bytes + // are the ASCII bytes p/x, len()-2 is a char boundary, so the + // slice below is safe. + let bytes = trimmed.as_bytes(); + let body = if bytes.len() >= 2 && bytes[bytes.len() - 2..].eq_ignore_ascii_case(b"px") { + &trimmed[..trimmed.len() - 2] + } else { + trimmed + }; + if let Ok(n) = body.parse::() { + return Some(n); + } + parse_integral_decimal(body) +} + +/// Parse an HTML `` tag and extract attributes into a `ProseMirror` image node. +/// +/// Returns `Some(json)` if the input looks like ``, otherwise `None`. +pub(crate) fn find_ascii_case_insensitive(haystack: &str, needle: &[u8]) -> Option { + haystack + .as_bytes() + .windows(needle.len()) + .position(|candidate| candidate.eq_ignore_ascii_case(needle)) +} + +pub(crate) fn parse_img_tag(html: &str) -> Option { + let trimmed = html.trim(); + let bytes = trimmed.as_bytes(); + if !bytes + .get(..4) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"' + ) + { + return None; + } + + let parsed = parse_tag_attrs(trimmed, 4); + let attr = |name: &str| parsed.get(name).map(String::as_str); + + let src = sanitize_image_url(attr("src")?); // src is required + let mut attrs = json!({"src": src}); + + if let Some(alt) = attr("alt") { + attrs["alt"] = json!(alt); + } + if let Some(title) = attr("title") { + attrs["title"] = json!(title); + } + if let Some(w) = attr("width") { + match parse_dimension(w) { + Some(n) => attrs["width"] = json!(n), + None => tracing::warn!("dropping unsupported image width {w:?} in import"), + } + } + if let Some(h) = attr("height") { + match parse_dimension(h) { + Some(n) => attrs["height"] = json!(n), + None => tracing::warn!("dropping unsupported image height {h:?} in import"), + } + } + + Some(json!({ + "type": "image", + "attrs": attrs + })) +} + +/// #5745: the allowed-scheme oracle for link URLs. +/// +/// A link URL is safe iff, after removing the characters browsers strip +/// while parsing a URL (TAB/LF/CR anywhere, leading C0 controls and +/// spaces), it either has no scheme at all — a relative or internal +/// reference, a fragment, a query, or a protocol-relative `//host/path` +/// reference, none of which can name an executable scheme — or its +/// scheme is exactly `http`, `https`, or `mailto` (case-insensitive). +/// Everything else (`javascript:`, `data:`, `vbscript:`, any unknown +/// scheme, and any obfuscation of those the stripping above exposes) +/// is unsafe. This explicit allowed set is the oracle every link test +/// for #5745 checks against; do not rely on browser sanitization. +pub(crate) fn link_url_is_safe(url: &str) -> bool { + let probe: String = url + .chars() + .filter(|c| !matches!(c, '\t' | '\n' | '\r')) + .collect(); + let probe = probe.trim_start_matches(|c: char| c.is_ascii_control() || c == ' '); + // A scheme exists only when a `:` precedes any `/`, `?`, or `#`. + let mut scheme_end = None; + for (i, c) in probe.char_indices() { + match c { + ':' => { + scheme_end = Some(i); + break; + } + '/' | '?' | '#' => break, + _ => {} + } + } + let Some(colon) = scheme_end else { + return true; // no scheme: relative / fragment / query / protocol-relative + }; + let scheme = &probe[..colon]; + let mut chars = scheme.chars(); + let valid_scheme = !scheme.is_empty() + && chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if !valid_scheme { + // A `:` in the first segment whose prefix is not a scheme + // (e.g. a relative path containing a colon) is not a scheme. + return true; + } + matches!( + scheme.to_ascii_lowercase().as_str(), + "http" | "https" | "mailto" + ) +} + +/// #5745: return `url` unchanged when [`link_url_is_safe`], else the +/// inert fragment `"#"`. The link text and mark survive; only the +/// executable target is removed, and `"#"` re-parses as a safe +/// fragment, so sanitized documents are a stable round-trip fixpoint. +pub(crate) fn sanitize_link_url(url: &str) -> String { + if link_url_is_safe(url) { + url.to_owned() + } else { + "#".to_owned() + } +} + +/// #6364: the image-specific allowed-scheme oracle. +/// +/// Image URLs allow relative/internal references and `http`/`https`, plus +/// data URLs whose media type is one of the supported raster formats. SVG is +/// deliberately excluded because it can contain active content. As with +/// links, inspect the scheme after stripping TAB/LF/CR and leading C0 +/// controls/spaces so browser URL parsing cannot expose an obfuscated scheme. +pub(crate) fn image_url_is_safe(url: &str) -> bool { + let probe: String = url + .chars() + .filter(|c| !matches!(c, '\t' | '\n' | '\r')) + .collect(); + let probe = probe.trim_start_matches(|c: char| c.is_ascii_control() || c == ' '); + + // A scheme exists only when a `:` precedes any `/`, `?`, or `#`. + let mut scheme_end = None; + for (i, c) in probe.char_indices() { + match c { + ':' => { + scheme_end = Some(i); + break; + } + '/' | '?' | '#' => break, + _ => {} + } + } + let Some(colon) = scheme_end else { + return true; + }; + + let scheme = &probe[..colon]; + let mut chars = scheme.chars(); + let valid_scheme = !scheme.is_empty() + && chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if !valid_scheme { + // Match the link oracle: a colon in a segment that is not a valid + // scheme (for example a relative path) does not introduce a scheme. + return true; + } + + let Some((raw_scheme, _)) = url.split_once(':') else { + return true; + }; + if raw_scheme.chars().any(|c| matches!(c, '\t' | '\n' | '\r')) { + return false; + } + + let scheme = scheme.to_ascii_lowercase(); + match scheme.as_str() { + "http" | "https" => true, + "data" => { + // Reject control-character spellings in the scheme or data URL + // header, even if removing them would produce an allowed MIME + // type. Controls in the encoded payload do not affect the scheme + // or media type and are left untouched. + let Some((header, _)) = url.split_once(',') else { + return false; + }; + if header.chars().any(|c| matches!(c, '\t' | '\n' | '\r')) { + return false; + } + let Some((metadata, _)) = probe[colon + 1..].split_once(',') else { + return false; + }; + let media_type = metadata.split(';').next().unwrap_or_default(); + matches!( + media_type.to_ascii_lowercase().as_str(), + "image/png" + | "image/gif" + | "image/jpeg" + | "image/webp" + | "image/avif" + | "image/bmp" + ) + } + _ => false, + } +} + +/// #6364: return `url` unchanged for an allowed image URL, otherwise the +/// inert fragment `#`. Keeping only the target neutralized preserves the +/// image node and makes the sanitized document a stable round-trip fixpoint. +pub(crate) fn sanitize_image_url(url: &str) -> String { + if image_url_is_safe(url) { + url.to_owned() + } else { + "#".to_owned() + } +} + +/// Parse an HTML `` opening tag, returning its `href` and optional +/// `title`. Returns `None` for anything else, including an anchor with no +/// (or an empty) `href`. +pub(crate) fn parse_anchor_tag(html: &str) -> Option<(String, Option)> { + let trimmed = html.trim(); + let after_name = trimmed.as_bytes().get(2).copied()?; + if !trimmed + .as_bytes() + .get(..2) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"') + { + return None; + } + let parsed = parse_tag_attrs(trimmed, 2); + let href = parsed.get("href")?; + if href.is_empty() { + return None; + } + let title = parsed.get("title").filter(|t| !t.is_empty()).cloned(); + // #5745: a raw-HTML anchor wrapping an image gets the same + // allowed-scheme treatment as a Markdown link; an unsafe href is + // neutralized (not dropped, which would strand the raw anchor tag + // as a verbatim html_inline atom carrying the executable URL). + Some((sanitize_link_url(href), title)) +} + +/// Attach a wrapping anchor's link to an image node (#880/#893), in the +/// same `linkHref`/`linkTitle` attrs the markdown `Image` arm produces. +pub(crate) fn image_with_link(mut img: Value, href: &str, link_title: Option<&str>) -> Value { + img["attrs"]["linkHref"] = json!(href); + if let Some(title) = link_title { + img["attrs"]["linkTitle"] = json!(title); + } + img +} + +/// Parse the combined `` form (#893) — the +/// sized linked image emission when comrak keeps it in a single literal +/// (e.g. an `HtmlBlock`) instead of splitting it into sibling `HtmlInline` +/// nodes (that split form is merged in `collect_inline_children`). +pub(crate) fn parse_linked_img_tag(html: &str) -> Option { + let trimmed = html.trim(); + let (href, link_title) = parse_anchor_tag(trimmed)?; + let img_start = find_ascii_case_insensitive(trimmed, b"') + || find_ascii_case_insensitive(&trimmed[img_start..], b"").is_none() + { + return None; + } + let img = parse_img_tag(&trimmed[img_start..])?; + Some(image_with_link(img, &href, link_title.as_deref())) +} + +/// Placement categories for the #1043 validation walk. A node whose type +/// is not listed here is left to `json_to_ast`, which reports it as +/// `ConversionError::UnknownType` — validation never masks that error. +/// (`front_matter` is intentionally unlisted: its doc-first-child rule +/// needs the child index, so `validate_placement` checks it directly.) +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Placement { + /// Block-level node (`paragraph`, `table`, lists, …). + Block, + /// Inline node (`text`, `image`, `hard_break`, …). + Inline, + /// `list_item` — only legal directly inside a bullet/ordered list. + ListItem, + /// `task_list_item` — only legal directly inside a `task_list`. + TaskListItem, + /// `table_row` — only legal directly inside a `table`. + TableRow, + /// `table_header` / `table_cell` — only legal inside a `table_row`. + TableCell, +} + +pub(crate) fn placement_of(node_type: &str) -> Option { + match node_type { + "paragraph" + | "heading" + | "blockquote" + | "code_block" + | "horizontal_rule" + | "bullet_list" + | "ordered_list" + | "task_list" + | "table" + | "footnote_definition" => Some(Placement::Block), + "text" | "image" | "hard_break" | "html_inline" | "footnote_reference" => { + Some(Placement::Inline) + } + "list_item" => Some(Placement::ListItem), + "task_list_item" => Some(Placement::TaskListItem), + "table_row" => Some(Placement::TableRow), + "table_header" | "table_cell" => Some(Placement::TableCell), + _ => None, + } +} + +/// Whether a child of category `child` may appear directly inside a +/// parent of type `parent`. Mirrors the comrak AST containment rules for +/// the node kinds this codec emits, at the `ProseMirror` level. +pub(crate) fn placement_allowed(parent: &str, child: Placement) -> bool { + match parent { + // The document and block containers hold blocks only. + "doc" | "blockquote" | "list_item" | "task_list_item" => child == Placement::Block, + // Inline containers hold inline content only. + "paragraph" | "heading" => child == Placement::Inline, + "bullet_list" | "ordered_list" => child == Placement::ListItem, + "task_list" => child == Placement::TaskListItem, + "table" => child == Placement::TableRow, + "table_row" => child == Placement::TableCell, + // PM table cells wrap blocks (unwrapped during conversion) and + // footnote definitions carry inline content on the PM side + // (re-wrapped during conversion, #945); both shapes are legal. + "table_header" | "table_cell" | "footnote_definition" => { + child == Placement::Block || child == Placement::Inline + } + "code_block" => false, + // Inline leaves and anything unlisted impose no child rules here; + // structural surprises inside them are json_to_ast's to report. + _ => true, + } +} + +/// Validate block/inline placement over a `ProseMirror` document before +/// conversion (#1043). `json_to_ast` places any known node type anywhere; +/// a misplaced node (a `text` node directly under `doc`, a `paragraph` +/// inside a `paragraph`, …) produces an ill-formed comrak AST that +/// panics the formatter in debug builds and silently emits invalid +/// markdown in release builds. Reject those documents up front with +/// `ConversionError::MisplacedNode` instead. +pub(crate) fn validate_placement(doc: &Value) -> Result<(), ConversionError> { + pub(crate) fn walk( + node: &Value, + parent: Option<&str>, + index_in_parent: Option, + ) -> Result<(), ConversionError> { + let Some(node_type) = node["type"].as_str() else { + // Missing type: json_to_ast reports MissingType; keep that + // error's precedence. + return Ok(()); + }; + // #1369: `front_matter` is legal only as the first child of `doc` + // (comrak only parses it there). Anything else is misplaced. + if node_type == "front_matter" { + let first_child_of_doc = parent == Some("doc") && index_in_parent == Some(0); + if !first_child_of_doc { + return Err(ConversionError::MisplacedNode { + parent: parent.unwrap_or("").to_owned(), + child: node_type.to_owned(), + }); + } + } else if let Some(parent_type) = parent + && let Some(category) = placement_of(node_type) + && !placement_allowed(parent_type, category) + { + return Err(ConversionError::MisplacedNode { + parent: parent_type.to_owned(), + child: node_type.to_owned(), + }); + } + // code_block content is literal text children only. + if node_type == "code_block" { + if let Some(content) = node["content"].as_array() { + for child in content { + if child["type"].as_str() != Some("text") { + return Err(ConversionError::MisplacedNode { + parent: node_type.to_owned(), + child: child["type"].as_str().unwrap_or("").to_owned(), + }); + } + } + } + return Ok(()); + } + // front_matter carries no PM child content (its payload is the + // `text` attr); nothing to recurse into. + if node_type == "front_matter" { + if node["content"].as_array().is_some_and(|c| !c.is_empty()) { + return Err(ConversionError::MisplacedNode { + parent: node_type.to_owned(), + child: "".to_owned(), + }); + } + return Ok(()); + } + if let Some(content) = node["content"].as_array() { + for (idx, child) in content.iter().enumerate() { + walk(child, Some(node_type), Some(idx))?; + } + } + Ok(()) + } + walk(doc, None, None) +}