Skip to main content

quillmark_content/
model.rs

1//! The `Content` content model — one text sequence per field carrying line
2//! attributes, anchored marks, and embedded islands, over a single coordinate
3//! space of Unicode scalar values (Rust `char`).
4//!
5//! This is the freeze (issue #831): the mark set, the three
6//! normalization rules, and the invariants are what canonical serialization
7//! commits to. Everything an editor disagrees on (edge-expand,
8//! adjacent-merge-at-insertion) is *not* encoded — the model only ever stores
9//! the resulting range, so the stored form is identical whatever the editor
10//! did.
11
12use crate::normalize::is_bidi_char;
13use serde_json::Value as JsonValue;
14
15/// A position in a [`Content`], counted in Unicode scalar values (USV) — never
16/// bytes, never UTF-16 units. One astral char is 1 USV / 4 UTF-8 bytes / 2
17/// UTF-16 units. Conversions to/from the JS (UTF-16) and Rust (UTF-8)
18/// boundaries live in [`crate::usv`].
19pub type Usv = usize;
20
21/// U+FFFC OBJECT REPLACEMENT CHARACTER — the single-USV slot an island occupies
22/// in the content. One slot per island; every slot has a backing island. A stray
23/// slot (or a slot with no island) is an invariant violation.
24pub const ISLAND_SLOT: char = '\u{FFFC}';
25
26/// One content field as a content: the text plus the structure that rides on it.
27///
28/// Invariants (established once by import normalization, checked by
29/// [`Content::validate`]): the text holds no `\r` and no bidi controls; the
30/// count of [`ISLAND_SLOT`] equals `islands.len()`; `lines.len()` equals the
31/// number of `\n`-separated segments; marks are normalized (sorted, unioned).
32#[derive(Debug, Clone, PartialEq)]
33pub struct Content {
34    /// The content. `\n` is a line boundary; [`ISLAND_SLOT`] is an island slot.
35    pub text: String,
36    /// One entry per `\n`-separated segment of `text`, in order. The line tree
37    /// is *derived* from this flat list plus each line's `containers` path — it
38    /// is never stored, so a split/join is a single-char edit with no identity
39    /// crisis (there are no paragraph IDs).
40    pub lines: Vec<Line>,
41    /// Marks over char ranges, kept normalized: sorted by
42    /// `(start, end, kind-ord, attrs)`, same-kind formatting marks unioned.
43    pub marks: Vec<Mark>,
44    /// One entry per [`ISLAND_SLOT`], in slot order (ascending char position).
45    pub islands: Vec<Island>,
46}
47
48/// A line's attributes: its block role plus the container path it sits in.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Line {
51    pub kind: LineKind,
52    /// Ancestor containers, outermost first. A multi-paragraph list item is two
53    /// `Para` lines sharing one `[ListItem]` path; a paragraph in a quote in a
54    /// list item is `[ListItem, Quote]`.
55    pub containers: Vec<Container>,
56    /// Whether this line continues the previous line's *block* across a hard
57    /// line break (no paragraph break between), rather than starting a new
58    /// block. `false` = a new block (paragraph spacing on either side); `true` =
59    /// a within-block line break (markdown hard break; consecutive lines of one
60    /// code fence). The first line is always `false`. This is what keeps a hard
61    /// break (backend `#linebreak()`) distinct from a paragraph boundary through
62    /// the freeze, and what groups a code fence's lines without an
63    /// adjacency heuristic.
64    pub continues: bool,
65}
66
67/// The block role of a line. The tree between lines is inferred: two adjacent
68/// lines with equal `kind`+`containers` are two blocks of that role (e.g. two
69/// paragraphs), never one.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum LineKind {
72    Para,
73    /// ATX/Setext heading, level 1..=6.
74    Heading {
75        level: u8,
76    },
77    /// A line of a code block. `lang` is the (sanitized) info string, shared by
78    /// every line of the same block.
79    Code {
80        lang: Option<String>,
81    },
82    /// A block-level island: the line's sole content is one [`ISLAND_SLOT`].
83    Island,
84    /// A thematic break (`---`/`***`/`___`). The line carries no text — the
85    /// break is the line itself, parallel to how an island's content is its
86    /// one slot char.
87    Rule,
88}
89
90/// A container a line nests inside. The ancestor path is a `Vec<Container>`.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Container {
93    /// A list item. `ordered` distinguishes `1.` from `-`; `start` is the list's
94    /// first number (1 by default); `ordinal` is this item's 0-based index in
95    /// its list. Two *adjacent* lines belong to the same item iff their whole
96    /// container path (ordinals included) is equal — so a multi-paragraph item
97    /// is two lines sharing one `ListItem`, while the next item differs by
98    /// `ordinal`. (Identity is path **plus contiguity**: two sibling inner lists
99    /// under one outer item can produce equal first-item paths, distinguished
100    /// only by the non-adjacency of their runs.) Positional and deterministic —
101    /// no minted ids.
102    ListItem {
103        ordered: bool,
104        start: u64,
105        ordinal: u64,
106    },
107    /// A block quote. Adjacent lines sharing `[Quote]` are one multi-paragraph
108    /// quote; two adjacent separate quotes are not distinguished (they merge on
109    /// round-trip — a documented canonicalization).
110    Quote,
111}
112
113/// A mark over a char range `[start, end)`. `start == end` (zero-width) is legal
114/// only for [`MarkKind::Anchor`]; normalization drops zero-width formatting.
115#[derive(Debug, Clone, PartialEq)]
116pub struct Mark {
117    pub start: Usv,
118    pub end: Usv,
119    pub kind: MarkKind,
120}
121
122/// The mark set — **open**: an unknown kind round-trips as [`MarkKind::Unknown`],
123/// absorbed as a new *type*, never a changed semantics of a known one. Two
124/// algebra classes: formatting is a property of a range (two coincident are
125/// redundant); identity is a handle (two over the same range are two things).
126#[derive(Debug, Clone, PartialEq)]
127pub enum MarkKind {
128    // Formatting — round-trippable projection marks. `is_formatting()`.
129    Strong,
130    Emph,
131    Underline,
132    Strike,
133    Code,
134    Link {
135        url: String,
136    },
137    // Identity — a handle, not a property. Never merged, may be zero-width.
138    /// A comment thread or stable anchor, carried by id and rebased across
139    /// edits like any position. No markdown projection (omitted on export;
140    /// survives via diff-rebase).
141    Anchor {
142        id: String,
143    },
144    // Open-set escape hatch — an unknown mark type, round-tripped opaque.
145    Unknown {
146        tag: String,
147        attrs: JsonValue,
148    },
149}
150
151/// A structured object with no honest text encoding — a table, figure, or future
152/// embed — occupying one [`ISLAND_SLOT`] in the content.
153#[derive(Debug, Clone, PartialEq)]
154pub struct Island {
155    /// Minted, `$id`-style stable id — once islands mint their own ids, this
156    /// becomes the sole source of hash nondeterminism; text stays deterministic.
157    pub id: String,
158    /// Island type discriminator (`"table"`, `"image"`, …). Unknown types
159    /// round-trip opaque.
160    pub island_type: String,
161    /// Typed payload. Recursively key-sorted by normalization so it hashes
162    /// deterministically despite `serde_json`'s `preserve_order`.
163    pub props: JsonValue,
164    /// How faithfully the markdown projection can carry this island.
165    pub loss: Loss,
166}
167
168/// The markdown-projection loss class of an island.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum Loss {
171    /// Markdown carries it faithfully (round-trips identically).
172    Lossless,
173    /// Markdown carries an approximation (round-trips visibly, not identically).
174    Degraded,
175    /// No markdown encoding; export emits a placeholder only.
176    Unrepresentable,
177}
178
179impl MarkKind {
180    /// Formatting marks are a property of a range and union when coincident;
181    /// identity/unknown marks are handles and never merge (Spike-A rules).
182    pub fn is_formatting(&self) -> bool {
183        matches!(
184            self,
185            MarkKind::Strong
186                | MarkKind::Emph
187                | MarkKind::Underline
188                | MarkKind::Strike
189                | MarkKind::Code
190                | MarkKind::Link { .. }
191        )
192    }
193
194    /// Total order over kinds for the canonical sort tie-break, after
195    /// `(start, end)`. Stable across releases — part of the freeze.
196    pub fn ord(&self) -> u8 {
197        match self {
198            MarkKind::Strong => 0,
199            MarkKind::Emph => 1,
200            MarkKind::Underline => 2,
201            MarkKind::Strike => 3,
202            MarkKind::Code => 4,
203            MarkKind::Link { .. } => 5,
204            MarkKind::Anchor { .. } => 6,
205            MarkKind::Unknown { .. } => 7,
206        }
207    }
208
209    /// Attribute tie-break string, appended after `ord` in the canonical sort so
210    /// two marks that differ only in attrs order deterministically. Also the
211    /// grouping key for same-kind union (two formatting marks union only when
212    /// this matches — e.g. two `link`s union only at the same url).
213    pub fn attrs_key(&self) -> String {
214        match self {
215            MarkKind::Link { url } => url.clone(),
216            MarkKind::Anchor { id } => id.clone(),
217            MarkKind::Unknown { tag, attrs } => {
218                // Attrs sorted so the key is order-insensitive.
219                format!("{}\u{0}{}", tag, canonical_json_string(attrs))
220            }
221            _ => String::new(),
222        }
223    }
224}
225
226/// A `serde_json::Value` rendered to a string with object keys recursively
227/// sorted — order-insensitive, so it is a stable comparison/grouping key.
228fn canonical_json_string(v: &JsonValue) -> String {
229    serde_json::to_string(&sorted_value(v)).unwrap_or_default()
230}
231
232/// Rebuild `v` with every object's keys sorted, recursively. Pins island
233/// `props` (and unknown-mark attrs) against `preserve_order` leaking insertion
234/// order into the canonical bytes / content hash (Spike C carry-forward). For
235/// an owned tree, prefer [`sort_keys_owned`] — it reorders in place without
236/// cloning the leaves.
237pub(crate) fn sorted_value(v: &JsonValue) -> JsonValue {
238    match v {
239        JsonValue::Array(items) => JsonValue::Array(items.iter().map(sorted_value).collect()),
240        JsonValue::Object(map) => {
241            let mut keys: Vec<&String> = map.keys().collect();
242            keys.sort();
243            let mut out = serde_json::Map::with_capacity(map.len());
244            for k in keys {
245                out.insert(k.clone(), sorted_value(&map[k]));
246            }
247            JsonValue::Object(out)
248        }
249        other => other.clone(),
250    }
251}
252
253/// Whether every object in `v` already has its keys in ascending order,
254/// recursively — the cheap allocation-free check that lets a re-normalize skip
255/// rebuilding an already-canonical `props`/`attrs` tree via [`sorted_value`].
256/// Once normalized, an untouched tree stays sorted, so a per-keystroke
257/// re-normalize pays a scan instead of a full clone.
258pub(crate) fn is_value_key_sorted(v: &JsonValue) -> bool {
259    match v {
260        JsonValue::Array(items) => items.iter().all(is_value_key_sorted),
261        JsonValue::Object(map) => {
262            map.keys().zip(map.keys().skip(1)).all(|(a, b)| a <= b)
263                && map.values().all(is_value_key_sorted)
264        }
265        _ => true,
266    }
267}
268
269/// The owned twin of [`sorted_value`]: reorder every object's keys by **moving**
270/// each entry into a freshly key-sorted map, recursively. Same canonical result
271/// — the fixed struct keys land alphabetically and any already-sorted `props`/
272/// `attrs` re-sort to themselves — but the leaves (the `text` string, mark
273/// attrs, arrays) are moved rather than deep-cloned, so a tree built once by
274/// `to_value` is canonicalized without a second full clone. Re-sorting a new
275/// `serde_json::Map` (not sorting in place) keeps this independent of whether
276/// `serde_json`'s `preserve_order` feature is on in the crate graph.
277pub(crate) fn sort_keys_owned(v: JsonValue) -> JsonValue {
278    match v {
279        JsonValue::Array(items) => {
280            JsonValue::Array(items.into_iter().map(sort_keys_owned).collect())
281        }
282        JsonValue::Object(map) => {
283            let mut entries: Vec<(String, JsonValue)> = map.into_iter().collect();
284            entries.sort_by(|a, b| a.0.cmp(&b.0));
285            let mut out = serde_json::Map::with_capacity(entries.len());
286            for (k, child) in entries {
287                out.insert(k, sort_keys_owned(child));
288            }
289            JsonValue::Object(out)
290        }
291        other => other,
292    }
293}
294
295/// Ways a [`Content`] can violate its invariants. Returned by
296/// [`Content::validate`]; import normalization guarantees none of these.
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub enum Invariant {
299    /// `\r` in the text (line endings must be normalized to `\n`).
300    CarriageReturn,
301    /// A bidi formatting control in the text.
302    BidiControl(char),
303    /// `island_slot_count != islands.len()`.
304    IslandSlotMismatch { slots: usize, islands: usize },
305    /// `lines.len() != newline_segment_count`.
306    LineCountMismatch { lines: usize, segments: usize },
307    /// A mark range runs past the content or is inverted (`start > end`).
308    MarkOutOfRange { start: Usv, end: Usv, len: Usv },
309    /// A zero-width formatting mark survived normalization.
310    ZeroWidthFormatting { at: Usv },
311    /// A heading level outside 1..=6.
312    BadHeadingLevel(u8),
313    /// The first line has `continues: true` (nothing precedes it to continue).
314    FirstLineContinues,
315    /// An [`MarkKind::Unknown`] reused a reserved built-in `type` name.
316    ReservedUnknownTag(String),
317    /// A formatting mark edge sits on a `\n` (normalization should have trimmed
318    /// it) — a hand-built content that skipped `normalize`.
319    MarkEdgeOnNewline { at: Usv },
320    /// A table island's `aligns` length differs from its column count (the
321    /// header width). `normalize` syncs `aligns` to the column count.
322    TableAlignsMismatch { aligns: usize, cols: usize },
323    /// A table island body row's width differs from the column count (the header
324    /// width). `normalize` pads short rows (and the header) to the widest.
325    TableRaggedRow { row: usize, width: usize, cols: usize },
326    /// A table cell's text carries a `\n` — cells are single-line (a newline
327    /// would break the exported table). `cell` is the flat header-then-rows
328    /// index; `normalize` rewrites the newline to a space.
329    TableCellNewline { cell: usize },
330    /// Two islands share an `id`. Ids are a minted, stable identity (the sole
331    /// source of hash nondeterminism); import mints them by index so they never
332    /// collide, but a hand-built or round-tripped content can. Downstream code
333    /// that keys islands by id would otherwise silently pick the wrong one.
334    IslandIdCollision { id: String },
335    /// A table island's `header` prop is present but not a JSON array — it
336    /// cannot carry column cells. `normalize` rewrites a non-array header to an
337    /// empty array (a zero-column, content-free table).
338    TableHeaderNotArray,
339}
340
341impl Content {
342    /// An empty content: one empty `Para` line, no marks, no islands.
343    pub fn empty() -> Self {
344        Content {
345            text: String::new(),
346            lines: vec![Line {
347                kind: LineKind::Para,
348                containers: Vec::new(),
349                continues: false,
350            }],
351            marks: Vec::new(),
352            islands: Vec::new(),
353        }
354    }
355
356    /// Total length in USV.
357    pub fn len_usv(&self) -> Usv {
358        self.text.chars().count()
359    }
360
361    /// Whether this content satisfies the `richtext(inline)` constraint: exactly
362    /// one `Para` line, sitting in no container, with no islands. A single line
363    /// can never `continues` (line 0 is always `false`), so that dimension is
364    /// implied. [`Content::empty`] is inline (one empty `Para`), so a blank or
365    /// zero-filled inline field passes.
366    pub fn is_inline(&self) -> bool {
367        self.islands.is_empty()
368            && self.lines.len() == 1
369            && self.lines[0].kind == LineKind::Para
370            && self.lines[0].containers.is_empty()
371    }
372
373    /// Whether this content satisfies the `plaintext` constraint: no marks, no
374    /// islands, and every line is a plain `Para` sitting in no container. It is
375    /// the multi-line generalization of [`is_inline`](Self::is_inline) (which
376    /// additionally pins the content to one line) with the mark/island exclusion
377    /// made explicit — a plaintext value carries prose the author navigates but
378    /// no formatting. `continues` is unconstrained: a lone `\n` may be a
379    /// within-paragraph break. [`Content::empty`] is plain.
380    ///
381    /// This is the plaintext analogue of `is_inline`, enforced at coercion and
382    /// validation with the `NotPlain` error; the distinguishing property of
383    /// plaintext over `richtext { marks: [] }` is the *literal* codec
384    /// ([`crate::import::from_plaintext`]), not this predicate.
385    pub fn is_plain(&self) -> bool {
386        self.marks.is_empty()
387            && self.islands.is_empty()
388            && self
389                .lines
390                .iter()
391                .all(|l| l.kind == LineKind::Para && l.containers.is_empty())
392    }
393
394    /// Whether the content carries no renderable content: the text is empty or
395    /// whitespace-only. An island slot ([`ISLAND_SLOT`], U+FFFC) is not
396    /// whitespace, so an island-bearing content is never blank. Body-disabled
397    /// validation and round-trip emit key on it.
398    pub fn is_blank(&self) -> bool {
399        self.text.trim().is_empty()
400    }
401
402    /// Number of `\n`-separated segments — the required `lines.len()`.
403    pub fn segment_count(&self) -> usize {
404        self.text.chars().filter(|c| *c == '\n').count() + 1
405    }
406
407    /// Normalize marks in place: drop zero-width formatting, union same-kind
408    /// formatting that is adjacent or overlapping, recursively key-sort island
409    /// props and unknown-mark attrs, then sort marks canonically. Idempotent —
410    /// the fixed point the canonical serialization commits to.
411    pub fn normalize(&mut self) {
412        // Islands: canonicalize props key order. A table island's cells carry
413        // inline `{text, marks}`; repair its shape (pad the header/rows/aligns to
414        // one column count, rewrite any cell `\n` to a space) and canonicalize
415        // each cell's marks (sort, union, drop zero-width) first so equal cells
416        // serialize to equal bytes and `validate` holds — the props are
417        // otherwise opaque here.
418        for island in &mut self.islands {
419            crate::serial::normalize_island_structure(island);
420            // Rebuild props only when a key is actually out of order — an
421            // untouched island (a pure text splice) stays sorted, so this skips
422            // the deep clone on the common per-keystroke path.
423            if !is_value_key_sorted(&island.props) {
424                island.props = sorted_value(&island.props);
425            }
426        }
427        for mark in &mut self.marks {
428            if let MarkKind::Unknown { attrs, .. } = &mut mark.kind {
429                if !is_value_key_sorted(attrs) {
430                    *attrs = sorted_value(attrs);
431                }
432            }
433        }
434        // A formatting mark's edges never sit on a line boundary: markdown can't
435        // bold a `\n`, so two producers that disagree only about whether the
436        // boundary is "inside" the mark must canonicalize to the same bounds.
437        // Trim leading/trailing `\n` (interior boundaries are kept — a mark may
438        // legitimately span lines). Zero-width results are dropped below.
439        // Skip the full-text char collection when nothing needs trimming.
440        if self.marks.iter().any(|m| m.kind.is_formatting()) {
441            let chars: Vec<char> = self.text.chars().collect();
442            for m in &mut self.marks {
443                if m.kind.is_formatting() {
444                    while m.start < m.end && chars.get(m.start) == Some(&'\n') {
445                        m.start += 1;
446                    }
447                    while m.end > m.start && chars.get(m.end - 1) == Some(&'\n') {
448                        m.end -= 1;
449                    }
450                }
451            }
452        }
453        self.marks = normalize_marks(std::mem::take(&mut self.marks));
454    }
455
456    /// Mark `type` names the projection reserves; an [`MarkKind::Unknown`] may
457    /// not reuse one (its serialization would parse back as the built-in,
458    /// silently dropping its attrs — non-injective). Checked by [`Content::validate`].
459    pub const RESERVED_MARK_TYPES: [&'static str; 7] = [
460        "strong",
461        "emph",
462        "underline",
463        "strike",
464        "code",
465        "link",
466        "anchor",
467    ];
468
469    /// Check every invariant. `Ok(())` on a well-formed content. Import
470    /// guarantees this; a hand-built content should be run through it in tests.
471    pub fn validate(&self) -> Result<(), Invariant> {
472        let mut slots = 0usize;
473        for c in self.text.chars() {
474            if c == '\r' {
475                return Err(Invariant::CarriageReturn);
476            }
477            if is_bidi_char(c) {
478                return Err(Invariant::BidiControl(c));
479            }
480            if c == ISLAND_SLOT {
481                slots += 1;
482            }
483        }
484        if slots != self.islands.len() {
485            return Err(Invariant::IslandSlotMismatch {
486                slots,
487                islands: self.islands.len(),
488            });
489        }
490        let segments = self.segment_count();
491        if self.lines.len() != segments {
492            return Err(Invariant::LineCountMismatch {
493                lines: self.lines.len(),
494                segments,
495            });
496        }
497        if self.lines.first().is_some_and(|l| l.continues) {
498            return Err(Invariant::FirstLineContinues);
499        }
500        let len = self.len_usv();
501        let chars: Vec<char> = self.text.chars().collect();
502        for m in &self.marks {
503            if m.start > m.end || m.end > len {
504                return Err(Invariant::MarkOutOfRange {
505                    start: m.start,
506                    end: m.end,
507                    len,
508                });
509            }
510            if m.start == m.end && m.kind.is_formatting() {
511                return Err(Invariant::ZeroWidthFormatting { at: m.start });
512            }
513            if m.kind.is_formatting() {
514                if chars.get(m.start) == Some(&'\n') {
515                    return Err(Invariant::MarkEdgeOnNewline { at: m.start });
516                }
517                if m.end > m.start && chars.get(m.end - 1) == Some(&'\n') {
518                    return Err(Invariant::MarkEdgeOnNewline { at: m.end - 1 });
519                }
520            }
521            if let MarkKind::Unknown { tag, .. } = &m.kind {
522                if Self::RESERVED_MARK_TYPES.contains(&tag.as_str()) {
523                    return Err(Invariant::ReservedUnknownTag(tag.clone()));
524                }
525            }
526        }
527        for line in &self.lines {
528            if let LineKind::Heading { level } = line.kind {
529                if !(1..=6).contains(&level) {
530                    return Err(Invariant::BadHeadingLevel(level));
531                }
532            }
533        }
534        // Table-cell marks: the prose range/zero-width/reserved-tag rules again,
535        // but each mark is bounded by its own cell's text length (in USV). Cells
536        // hold no `\n`, so the edge-on-newline rule does not apply.
537        let mut seen_ids = std::collections::HashSet::with_capacity(self.islands.len());
538        for island in &self.islands {
539            // Ids are a minted, stable identity — the sole source of hash
540            // nondeterminism — so two islands may not share one.
541            if !seen_ids.insert(island.id.as_str()) {
542                return Err(Invariant::IslandIdCollision {
543                    id: island.id.clone(),
544                });
545            }
546            // Structural shape (table column/row/aligns consistency, `\n`-free
547            // cells) before the per-cell mark ranges — a ragged island is
548            // ill-formed regardless of its marks.
549            if let Some(e) = crate::serial::island_shape_error(island) {
550                return Err(e);
551            }
552            for (text, marks) in crate::serial::island_cell_marks(island) {
553                let clen = text.chars().count();
554                for m in &marks {
555                    if m.start > m.end || m.end > clen {
556                        return Err(Invariant::MarkOutOfRange {
557                            start: m.start,
558                            end: m.end,
559                            len: clen,
560                        });
561                    }
562                    if m.start == m.end && m.kind.is_formatting() {
563                        return Err(Invariant::ZeroWidthFormatting { at: m.start });
564                    }
565                    if let MarkKind::Unknown { tag, .. } = &m.kind {
566                        if Self::RESERVED_MARK_TYPES.contains(&tag.as_str()) {
567                            return Err(Invariant::ReservedUnknownTag(tag.clone()));
568                        }
569                    }
570                }
571            }
572        }
573        Ok(())
574    }
575}
576
577/// Apply the three Spike-A rules and the canonical sort to a flat mark list.
578///
579/// 1. Same-kind formatting marks union when adjacent *or* overlapping.
580/// 2. Different-kind marks overlap freely (never split into runs).
581/// 3. Identity (and unknown) marks never merge.
582///
583/// Zero-width formatting marks are dropped (no-ops); zero-width anchors survive.
584pub(crate) fn normalize_marks(marks: Vec<Mark>) -> Vec<Mark> {
585    use std::collections::BTreeMap;
586
587    // Partition: formatting marks group by (ord, attrs_key) for union; identity
588    // and unknown pass through untouched (but zero-width formatting is dropped).
589    let mut groups: BTreeMap<(u8, String), Vec<(Usv, Usv)>> = BTreeMap::new();
590    let mut kind_of: BTreeMap<(u8, String), MarkKind> = BTreeMap::new();
591    let mut passthrough: Vec<Mark> = Vec::new();
592
593    for m in marks {
594        if m.kind.is_formatting() {
595            if m.start >= m.end {
596                continue; // drop zero-width / inverted formatting
597            }
598            let key = (m.kind.ord(), m.kind.attrs_key());
599            kind_of.entry(key.clone()).or_insert_with(|| m.kind.clone());
600            groups.entry(key).or_default().push((m.start, m.end));
601        } else {
602            passthrough.push(m);
603        }
604    }
605
606    let mut out: Vec<Mark> = Vec::new();
607    for (key, mut ranges) in groups {
608        ranges.sort_unstable();
609        let kind = kind_of.remove(&key).expect("kind recorded with group");
610        let mut cur = ranges[0];
611        for &(s, e) in &ranges[1..] {
612            if s <= cur.1 {
613                // adjacent (s == cur.1) or overlapping — union
614                cur.1 = cur.1.max(e);
615            } else {
616                out.push(Mark {
617                    start: cur.0,
618                    end: cur.1,
619                    kind: kind.clone(),
620                });
621                cur = (s, e);
622            }
623        }
624        out.push(Mark {
625            start: cur.0,
626            end: cur.1,
627            kind,
628        });
629    }
630    out.extend(passthrough);
631
632    // Canonical sort: (start, end, kind-ord, attrs). Key cached per mark so
633    // `attrs_key`'s allocation runs once each, not once per comparison.
634    out.sort_by_cached_key(|m| (m.start, m.end, m.kind.ord(), m.kind.attrs_key()));
635    // Drop byte-identical duplicates. Identity/unknown handles never *merge*
636    // (Spike-A rule 3), but two marks equal in range, kind, and attrs are the
637    // same handle recorded twice — redundant bytes, not two handles. The sort
638    // above makes any such pair adjacent, so `dedup` (structural `PartialEq`,
639    // order-independent for `Unknown` attrs under `preserve_order`) removes it.
640    out.dedup();
641    out
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    fn f(start: Usv, end: Usv, kind: MarkKind) -> Mark {
649        Mark { start, end, kind }
650    }
651
652    #[test]
653    fn is_blank_tracks_whitespace_and_islands() {
654        assert!(Content::empty().is_blank());
655        let mut ws = Content::empty();
656        ws.text = "  \n\t ".to_string();
657        ws.lines = vec![
658            Line {
659                kind: LineKind::Para,
660                containers: Vec::new(),
661                continues: false,
662            },
663            Line {
664                kind: LineKind::Para,
665                containers: Vec::new(),
666                continues: false,
667            },
668        ];
669        assert!(ws.is_blank(), "whitespace-only text is blank");
670
671        let mut has_text = Content::empty();
672        has_text.text = "x".to_string();
673        assert!(!has_text.is_blank());
674
675        // An island slot is not whitespace, so an island-bearing content is
676        // never blank even with no other text.
677        let mut island_only = Content::empty();
678        island_only.text = ISLAND_SLOT.to_string();
679        assert!(!island_only.is_blank());
680    }
681
682    #[test]
683    fn same_kind_adjacent_unions() {
684        // [0,3) strong + [3,6) strong -> [0,6) strong (rule 1, adjacency).
685        let got = normalize_marks(vec![f(3, 6, MarkKind::Strong), f(0, 3, MarkKind::Strong)]);
686        assert_eq!(got, vec![f(0, 6, MarkKind::Strong)]);
687    }
688
689    #[test]
690    fn same_kind_overlapping_unions() {
691        let got = normalize_marks(vec![f(0, 4, MarkKind::Emph), f(2, 7, MarkKind::Emph)]);
692        assert_eq!(got, vec![f(0, 7, MarkKind::Emph)]);
693    }
694
695    #[test]
696    fn different_kinds_overlap_freely() {
697        // Strong and emph over overlapping ranges stay two marks (rule 2).
698        let got = normalize_marks(vec![f(0, 5, MarkKind::Strong), f(2, 7, MarkKind::Emph)]);
699        assert_eq!(
700            got,
701            vec![f(0, 5, MarkKind::Strong), f(2, 7, MarkKind::Emph)]
702        );
703    }
704
705    #[test]
706    fn links_union_only_at_same_url() {
707        let a = MarkKind::Link { url: "a".into() };
708        let b = MarkKind::Link { url: "b".into() };
709        // Same url adjacent -> union; different url -> distinct.
710        let got = normalize_marks(vec![
711            f(0, 2, a.clone()),
712            f(2, 4, a.clone()),
713            f(4, 6, b.clone()),
714        ]);
715        assert_eq!(got, vec![f(0, 4, a), f(4, 6, b)]);
716    }
717
718    #[test]
719    fn identity_never_merges() {
720        // Two anchors over the same range are two distinct things (rule 3).
721        let a = MarkKind::Anchor { id: "c1".into() };
722        let b = MarkKind::Anchor { id: "c2".into() };
723        let got = normalize_marks(vec![f(3, 3, a.clone()), f(3, 3, b.clone())]);
724        assert_eq!(got.len(), 2);
725        assert!(got.contains(&f(3, 3, a)));
726        assert!(got.contains(&f(3, 3, b)));
727    }
728
729    #[test]
730    fn zero_width_formatting_dropped_zero_width_anchor_kept() {
731        let got = normalize_marks(vec![
732            f(2, 2, MarkKind::Strong),
733            f(2, 2, MarkKind::Anchor { id: "x".into() }),
734        ]);
735        assert_eq!(got, vec![f(2, 2, MarkKind::Anchor { id: "x".into() })]);
736    }
737
738    #[test]
739    fn empty_is_valid() {
740        assert_eq!(Content::empty().validate(), Ok(()));
741    }
742
743    #[test]
744    fn is_inline_accepts_empty_and_single_para() {
745        assert!(Content::empty().is_inline());
746        assert!(crate::import::from_markdown("just one line")
747            .unwrap()
748            .is_inline());
749        assert!(crate::import::from_markdown("a *bold* run")
750            .unwrap()
751            .is_inline());
752    }
753
754    #[test]
755    fn is_inline_rejects_blocks_containers_and_islands() {
756        // Two paragraphs → two Para lines.
757        assert!(!crate::import::from_markdown("one\n\ntwo")
758            .unwrap()
759            .is_inline());
760        // A heading is a non-Para line kind.
761        assert!(!crate::import::from_markdown("# heading")
762            .unwrap()
763            .is_inline());
764        // A list item sits in a container.
765        assert!(!crate::import::from_markdown("- item").unwrap().is_inline());
766    }
767
768    #[test]
769    fn validate_catches_slot_mismatch() {
770        let mut rt = Content::empty();
771        rt.text = "\u{FFFC}".into();
772        rt.lines = vec![Line {
773            kind: LineKind::Island,
774            containers: vec![],
775            continues: false,
776        }];
777        assert_eq!(
778            rt.validate(),
779            Err(Invariant::IslandSlotMismatch {
780                slots: 1,
781                islands: 0
782            })
783        );
784    }
785
786    #[test]
787    fn validate_catches_line_count() {
788        let mut rt = Content::empty();
789        rt.text = "a\nb".into(); // 2 segments, but 1 line
790        assert_eq!(
791            rt.validate(),
792            Err(Invariant::LineCountMismatch {
793                lines: 1,
794                segments: 2
795            })
796        );
797    }
798
799    #[test]
800    fn normalize_is_idempotent() {
801        let mut rt = Content::empty();
802        rt.text = "hello world".into();
803        rt.marks = vec![
804            f(6, 11, MarkKind::Strong),
805            f(0, 5, MarkKind::Strong),
806            f(0, 5, MarkKind::Emph),
807        ];
808        rt.normalize();
809        let once = rt.marks.clone();
810        rt.normalize();
811        assert_eq!(rt.marks, once);
812        assert_eq!(rt.validate(), Ok(()));
813    }
814
815    /// A table cell built with un-normalized marks (reversed order, an adjacent
816    /// same-kind pair, a zero-width formatting mark) canonicalizes to the same
817    /// marks whatever the input order — the live-model determinism invariant.
818    #[test]
819    fn table_cell_marks_normalize_and_are_idempotent() {
820        fn table(cell_marks: serde_json::Value) -> Content {
821            let mut rt = Content::empty();
822            rt.text = ISLAND_SLOT.to_string();
823            rt.lines = vec![Line {
824                kind: LineKind::Island,
825                containers: vec![],
826                continues: false,
827            }];
828            rt.islands = vec![Island {
829                id: "i".into(),
830                island_type: "table".into(),
831                props: serde_json::json!({
832                    "aligns": ["none"],
833                    "header": [{"text": "abcd", "marks": cell_marks}],
834                    "rows": [],
835                }),
836                loss: Loss::Lossless,
837            }];
838            rt
839        }
840        // Reversed order + adjacent same-kind pair (0..2)+(2..4) → unioned 0..4;
841        // a zero-width strong at 1 → dropped.
842        let mut a = table(serde_json::json!([
843            {"start": 2, "end": 4, "type": "strong"},
844            {"start": 1, "end": 1, "type": "strong"},
845            {"start": 0, "end": 2, "type": "strong"}
846        ]));
847        a.normalize();
848        assert_eq!(a.validate(), Ok(()));
849        let cell = &a.islands[0].props["header"][0];
850        assert_eq!(cell["marks"].as_array().unwrap().len(), 1);
851        assert_eq!(cell["marks"][0]["start"], 0);
852        assert_eq!(cell["marks"][0]["end"], 4);
853        // Same content, different input order → identical canonical bytes.
854        let mut b = table(serde_json::json!([
855            {"start": 0, "end": 2, "type": "strong"},
856            {"start": 2, "end": 4, "type": "strong"}
857        ]));
858        b.normalize();
859        assert_eq!(a.to_canonical_json(), b.to_canonical_json());
860        // Idempotent.
861        let once = a.to_canonical_json();
862        a.normalize();
863        assert_eq!(a.to_canonical_json(), once);
864    }
865
866    /// `validate` bounds a cell mark by its own cell's text length (in USV).
867    #[test]
868    fn validate_catches_cell_mark_out_of_range() {
869        let mut rt = Content::empty();
870        rt.text = ISLAND_SLOT.to_string();
871        rt.lines = vec![Line {
872            kind: LineKind::Island,
873            containers: vec![],
874            continues: false,
875        }];
876        rt.islands = vec![Island {
877            id: "i".into(),
878            island_type: "table".into(),
879            props: serde_json::json!({
880                "aligns": ["none"],
881                // "ab" is 2 USV; a mark ending at 5 runs past the cell.
882                "header": [{"text": "ab", "marks": [{"start": 0, "end": 5, "type": "strong"}]}],
883                "rows": [],
884            }),
885            loss: Loss::Lossless,
886        }];
887        assert_eq!(
888            rt.validate(),
889            Err(Invariant::MarkOutOfRange {
890                start: 0,
891                end: 5,
892                len: 2
893            })
894        );
895    }
896
897    /// A `Content` holding a single table island with the given props — the
898    /// shared fixture for the table-shape invariant tests.
899    fn table_rt(props: serde_json::Value) -> Content {
900        let mut rt = Content::empty();
901        rt.text = ISLAND_SLOT.to_string();
902        rt.lines = vec![Line {
903            kind: LineKind::Island,
904            containers: vec![],
905            continues: false,
906        }];
907        rt.islands = vec![Island {
908            id: "i".into(),
909            island_type: "table".into(),
910            props,
911            loss: Loss::Lossless,
912        }];
913        rt
914    }
915
916    fn cell(t: &str) -> serde_json::Value {
917        serde_json::json!({ "text": t, "marks": [] })
918    }
919
920    /// `validate` rejects a ragged body row, an `aligns`/column mismatch, and a
921    /// cell carrying a `\n` — the three table-shape invariants.
922    #[test]
923    fn validate_catches_table_shape() {
924        // Ragged row: header has 2 columns, the row has 3.
925        let rt = table_rt(serde_json::json!({
926            "aligns": ["none", "none"],
927            "header": [cell("a"), cell("b")],
928            "rows": [[cell("1"), cell("2"), cell("3")]],
929        }));
930        assert_eq!(
931            rt.validate(),
932            Err(Invariant::TableRaggedRow {
933                row: 0,
934                width: 3,
935                cols: 2
936            })
937        );
938
939        // aligns length differs from the column count.
940        let rt = table_rt(serde_json::json!({
941            "aligns": ["none"],
942            "header": [cell("a"), cell("b")],
943            "rows": [],
944        }));
945        assert_eq!(
946            rt.validate(),
947            Err(Invariant::TableAlignsMismatch { aligns: 1, cols: 2 })
948        );
949
950        // A `\n` in a cell (flat header-then-rows index 1 = the second header cell).
951        let rt = table_rt(serde_json::json!({
952            "aligns": ["none", "none"],
953            "header": [cell("a"), cell("b\nc")],
954            "rows": [],
955        }));
956        assert_eq!(rt.validate(), Err(Invariant::TableCellNewline { cell: 1 }));
957    }
958
959    /// `normalize` repairs every table-shape violation — pads the header and
960    /// short rows to the widest column count, syncs `aligns`, and rewrites a
961    /// cell `\n` to a space — so the result validates and is idempotent. This is
962    /// also the one-column-count unification: the widest row (3) drives the
963    /// header width, so the markdown (header-derived) and Typst (widest-row)
964    /// projections agree.
965    #[test]
966    fn normalize_repairs_table_shape() {
967        let mut rt = table_rt(serde_json::json!({
968            "aligns": ["none"],
969            "header": [cell("h")],
970            "rows": [
971                [cell("a"), cell("b"), cell("c")],
972                [cell("d\ne")],
973            ],
974        }));
975        rt.normalize();
976        assert_eq!(rt.validate(), Ok(()));
977
978        let props = &rt.islands[0].props;
979        assert_eq!(props["header"].as_array().unwrap().len(), 3);
980        assert_eq!(props["aligns"].as_array().unwrap().len(), 3);
981        for row in props["rows"].as_array().unwrap() {
982            assert_eq!(row.as_array().unwrap().len(), 3);
983        }
984        // Padded aligns default to "none"; the padded cells are empty.
985        assert_eq!(props["aligns"][2], serde_json::json!("none"));
986        assert_eq!(props["header"][1]["text"], serde_json::json!(""));
987        // The `\n` in "d\ne" became a space, preserving char count.
988        assert_eq!(props["rows"][1][0]["text"], serde_json::json!("d e"));
989
990        // Idempotent on canonical bytes.
991        let once = rt.to_canonical_json();
992        rt.normalize();
993        assert_eq!(rt.to_canonical_json(), once);
994    }
995
996    /// An empty table (no header, no rows) is trivially well-formed: every width
997    /// is zero, so no shape invariant fires and `normalize` leaves it alone.
998    #[test]
999    fn empty_table_is_valid() {
1000        let mut rt = table_rt(serde_json::json!({
1001            "aligns": [],
1002            "header": [],
1003            "rows": [],
1004        }));
1005        assert_eq!(rt.validate(), Ok(()));
1006        rt.normalize();
1007        assert_eq!(rt.validate(), Ok(()));
1008    }
1009
1010    /// A non-array `header` carries no cells: `validate` rejects it and
1011    /// `normalize` repairs it to an empty array (a zero-column table that then
1012    /// validates). Issue #904.
1013    #[test]
1014    fn non_array_table_header_is_rejected_then_repaired() {
1015        let mut rt = table_rt(serde_json::json!({
1016            "header": "oops",
1017            "aligns": [],
1018            "rows": [],
1019        }));
1020        assert_eq!(rt.validate(), Err(Invariant::TableHeaderNotArray));
1021        rt.normalize();
1022        assert_eq!(rt.validate(), Ok(()));
1023        assert_eq!(rt.islands[0].props["header"], serde_json::json!([]));
1024    }
1025
1026    /// Two islands sharing an `id` violate the minted-identity invariant.
1027    /// Import mints ids by index so never collides; a hand-built content can.
1028    /// Issue #903.
1029    #[test]
1030    fn duplicate_island_id_is_rejected() {
1031        let mut rt = Content::empty();
1032        rt.text = format!("{ISLAND_SLOT}\n{ISLAND_SLOT}");
1033        rt.lines = vec![
1034            Line {
1035                kind: LineKind::Island,
1036                containers: vec![],
1037                continues: false,
1038            },
1039            Line {
1040                kind: LineKind::Island,
1041                containers: vec![],
1042                continues: false,
1043            },
1044        ];
1045        let table = |id: &str| Island {
1046            id: id.into(),
1047            island_type: "table".into(),
1048            props: serde_json::json!({ "header": [cell("h")], "aligns": ["none"], "rows": [] }),
1049            loss: Loss::Lossless,
1050        };
1051        rt.islands = vec![table("dup"), table("dup")];
1052        assert_eq!(
1053            rt.validate(),
1054            Err(Invariant::IslandIdCollision { id: "dup".into() })
1055        );
1056        // Distinct ids validate.
1057        rt.islands = vec![table("a"), table("b")];
1058        assert_eq!(rt.validate(), Ok(()));
1059    }
1060
1061    /// `normalize` drops a byte-identical duplicate identity mark (same range,
1062    /// same id) — the same handle recorded twice is redundant, not two handles.
1063    /// Distinct-id anchors over the same range are kept. Issue #906.
1064    #[test]
1065    fn normalize_dedupes_identical_identity_marks() {
1066        let mut rt = Content::empty();
1067        rt.text = "abcd".into();
1068        let anchor = |id: &str| Mark {
1069            start: 0,
1070            end: 4,
1071            kind: MarkKind::Anchor { id: id.into() },
1072        };
1073        rt.marks = vec![anchor("x"), anchor("x")];
1074        rt.normalize();
1075        assert_eq!(rt.marks, vec![anchor("x")]);
1076        // Different ids over the same range are distinct handles — both survive.
1077        rt.marks = vec![anchor("x"), anchor("y")];
1078        rt.normalize();
1079        assert_eq!(rt.marks.len(), 2);
1080    }
1081}