Skip to main content

common/
format_runs.rs

1//! Per-block character formatting as sorted, non-overlapping byte spans.
2//!
3//! Each block carries a `Vec<FormatRun>` (formatting) and a
4//! `Vec<ImageAnchor>` (image positions). The block's `plain_text` is
5//! the authoritative character source for byte offsets used by both.
6//! Replaces the pre-Phase-1 model where every formatted run and every
7//! inline image was a row in the now-deleted `inline_elements` entity
8//! table; the [`InlineSegment`] type in this module is a transient
9//! view synthesized from `(plain_text, format_runs, block_images)`
10//! for readers (export, fragments, cursor) that still consume a
11//! per-segment shape.
12//!
13//! Invariants are documented on [`FormatRun`] and enforced by
14//! [`debug_assert_well_formed`] and by [`splice_range`] / [`shift_after`]
15//! which rebuild the run list while preserving them.
16//!
17//! **In a release build a `debug_assert!` is not enforcement.** It is compiled out, so
18//! a contract violation there produced a malformed run list *silently* — and autosave
19//! wrote that corruption to the writer's file seconds later. The bulk-edit path
20//! therefore uses the checked siblings, which report instead of assert:
21//! [`check_well_formed`], [`try_splice_range`] and [`shift_runs_for_replace`], all
22//! returning [`FormatRunError`].
23
24use crate::entities::{CharVerticalAlignment, UnderlineStyle};
25use serde::{Deserialize, Serialize};
26use thiserror::Error;
27
28/// A violation of the format-run invariants, reported instead of asserted.
29///
30/// The invariants used to be guarded only by `debug_assert!`, which is **compiled out
31/// of release builds** — so a contract violation silently produced a malformed run list
32/// in a shipped binary, and (with autosave) that corruption became the file's new truth
33/// within seconds. Anything on the *replace* path returns this instead, so the use case
34/// can refuse the edit and say why rather than quietly mangle a writer's formatting.
35#[derive(Debug, Clone, PartialEq, Eq, Error)]
36pub enum FormatRunError {
37    #[error("byte range {start}..{end} is reversed")]
38    ReversedRange { start: u32, end: u32 },
39
40    #[error(
41        "replacement run {run_start}..{run_end} falls outside the spliced range \
42         {range_start}..{range_end}"
43    )]
44    ReplacementOutsideRange {
45        run_start: u32,
46        run_end: u32,
47        range_start: u32,
48        range_end: u32,
49    },
50
51    #[error("run {start}..{end} is empty or reversed")]
52    EmptyRun { start: u32, end: u32 },
53
54    #[error("runs overlap or are out of order at index {index}: {left:?} then {right:?}")]
55    RunsOverlap {
56        index: usize,
57        left: Box<FormatRun>,
58        right: Box<FormatRun>,
59    },
60
61    #[error("adjacent runs with identical formatting were left uncoalesced at index {index}")]
62    RunsNotCoalesced { index: usize },
63
64    #[error("run {start}..{end} runs past the end of the block's {text_len} bytes")]
65    RunPastEndOfBlock {
66        start: u32,
67        end: u32,
68        text_len: usize,
69    },
70}
71
72/// What the replacement text wears when it overwrites formatted text.
73///
74/// Before this existed the behaviour was **emergent, not chosen**: a replace was a
75/// delete followed by an insert, and `shift_runs_for_insert` hardcodes "the inserted
76/// text inherits whatever run ends at the insertion point". That silently destroys
77/// formatting — renaming a character whose name reads `Auré**lien**` dropped the bold
78/// entirely, and not one test in the repo covered it.
79///
80/// The old behaviour is still the default (and is byte-for-byte identical); it is now
81/// simply one option among four, and the caller has to look at it.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
83pub enum ReplaceFormatPolicy {
84    /// The replacement inherits the format of the run that straddles the start of the
85    /// replaced range or ends exactly on it (precisely: `byte_start < start &&
86    /// byte_end >= start`); otherwise it is unformatted. A run beginning *exactly* at
87    /// the start never contributes.
88    ///
89    /// This is the Qt / ProseMirror insertion convention, and it is what
90    /// delete-then-insert has always produced — byte for byte, which
91    /// `inherit_preceding_matches_the_historical_delete_then_insert` pins *differentially*
92    /// (it runs the historical primitives and compares, rather than trusting a
93    /// transcription of them).
94    #[default]
95    InheritPreceding,
96
97    /// If a **single run covers the whole replaced range**, the replacement keeps that
98    /// run's format; otherwise fall back to [`Self::InheritPreceding`]. "Rename a name
99    /// that was entirely bold and it stays bold" — without guessing when the range is
100    /// formatted unevenly.
101    PreserveIfFullyCovered,
102
103    /// The replacement takes the format that covered the **most bytes** of the replaced
104    /// range. Unformatted gaps count as a candidate, so a mostly-plain range stays
105    /// plain; ties go to the *formatted* run, because a tie means the writer's
106    /// formatting covered at least as much as its absence and dropping it is the
107    /// destructive answer.
108    KeepDominantRun,
109
110    /// The replacement carries no formatting at all.
111    PreserveNothing,
112}
113
114/// Content type for an inline segment: text, image, footnote reference, or empty.
115#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)]
116pub enum InlineContent {
117    #[default]
118    Empty,
119    Text(String),
120    /// A footnote reference — the marker in the prose that points at a note.
121    ///
122    /// Carries only the **label**, never the number a reader sees. The number is
123    /// a fact about document order and about which notes an export happens to
124    /// include, so storing it would mean rewriting the author's prose every time
125    /// a note was inserted above it. Renderers derive it; the model never knows
126    /// it.
127    ///
128    /// The label need not resolve. A reference whose definition lives outside
129    /// this document — which is the normal state for a host that owns note
130    /// bodies itself — must survive a round trip unchanged, so nothing here
131    /// requires a matching definition to exist.
132    FootnoteRef {
133        label: String,
134    },
135    Image {
136        name: String,
137        /// Alternative text describing the image.
138        ///
139        /// Carried on the model rather than derived from the resource name
140        /// because it is the image's accessible description and its export
141        /// representation (HTML/EPUB `alt`, DOCX drawing description, Djot's
142        /// `![…]` label) — a filename is none of those things.
143        ///
144        /// `#[serde(default)]`: fragments are serialized onto the OS clipboard,
145        /// so a payload written by a build without this field must still
146        /// deserialize.
147        #[serde(default)]
148        alt: String,
149        width: i64,
150        height: i64,
151        quality: i64,
152    },
153}
154
155/// A lean view type representing one inline segment (text or image) with its
156/// associated formatting. Used by readers (export, fragments, cursor) to
157/// consume per-segment data synthesized from `(plain_text, format_runs,
158/// block_images)` via [`crate::format_runs_query::inline_segments_for_block`].
159/// Never stored — synthesized on demand.
160///
161/// The `fmt_*` field names match those on `Block` and on `FragmentElement`
162/// so readers can copy fields verbatim across the three types.
163#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct InlineSegment {
165    pub content: InlineContent,
166    pub fmt_font_family: Option<String>,
167    pub fmt_font_point_size: Option<i64>,
168    pub fmt_font_weight: Option<i64>,
169    pub fmt_font_bold: Option<bool>,
170    pub fmt_font_italic: Option<bool>,
171    pub fmt_font_underline: Option<bool>,
172    pub fmt_font_overline: Option<bool>,
173    pub fmt_font_strikeout: Option<bool>,
174    pub fmt_letter_spacing: Option<i64>,
175    pub fmt_word_spacing: Option<i64>,
176    pub fmt_anchor_href: Option<String>,
177    pub fmt_anchor_names: Vec<String>,
178    pub fmt_is_anchor: Option<bool>,
179    pub fmt_tooltip: Option<String>,
180    pub fmt_underline_style: Option<UnderlineStyle>,
181    pub fmt_vertical_alignment: Option<CharVerticalAlignment>,
182}
183
184/// Character-level formatting for a contiguous byte span. One per
185/// [`FormatRun`]; one per [`ImageAnchor`]. Fields mirror the `fmt_*`
186/// set on [`InlineSegment`] and on `FragmentElement` so values copy
187/// across types verbatim.
188#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
189pub struct CharacterFormat {
190    pub font_family: Option<String>,
191    pub font_point_size: Option<i64>,
192    pub font_weight: Option<i64>,
193    pub font_bold: Option<bool>,
194    pub font_italic: Option<bool>,
195    pub font_underline: Option<bool>,
196    pub font_overline: Option<bool>,
197    pub font_strikeout: Option<bool>,
198    pub letter_spacing: Option<i64>,
199    pub word_spacing: Option<i64>,
200    pub anchor_href: Option<String>,
201    pub anchor_names: Vec<String>,
202    pub is_anchor: Option<bool>,
203    pub tooltip: Option<String>,
204    pub underline_style: Option<UnderlineStyle>,
205    pub vertical_alignment: Option<CharVerticalAlignment>,
206}
207
208/// One run of identical character formatting inside a block. Byte offsets
209/// are relative to the block's `plain_text` (Phase 1) or to the block's
210/// rope range (Phase 2).
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct FormatRun {
213    pub byte_start: u32,
214    pub byte_end: u32,
215    pub format: CharacterFormat,
216}
217
218/// An image embedded at a specific byte position inside a block. In
219/// Phase 1 the byte position is an index into the block's `plain_text`;
220/// in Phase 2 it points at the U+FFFC sentinel character in the rope.
221///
222/// Images carry their own [`CharacterFormat`] because vertical alignment
223/// and anchor metadata apply per inline run.
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225pub struct ImageAnchor {
226    pub byte_offset: u32,
227    pub name: String,
228    /// Alternative text. See [`InlineContent::Image::alt`] for why it lives on
229    /// the model and why it defaults.
230    #[serde(default)]
231    pub alt: String,
232    pub width: i64,
233    pub height: i64,
234    pub quality: i64,
235    pub format: CharacterFormat,
236}
237
238/// A footnote reference embedded at a specific byte position inside a block.
239///
240/// The exact shape of [`ImageAnchor`], and for the same reason: a reference is
241/// an inline object occupying one `U+FFFC` sentinel in the block's text, so the
242/// rope moves it with every edit and deleting the sentence deletes the
243/// reference — no re-anchoring, no quote matching, no orphan state to keep.
244///
245/// It carries its own [`CharacterFormat`] because a reference is normally
246/// superscript, and because whatever formatting surrounds it should not bleed
247/// onto the marker.
248///
249/// What it deliberately does **not** carry is the number. See
250/// [`InlineContent::FootnoteRef`].
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct FootnoteRefAnchor {
253    pub byte_offset: u32,
254    /// Matches a footnote definition's `Frame::footnote_label`, when one exists
255    /// in this document at all. Djot's `[^label]` syntax on the wire.
256    pub label: String,
257    pub format: CharacterFormat,
258}
259
260/// One inline object anchored in a block: an image, or a footnote reference.
261///
262/// Both occupy a single `U+FFFC` and are woven into the text by the same rules,
263/// so the weave takes them as one byte-ordered sequence rather than walking two
264/// lists and hoping they interleave. They are stored apart because they are
265/// edited apart, and are brought together only here.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum BlockAnchor<'a> {
268    Image(&'a ImageAnchor),
269    FootnoteRef(&'a FootnoteRefAnchor),
270}
271
272impl BlockAnchor<'_> {
273    /// Byte position of this anchor's sentinel within the block's text.
274    pub fn byte_offset(&self) -> u32 {
275        match self {
276            BlockAnchor::Image(i) => i.byte_offset,
277            BlockAnchor::FootnoteRef(f) => f.byte_offset,
278        }
279    }
280}
281
282/// Every anchor in a block, in byte order.
283///
284/// A stable sort, so an image and a reference mirrored at the same offset keep
285/// a deterministic order rather than swapping between reads — which would show
286/// up as a diff in exported Djot for a document nobody edited.
287pub fn block_anchors<'a>(
288    images: &'a [ImageAnchor],
289    footnote_refs: &'a [FootnoteRefAnchor],
290) -> Vec<BlockAnchor<'a>> {
291    let mut anchors: Vec<BlockAnchor<'a>> = Vec::with_capacity(images.len() + footnote_refs.len());
292    anchors.extend(images.iter().map(BlockAnchor::Image));
293    anchors.extend(footnote_refs.iter().map(BlockAnchor::FootnoteRef));
294    anchors.sort_by_key(|a| a.byte_offset());
295    anchors
296}
297
298/// Debug-only invariant check. Run from `debug_assert!` callsites in
299/// the use cases that mutate format runs. Cheap: O(n) where n is the
300/// run count (typically < 100 per block in real prose).
301///
302/// # Invariants
303/// 1. Runs are sorted by `byte_start` ascending.
304/// 2. Each run has `byte_start < byte_end`.
305/// 3. Runs are non-overlapping: `runs[i].byte_end <= runs[i+1].byte_start`.
306/// 4. The last run's `byte_end` does not exceed `block_text_len`.
307/// 5. Adjacent runs with identical format are coalesced (no two
308///    consecutive runs satisfy `byte_end == next.byte_start &&
309///    format == next.format`).
310pub fn debug_assert_well_formed(runs: &[FormatRun], block_text_len: usize) {
311    // Only pay the O(n) walk where the assertion would actually fire.
312    if cfg!(debug_assertions)
313        && let Err(e) = check_well_formed(runs, block_text_len)
314    {
315        debug_assert!(false, "format runs are malformed: {e}");
316    }
317}
318
319/// The same invariants as [`debug_assert_well_formed`], but **reported rather than
320/// asserted** — so a caller that must not corrupt a block can refuse the edit.
321///
322/// This exists because `debug_assert!` is compiled out of release builds: a malformed
323/// run list produced in a shipped binary went completely undetected, and autosave wrote
324/// it to disk seconds later. The replace path calls this and propagates the error.
325pub fn check_well_formed(runs: &[FormatRun], block_text_len: usize) -> Result<(), FormatRunError> {
326    if runs.is_empty() {
327        return Ok(());
328    }
329    for run in runs {
330        if run.byte_start >= run.byte_end {
331            return Err(FormatRunError::EmptyRun {
332                start: run.byte_start,
333                end: run.byte_end,
334            });
335        }
336    }
337    for i in 0..runs.len() - 1 {
338        if runs[i].byte_end > runs[i + 1].byte_start {
339            return Err(FormatRunError::RunsOverlap {
340                index: i,
341                left: Box::new(runs[i].clone()),
342                right: Box::new(runs[i + 1].clone()),
343            });
344        }
345        if runs[i].byte_end == runs[i + 1].byte_start && runs[i].format == runs[i + 1].format {
346            return Err(FormatRunError::RunsNotCoalesced { index: i });
347        }
348    }
349    let last = runs.last().expect("non-empty");
350    if last.byte_end as usize > block_text_len {
351        return Err(FormatRunError::RunPastEndOfBlock {
352            start: last.byte_start,
353            end: last.byte_end,
354            text_len: block_text_len,
355        });
356    }
357    Ok(())
358}
359
360/// Merge adjacent runs that have identical formatting. O(n).
361pub fn coalesce_in_place(runs: &mut Vec<FormatRun>) {
362    if runs.len() < 2 {
363        return;
364    }
365    let mut write = 0usize;
366    for read in 1..runs.len() {
367        if runs[write].byte_end == runs[read].byte_start && runs[write].format == runs[read].format
368        {
369            runs[write].byte_end = runs[read].byte_end;
370        } else {
371            write += 1;
372            if write != read {
373                runs[write] = runs[read].clone();
374            }
375        }
376    }
377    runs.truncate(write + 1);
378}
379
380/// Replace the runs covering `range` with `replacement`, preserving the
381/// invariants. Runs that straddle the range boundary are clipped on
382/// either side; runs fully contained are removed.
383///
384/// The replacement byte ranges must lie within `range` and themselves
385/// be well-formed (sorted, non-overlapping). The function does NOT
386/// shift bytes after `range.end` — callers wanting to splice in a
387/// different-length text must call [`shift_after`] first or after,
388/// depending on whether the text length is changing.
389pub fn splice_range(
390    runs: &mut Vec<FormatRun>,
391    range: std::ops::Range<u32>,
392    replacement: Vec<FormatRun>,
393) {
394    if let Err(e) = try_splice_range(runs, range, replacement) {
395        // Previously this was a bare `debug_assert!` — compiled OUT of release, where a
396        // contract violation therefore went on to build a malformed run list and corrupt
397        // the block's formatting silently. Keep the loud failure in debug; in release,
398        // refuse the splice and leave `runs` untouched rather than mangle it.
399        //
400        // No existing caller can reach this: every one either builds a replacement that
401        // spans exactly the range, or goes through `shift_runs_for_delete`, which
402        // early-returns on an inverted range. It is a net, not a behaviour change.
403        debug_assert!(false, "splice_range contract violated: {e}");
404    }
405}
406
407/// [`splice_range`], but the contract is **checked and reported** instead of asserted.
408///
409/// `runs` is left completely untouched when this returns `Err` — validation happens
410/// before any mutation, so a rejected splice cannot half-apply.
411pub fn try_splice_range(
412    runs: &mut Vec<FormatRun>,
413    range: std::ops::Range<u32>,
414    replacement: Vec<FormatRun>,
415) -> Result<(), FormatRunError> {
416    if range.start > range.end {
417        return Err(FormatRunError::ReversedRange {
418            start: range.start,
419            end: range.end,
420        });
421    }
422    for r in &replacement {
423        if r.byte_start >= r.byte_end {
424            return Err(FormatRunError::EmptyRun {
425                start: r.byte_start,
426                end: r.byte_end,
427            });
428        }
429        if r.byte_start < range.start || r.byte_end > range.end {
430            return Err(FormatRunError::ReplacementOutsideRange {
431                run_start: r.byte_start,
432                run_end: r.byte_end,
433                range_start: range.start,
434                range_end: range.end,
435            });
436        }
437    }
438    for i in 1..replacement.len() {
439        if replacement[i - 1].byte_end > replacement[i].byte_start {
440            return Err(FormatRunError::RunsOverlap {
441                index: i - 1,
442                left: Box::new(replacement[i - 1].clone()),
443                right: Box::new(replacement[i].clone()),
444            });
445        }
446    }
447
448    let mut result: Vec<FormatRun> = Vec::with_capacity(runs.len() + replacement.len());
449
450    // Keep / clip everything strictly before range.start.
451    for run in runs.iter() {
452        if run.byte_end <= range.start {
453            result.push(run.clone());
454        } else if run.byte_start < range.start {
455            // Run straddles range.start: keep the left part.
456            result.push(FormatRun {
457                byte_start: run.byte_start,
458                byte_end: range.start,
459                format: run.format.clone(),
460            });
461        }
462    }
463
464    // Insert the replacement runs.
465    result.extend(replacement);
466
467    // Keep / clip everything starting at or after range.end.
468    for run in runs.iter() {
469        if run.byte_start >= range.end {
470            result.push(run.clone());
471        } else if run.byte_end > range.end {
472            // Run straddles range.end: keep the right part.
473            result.push(FormatRun {
474                byte_start: range.end,
475                byte_end: run.byte_end,
476                format: run.format.clone(),
477            });
478        }
479    }
480
481    coalesce_in_place(&mut result);
482    *runs = result;
483    Ok(())
484}
485
486/// Capture the slice of `runs` that intersects `[start..end)`, clipped
487/// to those bounds. Used by hand-rolled-inverse undo for format-only
488/// edits: callers capture this BEFORE calling [`splice_range`], and
489/// on undo splice the captured runs back into the same byte range to
490/// restore the prior state without paying the cost of a full
491/// `RopeStoreSnapshot`.
492///
493/// Gaps in the original runs (positions inside `[start..end)` with no
494/// formatting) become gaps in the captured output too — the undo
495/// splice preserves them faithfully.
496pub fn capture_runs_in_range(runs: &[FormatRun], start: u32, end: u32) -> Vec<FormatRun> {
497    let mut out = Vec::new();
498    for run in runs {
499        if run.byte_end <= start || run.byte_start >= end {
500            continue;
501        }
502        let clipped_start = std::cmp::max(run.byte_start, start);
503        let clipped_end = std::cmp::min(run.byte_end, end);
504        if clipped_start < clipped_end {
505            out.push(FormatRun {
506                byte_start: clipped_start,
507                byte_end: clipped_end,
508                format: run.format.clone(),
509            });
510        }
511    }
512    out
513}
514
515/// Capture the `(byte_offset, format)` pairs for every image anchor
516/// inside `[start..end)`. Used together with [`capture_runs_in_range`]
517/// by hand-rolled-inverse undo for format-only edits.
518pub fn capture_image_formats_in_range(
519    images: &[ImageAnchor],
520    start: u32,
521    end: u32,
522) -> Vec<(u32, CharacterFormat)> {
523    let mut out = Vec::new();
524    for img in images {
525        if img.byte_offset >= start && img.byte_offset < end {
526            out.push((img.byte_offset, img.format.clone()));
527        }
528    }
529    out
530}
531
532/// Shift the byte offsets of every run whose `byte_start >= threshold`
533/// by `delta`. Used after a text insert/delete to keep downstream runs
534/// in sync with the new block text. Runs strictly before the threshold
535/// are unaffected; runs that straddle the threshold are left alone
536/// (the caller should have spliced them first).
537///
538/// Panics in debug mode if `delta` would underflow a run's offset.
539pub fn shift_after(runs: &mut [FormatRun], threshold: u32, delta: i32) {
540    for run in runs.iter_mut() {
541        if run.byte_start >= threshold {
542            let new_start = (run.byte_start as i64) + (delta as i64);
543            let new_end = (run.byte_end as i64) + (delta as i64);
544            debug_assert!(new_start >= 0 && new_end >= new_start);
545            run.byte_start = new_start as u32;
546            run.byte_end = new_end as u32;
547        }
548    }
549}
550
551/// Synthesize a stable per-fragment id from a block id and byte offset
552/// within that block. Populates the `element_id` field in
553/// `FragmentContent::{Text, Image}` (the public layout-engine type),
554/// giving callers a stable handle across renders even though the
555/// underlying [`InlineSegment`]s are never stored. Two segments at the
556/// same `(block_id, byte_start)` always produce the same id; a segment
557/// that moves to a new byte_start (e.g. due to an insert upstream)
558/// gets a new id.
559///
560/// Bit layout (u64): bit 62 = synth tag (so synthesized ids never
561/// collide with real entity ids issued by the store's counter, which
562/// start at 1 and grow upward). Bits 32..62 = block id (1 billion
563/// blocks per document, 30 bits). Bottom 32 bits = byte offset (4 GB
564/// per block). The top bit stays zero so the value fits in positive
565/// i64 range — public DTOs expose element_id as i64.
566pub fn synth_element_id(block_id: u64, byte_start: u32) -> u64 {
567    const SYNTH_TAG: u64 = 0x4000_0000_0000_0000;
568    SYNTH_TAG | ((block_id & 0x3FFF_FFFF) << 32) | (byte_start as u64)
569}
570
571/// Same as `shift_after` for image anchors. Anchors AT the threshold are
572/// shifted (treated as part of the inserted region's right side).
573pub fn shift_images_after(images: &mut [ImageAnchor], threshold: u32, delta: i32) {
574    for img in images.iter_mut() {
575        if img.byte_offset >= threshold {
576            let new_off = (img.byte_offset as i64) + (delta as i64);
577            debug_assert!(new_off >= 0);
578            img.byte_offset = new_off as u32;
579        }
580    }
581}
582
583// ─────────────────────────────────────────────────────────────────────
584// Composite helpers used by writer use cases. These keep the per-block
585// run / image vectors well-formed under insert / delete / split.
586// ─────────────────────────────────────────────────────────────────────
587
588/// Apply an "insert `inserted_bytes` of text at `byte_offset`" mutation
589/// to a block's runs in place. Runs strictly before the offset are
590/// unchanged; runs strictly after are shifted by +inserted_bytes; runs
591/// that straddle the offset are extended (the inserted text inherits
592/// the surrounding run's format — Qt / ProseMirror convention).
593pub fn shift_runs_for_insert(runs: &mut [FormatRun], byte_offset: u32, inserted_bytes: u32) {
594    if inserted_bytes == 0 {
595        return;
596    }
597    for run in runs.iter_mut() {
598        if run.byte_start >= byte_offset {
599            run.byte_start += inserted_bytes;
600            run.byte_end += inserted_bytes;
601        } else if run.byte_end >= byte_offset {
602            // Run straddles the insertion point, or its right edge sits
603            // exactly on it. In both cases the inserted text inherits
604            // this run's format (Qt convention).
605            run.byte_end += inserted_bytes;
606        }
607    }
608}
609
610/// Apply a "delete byte range `[byte_start..byte_end)`" mutation to a
611/// block's runs. Splices the range with empty replacement (clipping
612/// straddling runs) and shifts everything past `byte_end` back by the
613/// deleted length. Adjacent runs that end up equal-format are coalesced.
614pub fn shift_runs_for_delete(runs: &mut Vec<FormatRun>, byte_start: u32, byte_end: u32) {
615    if byte_end <= byte_start {
616        return;
617    }
618    splice_range(runs, byte_start..byte_end, Vec::new());
619    let delta = (byte_end - byte_start) as i32;
620    shift_after(runs, byte_end, -delta);
621    // The shift can make a left-clipped run abut a shifted trailing run
622    // with identical format; coalesce once more to restore the invariant.
623    coalesce_in_place(runs);
624}
625
626/// Apply a "replace byte range `[byte_start..byte_end)` with `replacement_bytes` bytes"
627/// mutation to a block's runs, choosing explicitly what the replacement wears.
628///
629/// This is the one edit where the old delete-then-insert composition quietly lost a
630/// writer's formatting: replacing `Auré**lien**` deletes both runs under the range and
631/// then lets the replacement inherit whatever preceded it, so the bold is gone. That
632/// behaviour is still available — and is still the default — but it is now a *decision*
633/// ([`ReplaceFormatPolicy`]) rather than an accident of two functions being called in
634/// sequence.
635///
636/// Additive by design: `shift_runs_for_delete` / `shift_runs_for_insert` are untouched,
637/// because 13 other call sites across delete/insert/paste depend on their exact
638/// behaviour. [`ReplaceFormatPolicy::InheritPreceding`] is implemented *by calling that
639/// very composition*, so the default cannot drift away from what shipped.
640///
641/// Returns `Err` rather than corrupting the block if the range is inverted or the
642/// re-splice would violate the run invariants — see [`FormatRunError`].
643pub fn shift_runs_for_replace(
644    runs: &mut Vec<FormatRun>,
645    byte_start: u32,
646    byte_end: u32,
647    replacement_bytes: u32,
648    policy: ReplaceFormatPolicy,
649) -> Result<(), FormatRunError> {
650    if byte_end < byte_start {
651        return Err(FormatRunError::ReversedRange {
652            start: byte_start,
653            end: byte_end,
654        });
655    }
656
657    // Decide what the replacement wears from the runs as they stand BEFORE the edit —
658    // afterwards the runs under the range are gone and the evidence with them.
659    //
660    // `None` here means "do not override": let the composition below decide, which is
661    // exactly `InheritPreceding`.
662    //
663    // An empty range replaces nothing, so it is an *insertion*, and the two
664    // coverage-based policies have nothing to reason about — they must defer to the
665    // insert convention rather than strip the format the typed text would have
666    // inherited. Only `PreserveNothing`, which is an explicit request for unformatted
667    // text, still applies.
668    let destroys_formatting = byte_end > byte_start;
669    let override_format: Option<Option<CharacterFormat>> = match policy {
670        ReplaceFormatPolicy::InheritPreceding => None,
671        ReplaceFormatPolicy::PreserveNothing => Some(None),
672        ReplaceFormatPolicy::PreserveIfFullyCovered => {
673            covering_format(runs, byte_start, byte_end).map(Some)
674        }
675        ReplaceFormatPolicy::KeepDominantRun if destroys_formatting => {
676            Some(dominant_format(runs, byte_start, byte_end))
677        }
678        ReplaceFormatPolicy::KeepDominantRun => None,
679    };
680
681    // The historical composition. This IS `InheritPreceding`, byte for byte.
682    shift_runs_for_delete(runs, byte_start, byte_end);
683    shift_runs_for_insert(runs, byte_start, replacement_bytes);
684
685    // Every other policy is a targeted re-splice of exactly the replacement's span.
686    if let Some(format) = override_format
687        && replacement_bytes > 0
688    {
689        let span = byte_start..byte_start + replacement_bytes;
690        let replacement = match format {
691            Some(format) => vec![FormatRun {
692                byte_start: span.start,
693                byte_end: span.end,
694                format,
695            }],
696            None => Vec::new(),
697        };
698        try_splice_range(runs, span, replacement)?;
699    }
700    Ok(())
701}
702
703/// The format of the single run covering **all** of `[start..end)`, if one does.
704///
705/// An empty range is covered by nothing: a pure insertion has no formatting of its own
706/// to preserve, so every policy falls back to inheritance there rather than silently
707/// formatting typed text from a run it merely sits next to.
708fn covering_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
709    if end <= start {
710        return None;
711    }
712    runs.iter()
713        .find(|r| r.byte_start <= start && r.byte_end >= end)
714        .map(|r| r.format.clone())
715}
716
717/// The format covering the most bytes of `[start..end)`, or `None` if unformatted text
718/// covers more than any single run.
719///
720/// Gaps count as a candidate, so renaming inside a mostly-plain range stays plain. Ties
721/// go to the formatted run: a tie means the formatting covered at least as much of the
722/// range as its absence did, and dropping it is the destructive outcome.
723fn dominant_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
724    if end <= start {
725        return None;
726    }
727    let span = u64::from(end - start);
728    let mut covered = 0u64;
729    let mut best: Option<(u64, &FormatRun)> = None;
730
731    for r in runs {
732        let lo = r.byte_start.max(start);
733        let hi = r.byte_end.min(end);
734        if hi <= lo {
735            continue;
736        }
737        let overlap = u64::from(hi - lo);
738        covered += overlap;
739        // `>` keeps the EARLIEST run on a tie between two runs, so the result does not
740        // depend on iteration order beyond the list's own sortedness.
741        if best.is_none_or(|(best_overlap, _)| overlap > best_overlap) {
742            best = Some((overlap, r));
743        }
744    }
745
746    let plain = span - covered;
747    match best {
748        Some((overlap, run)) if overlap >= plain => Some(run.format.clone()),
749        _ => None,
750    }
751}
752
753/// Apply an "insert" shift to a block's image anchors. Anchors at or
754/// past the offset move forward by `inserted_bytes`.
755/// Apply an "insert" mutation to a block's footnote references — the rule
756/// [`shift_images_for_insert`] applies, for the same reason.
757pub fn shift_footnote_refs_for_insert(
758    notes: &mut [FootnoteRefAnchor],
759    byte_offset: u32,
760    inserted_bytes: u32,
761) {
762    if inserted_bytes == 0 {
763        return;
764    }
765    for note in notes.iter_mut() {
766        if note.byte_offset >= byte_offset {
767            note.byte_offset += inserted_bytes;
768        }
769    }
770}
771
772pub fn shift_images_for_insert(images: &mut [ImageAnchor], byte_offset: u32, inserted_bytes: u32) {
773    if inserted_bytes == 0 {
774        return;
775    }
776    for img in images.iter_mut() {
777        if img.byte_offset >= byte_offset {
778            img.byte_offset += inserted_bytes;
779        }
780    }
781}
782
783/// Apply a "delete" mutation to a block's image anchors. Anchors whose
784/// `byte_offset` falls inside `[byte_start..byte_end)` are removed;
785/// anchors at or past `byte_end` shift back by the deleted length.
786/// Returns the number of anchors removed.
787pub fn shift_images_for_delete(
788    images: &mut Vec<ImageAnchor>,
789    byte_start: u32,
790    byte_end: u32,
791) -> usize {
792    if byte_end <= byte_start {
793        return 0;
794    }
795    let before = images.len();
796    images.retain(|i| !(i.byte_offset >= byte_start && i.byte_offset < byte_end));
797    let removed = before - images.len();
798    let delta = (byte_end - byte_start) as i32;
799    shift_images_after(images, byte_end, -delta);
800    removed
801}
802
803/// Apply a "delete" mutation to a block's footnote references: the rule
804/// [`shift_images_for_delete`] applies, for the same reason, since a reference
805/// occupies one `U+FFFC` exactly as an image does. References inside
806/// `[byte_start..byte_end)` are removed with the text that held them;
807/// references at or past `byte_end` move back by the deleted length.
808/// Returns the number of references removed.
809///
810/// Every edit that moves a block's images has to move its references too. The
811/// editing use cases used to move only the images, so a reference kept the
812/// byte offset it was loaded with: typing in front of it left it pointing into
813/// the word, a paragraph break in front of it left it past the end of its
814/// block (and every export that sliced the block there panicked), and deleting
815/// the sentence around it left it behind, dangling past the text.
816pub fn shift_footnote_refs_for_delete(
817    notes: &mut Vec<FootnoteRefAnchor>,
818    byte_start: u32,
819    byte_end: u32,
820) -> usize {
821    if byte_end <= byte_start {
822        return 0;
823    }
824    let before = notes.len();
825    notes.retain(|n| !(n.byte_offset >= byte_start && n.byte_offset < byte_end));
826    let removed = before - notes.len();
827    let delta = byte_end - byte_start;
828    for note in notes.iter_mut() {
829        if note.byte_offset >= byte_end {
830            note.byte_offset -= delta;
831        }
832    }
833    removed
834}
835
836/// Translate a logical character offset (counting text characters AND
837/// image positions interleaved by their `byte_offset`) into a UTF-8
838/// byte offset within `plain_text`. Used by writer use cases to map a
839/// document-space char position to the byte position where text edits
840/// should land in `block.plain_text`.
841///
842/// Each image already occupies exactly one character of `plain_text`: the
843/// `U+FFFC` OBJECT REPLACEMENT CHARACTER that `insert_image` mirrors into the
844/// rope, which [`ImageAnchor::byte_offset`] points at. So a logical offset *is*
845/// a character offset and this is a plain char→byte mapping.
846///
847/// `images` is retained in the signature — and deliberately unused — because
848/// getting this wrong is silent and expensive, and callers pass it naturally.
849/// The previous implementation walked the anchor list *in addition to*
850/// `char_indices()`, so every image advanced the logical counter twice. That
851/// dates from the pre-rope model, where an anchor genuinely contributed no
852/// bytes; once the sentinel went into the rope the two representations started
853/// double-counting. The visible effects: selecting across an image returned the
854/// wrong text (an extra sentinel, a missing character), and deleting a range
855/// containing one removed too little.
856pub fn logical_offset_to_byte(plain_text: &str, _images: &[ImageAnchor], char_offset: i64) -> u32 {
857    if char_offset <= 0 {
858        return 0;
859    }
860    plain_text
861        .char_indices()
862        .nth(char_offset as usize)
863        .map(|(b, _)| b as u32)
864        .unwrap_or(plain_text.len() as u32)
865}
866
867/// Split a block's format runs at `byte_offset`. The returned right-hand
868/// vector has its run offsets re-based so they start at byte 0 of the
869/// new (right) block. Straddling runs are split with their `format`
870/// cloned to both halves.
871pub fn split_runs_at(runs: &[FormatRun], byte_offset: u32) -> (Vec<FormatRun>, Vec<FormatRun>) {
872    let mut left = Vec::new();
873    let mut right = Vec::new();
874    for run in runs {
875        if run.byte_end <= byte_offset {
876            left.push(run.clone());
877        } else if run.byte_start >= byte_offset {
878            right.push(FormatRun {
879                byte_start: run.byte_start - byte_offset,
880                byte_end: run.byte_end - byte_offset,
881                format: run.format.clone(),
882            });
883        } else {
884            left.push(FormatRun {
885                byte_start: run.byte_start,
886                byte_end: byte_offset,
887                format: run.format.clone(),
888            });
889            right.push(FormatRun {
890                byte_start: 0,
891                byte_end: run.byte_end - byte_offset,
892                format: run.format.clone(),
893            });
894        }
895    }
896    (left, right)
897}
898
899/// Split block image anchors at `byte_offset`. Anchors at exactly
900/// `byte_offset` go to the right half (rebased to offset 0).
901/// Split footnote references at `byte_offset`, rebasing the right-hand side to
902/// zero — the exact rule [`split_images_at`] applies, because a reference
903/// occupies a block the same way an image does.
904pub fn split_footnote_refs_at(
905    notes: &[FootnoteRefAnchor],
906    byte_offset: u32,
907) -> (Vec<FootnoteRefAnchor>, Vec<FootnoteRefAnchor>) {
908    let mut left = Vec::new();
909    let mut right = Vec::new();
910    for note in notes {
911        if note.byte_offset < byte_offset {
912            left.push(note.clone());
913        } else {
914            let mut new = note.clone();
915            new.byte_offset -= byte_offset;
916            right.push(new);
917        }
918    }
919    (left, right)
920}
921
922pub fn split_images_at(
923    images: &[ImageAnchor],
924    byte_offset: u32,
925) -> (Vec<ImageAnchor>, Vec<ImageAnchor>) {
926    let mut left = Vec::new();
927    let mut right = Vec::new();
928    for img in images {
929        if img.byte_offset < byte_offset {
930            left.push(img.clone());
931        } else {
932            let mut new = img.clone();
933            new.byte_offset -= byte_offset;
934            right.push(new);
935        }
936    }
937    (left, right)
938}
939
940// ─────────────────────────────────────────────────────────────────────
941// View synthesis: build a Vec<InlineSegment> from format_runs + images.
942// ─────────────────────────────────────────────────────────────────────
943
944/// Copy the `fmt_*` fields of an `InlineSegment` into a `CharacterFormat`.
945pub fn character_format_from_segment(seg: &InlineSegment) -> CharacterFormat {
946    CharacterFormat {
947        font_family: seg.fmt_font_family.clone(),
948        font_point_size: seg.fmt_font_point_size,
949        font_weight: seg.fmt_font_weight,
950        font_bold: seg.fmt_font_bold,
951        font_italic: seg.fmt_font_italic,
952        font_underline: seg.fmt_font_underline,
953        font_overline: seg.fmt_font_overline,
954        font_strikeout: seg.fmt_font_strikeout,
955        letter_spacing: seg.fmt_letter_spacing,
956        word_spacing: seg.fmt_word_spacing,
957        anchor_href: seg.fmt_anchor_href.clone(),
958        anchor_names: seg.fmt_anchor_names.clone(),
959        is_anchor: seg.fmt_is_anchor,
960        tooltip: seg.fmt_tooltip.clone(),
961        underline_style: seg.fmt_underline_style.clone(),
962        vertical_alignment: seg.fmt_vertical_alignment.clone(),
963    }
964}
965
966/// Apply a `CharacterFormat` onto an `InlineSegment`'s fmt_* fields.
967pub fn apply_character_format_to_segment(seg: &mut InlineSegment, fmt: &CharacterFormat) {
968    seg.fmt_font_family = fmt.font_family.clone();
969    seg.fmt_font_point_size = fmt.font_point_size;
970    seg.fmt_font_weight = fmt.font_weight;
971    seg.fmt_font_bold = fmt.font_bold;
972    seg.fmt_font_italic = fmt.font_italic;
973    seg.fmt_font_underline = fmt.font_underline;
974    seg.fmt_font_overline = fmt.font_overline;
975    seg.fmt_font_strikeout = fmt.font_strikeout;
976    seg.fmt_letter_spacing = fmt.letter_spacing;
977    seg.fmt_word_spacing = fmt.word_spacing;
978    seg.fmt_anchor_href = fmt.anchor_href.clone();
979    seg.fmt_anchor_names = fmt.anchor_names.clone();
980    seg.fmt_is_anchor = fmt.is_anchor;
981    seg.fmt_tooltip = fmt.tooltip.clone();
982    seg.fmt_underline_style = fmt.underline_style.clone();
983    seg.fmt_vertical_alignment = fmt.vertical_alignment.clone();
984}
985
986/// One ordered piece of a block's inline content: a run of text, or an image.
987///
988/// Produced by [`merge_runs_and_anchors`] and mapped by each caller into its own
989/// output type.
990#[derive(Debug, Clone, PartialEq)]
991pub enum InlinePiece<'a> {
992    /// Byte range `[start, end)` of the block's `plain_text`. `format` is
993    /// `None` for bytes no format run covers.
994    Text {
995        start: u32,
996        end: u32,
997        format: Option<&'a CharacterFormat>,
998    },
999    /// An image anchored at this position. Contributes one logical character
1000    /// and zero bytes.
1001    Image(&'a ImageAnchor),
1002    /// A footnote reference anchored at this position. Contributes one logical
1003    /// character and zero bytes, exactly as an image does.
1004    FootnoteRef(&'a FootnoteRefAnchor),
1005}
1006
1007/// Interleave a block's format runs and image anchors into one ordered stream.
1008///
1009/// A block stores three parallel things — the text bytes, a list of formatted
1010/// byte ranges, and a list of image anchors keyed by byte offset — and every
1011/// reader has to weave them back into document order. That weave is fiddly in
1012/// exactly one place: an image anchored *inside* a formatted run has to split
1013/// the run, emitting the text before it, then the image, then the rest of the
1014/// run with the same format.
1015///
1016/// This function exists because that weave was previously written out twice, by
1017/// hand, in two crates, and the two copies disagreed. The version behind
1018/// `inline_segments_view` only checked `img.byte_offset < run.byte_start`, so an
1019/// image inside a run was skipped by the run loop entirely and swept up by the
1020/// trailing loop — landing **after every run in the block**. Insert a picture
1021/// into the middle of a bold sentence and every exporter, and the fragment/copy
1022/// path, moved it to the end of the paragraph.
1023///
1024/// Callers map the returned pieces to their own types; nobody re-derives the
1025/// ordering.
1026pub fn merge_runs_and_anchors<'a>(
1027    plain_text: &str,
1028    runs: &'a [FormatRun],
1029    anchors: &[BlockAnchor<'a>],
1030) -> Vec<InlinePiece<'a>> {
1031    let text_len = plain_text.len() as u32;
1032    let mut out: Vec<InlinePiece<'a>> = Vec::new();
1033    let mut img_iter = anchors.iter().peekable();
1034    // Highest byte offset already emitted. Never moves backwards.
1035    let mut cursor: u32 = 0;
1036
1037    /// Bytes an anchor occupies in `plain_text`.
1038    ///
1039    /// `insert_image` mirrors a `U+FFFC` OBJECT REPLACEMENT CHARACTER into the
1040    /// rope at the anchor's `byte_offset`, so an image's own character sits in
1041    /// the text and text resuming after the image must step over it. Emitting
1042    /// both the image piece *and* the sentinel yields the image twice — which
1043    /// is what made a selection across an image read back with a doubled
1044    /// sentinel and a missing following character. A footnote reference is
1045    /// mirrored the same way and steps over the same three bytes.
1046    ///
1047    /// Checked rather than assumed: `U+FFFC` also marks table anchors, and not
1048    /// every writer of an `ImageAnchor` mirrors one (the test harness writes
1049    /// anchors directly). An anchor without a sentinel is still handled, it
1050    /// simply consumes no bytes.
1051    fn sentinel_len(plain_text: &str, byte_offset: u32) -> u32 {
1052        let at = byte_offset as usize;
1053        if plain_text.len() >= at + 3 && plain_text.as_bytes()[at..at + 3] == [0xEF, 0xBF, 0xBC] {
1054            3
1055        } else {
1056            0
1057        }
1058    }
1059
1060    let push_text = |out: &mut Vec<InlinePiece<'a>>,
1061                     start: u32,
1062                     end: u32,
1063                     format: Option<&'a CharacterFormat>| {
1064        if start < end {
1065            out.push(InlinePiece::Text { start, end, format });
1066        }
1067    };
1068
1069    /// The piece an anchor contributes, whichever kind it is.
1070    fn piece<'a>(anchor: &BlockAnchor<'a>) -> InlinePiece<'a> {
1071        match *anchor {
1072            BlockAnchor::Image(i) => InlinePiece::Image(i),
1073            BlockAnchor::FootnoteRef(f) => InlinePiece::FootnoteRef(f),
1074        }
1075    }
1076
1077    for run in runs {
1078        // Anchors strictly before this run: unformatted gap text, then the anchor.
1079        while let Some(anchor) = img_iter.peek() {
1080            let at = anchor.byte_offset();
1081            if at >= run.byte_start {
1082                break;
1083            }
1084            push_text(&mut out, cursor, at, None);
1085            out.push(piece(anchor));
1086            cursor = cursor.max(at + sentinel_len(plain_text, at));
1087            img_iter.next();
1088        }
1089
1090        // Unformatted gap between the last emission and the run's start.
1091        push_text(&mut out, cursor, run.byte_start, None);
1092        cursor = cursor.max(run.byte_start);
1093
1094        // Anchors inside the run split it, keeping the run's format on both
1095        // sides. `<=` so an anchor sitting exactly on the run's end boundary is
1096        // consumed here rather than deferred — deferring it is what produced
1097        // the out-of-order emission described above.
1098        while let Some(anchor) = img_iter.peek() {
1099            let at = anchor.byte_offset();
1100            if at > run.byte_end {
1101                break;
1102            }
1103            push_text(&mut out, cursor, at, Some(&run.format));
1104            out.push(piece(anchor));
1105            cursor = cursor.max(at + sentinel_len(plain_text, at));
1106            img_iter.next();
1107        }
1108
1109        push_text(&mut out, cursor, run.byte_end, Some(&run.format));
1110        cursor = cursor.max(run.byte_end);
1111    }
1112
1113    // Anchors past the last run.
1114    for anchor in img_iter {
1115        let at = anchor.byte_offset();
1116        push_text(&mut out, cursor, at, None);
1117        out.push(piece(anchor));
1118        cursor = cursor.max(at + sentinel_len(plain_text, at));
1119    }
1120
1121    push_text(&mut out, cursor, text_len, None);
1122
1123    out
1124}
1125
1126/// [`InlinePiece`], but positioned in the document's own **addressable character space**
1127/// rather than as byte offsets local to the block's `plain_text`.
1128///
1129/// `InlinePiece::Text { start, end, .. }` is a byte range good for slicing `plain_text` and
1130/// nothing else: it carries no notion of where in the *document* that range sits. Every
1131/// offset the rest of this crate deals out — `TextDocument::to_addressable_text()`, `find_all`
1132/// match positions, a block's own `document_position` — lives in one **character** space, and
1133/// a caller that reconstructs a document position by summing `InlinePiece` text lengths drifts
1134/// the moment a block holds a multi-byte character before the point in question, or an inline
1135/// image/footnote reference at all — their `U+FFFC` sentinel is three bytes but one char (see
1136/// `sentinel_len` on [`merge_runs_and_anchors`]). That is the same "offset from one space,
1137/// string from another" bug class the public API's `TextDocument::to_addressable_text()`
1138/// exists to close for whole-document offsets (see its doc comment), one level down, inside
1139/// a single block.
1140///
1141/// Built by [`addressable_inline_pieces`] (pure — block-local character space, `base_char_offset`
1142/// left at `0`) or [`crate::format_runs_query::addressable_inline_pieces_for_block`]
1143/// (store-aware — adds the block's own `document_position` so `start`/`end` land in the
1144/// *document's* space). Every downstream consumer that needs a piece boundary in that space —
1145/// a comment's stored quote, a DOCX/ODT comment marker split at an arbitrary character — reads
1146/// `start`/`end` straight off this type instead of re-deriving them by hand.
1147#[derive(Debug, Clone, PartialEq)]
1148pub struct AddressableInlinePiece {
1149    /// `[start, end)` in the addressable character space. `end - start` is always `1` for
1150    /// [`InlineContent::Image`] and [`InlineContent::FootnoteRef`] — the sentinel counts as
1151    /// exactly one character, matching how the document itself counts it — and equals the
1152    /// piece's own text's `chars().count()` for [`InlineContent::Text`].
1153    pub start: u32,
1154    pub end: u32,
1155    pub content: InlineContent,
1156    pub format: CharacterFormat,
1157}
1158
1159/// Build a block's [`AddressableInlinePiece`]s from its `plain_text`, format runs, and
1160/// anchors, offset by `base_char_offset` — the character position this block's own first
1161/// piece should start at.
1162///
1163/// Layered on [`merge_runs_and_anchors`] rather than duplicating its weave: the only thing
1164/// added here is the byte→char conversion (`plain_text[start..end].chars().count()` is the
1165/// only correct way to size a UTF-8 slice in the character space every other offset in this
1166/// crate uses — NOT `end - start`, which is a byte count) and a running `base_char_offset`
1167/// accumulator. Pass `0` to get offsets relative to this block alone, which is what this
1168/// module's own tests do; [`crate::format_runs_query::addressable_inline_pieces_for_block`]
1169/// passes the block's own `document_position` instead, to land in document-wide space.
1170pub fn addressable_inline_pieces(
1171    plain_text: &str,
1172    runs: &[FormatRun],
1173    anchors: &[BlockAnchor<'_>],
1174    base_char_offset: u32,
1175) -> Vec<AddressableInlinePiece> {
1176    let pieces = merge_runs_and_anchors(plain_text, runs, anchors);
1177    let mut out = Vec::with_capacity(pieces.len());
1178    let mut cursor = base_char_offset;
1179    for piece in pieces {
1180        match piece {
1181            InlinePiece::Text { start, end, format } => {
1182                let text = &plain_text[start as usize..end as usize];
1183                let len = text.chars().count() as u32;
1184                out.push(AddressableInlinePiece {
1185                    start: cursor,
1186                    end: cursor + len,
1187                    content: InlineContent::Text(text.to_string()),
1188                    format: format.cloned().unwrap_or_default(),
1189                });
1190                cursor += len;
1191            }
1192            InlinePiece::Image(anchor) => {
1193                out.push(AddressableInlinePiece {
1194                    start: cursor,
1195                    end: cursor + 1,
1196                    content: InlineContent::Image {
1197                        name: anchor.name.clone(),
1198                        alt: anchor.alt.clone(),
1199                        width: anchor.width,
1200                        height: anchor.height,
1201                        quality: anchor.quality,
1202                    },
1203                    format: anchor.format.clone(),
1204                });
1205                cursor += 1;
1206            }
1207            InlinePiece::FootnoteRef(anchor) => {
1208                out.push(AddressableInlinePiece {
1209                    start: cursor,
1210                    end: cursor + 1,
1211                    content: InlineContent::FootnoteRef {
1212                        label: anchor.label.clone(),
1213                    },
1214                    format: anchor.format.clone(),
1215                });
1216                cursor += 1;
1217            }
1218        }
1219    }
1220    out
1221}
1222
1223/// Synthesize a `Vec<InlineSegment>` view of a block from its
1224/// `plain_text`, `format_runs`, and `block_images`. Returns segments
1225/// in document order: a Text segment per format run (with a fallback
1226/// default-format segment for any uncovered bytes), and an Image
1227/// segment per anchor at its byte offset.
1228///
1229/// The canonical reader-side accessor for per-segment data — there is
1230/// no persistent inline-element table; this view is computed fresh
1231/// each call.
1232pub fn inline_segments_view(
1233    plain_text: &str,
1234    runs: &[FormatRun],
1235    images: &[ImageAnchor],
1236    footnote_refs: &[FootnoteRefAnchor],
1237) -> Vec<InlineSegment> {
1238    let bytes = plain_text.as_bytes();
1239    let default_format = CharacterFormat::default();
1240
1241    merge_runs_and_anchors(plain_text, runs, &block_anchors(images, footnote_refs))
1242        .into_iter()
1243        .map(|piece| match piece {
1244            InlinePiece::Text { start, end, format } => {
1245                let slice = &bytes[start as usize..end as usize];
1246                let text = std::str::from_utf8(slice)
1247                    .expect("block plain_text must be valid UTF-8")
1248                    .to_string();
1249                let mut seg = InlineSegment {
1250                    content: InlineContent::Text(text),
1251                    ..Default::default()
1252                };
1253                apply_character_format_to_segment(&mut seg, format.unwrap_or(&default_format));
1254                seg
1255            }
1256            InlinePiece::Image(anchor) => {
1257                let mut seg = InlineSegment {
1258                    content: InlineContent::Image {
1259                        name: anchor.name.clone(),
1260                        alt: anchor.alt.clone(),
1261                        width: anchor.width,
1262                        height: anchor.height,
1263                        quality: anchor.quality,
1264                    },
1265                    ..Default::default()
1266                };
1267                apply_character_format_to_segment(&mut seg, &anchor.format);
1268                seg
1269            }
1270            InlinePiece::FootnoteRef(anchor) => {
1271                let mut seg = InlineSegment {
1272                    content: InlineContent::FootnoteRef {
1273                        label: anchor.label.clone(),
1274                    },
1275                    ..Default::default()
1276                };
1277                apply_character_format_to_segment(&mut seg, &anchor.format);
1278                seg
1279            }
1280        })
1281        .collect()
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286    use super::*;
1287
1288    fn run(s: u32, e: u32, bold: bool) -> FormatRun {
1289        FormatRun {
1290            byte_start: s,
1291            byte_end: e,
1292            format: CharacterFormat {
1293                font_bold: Some(bold),
1294                ..Default::default()
1295            },
1296        }
1297    }
1298
1299    #[test]
1300    fn empty_runs_are_well_formed() {
1301        debug_assert_well_formed(&[], 0);
1302        debug_assert_well_formed(&[], 100);
1303    }
1304
1305    // ── merge_runs_and_anchors ────────────────────────────────────────────
1306
1307    fn anchor(at: u32, name: &str) -> ImageAnchor {
1308        ImageAnchor {
1309            byte_offset: at,
1310            name: name.into(),
1311            alt: String::new(),
1312            width: 10,
1313            height: 10,
1314            quality: 100,
1315            format: CharacterFormat::default(),
1316        }
1317    }
1318
1319    fn fn_anchor(at: u32, label: &str) -> FootnoteRefAnchor {
1320        FootnoteRefAnchor {
1321            byte_offset: at,
1322            label: label.into(),
1323            format: CharacterFormat::default(),
1324        }
1325    }
1326
1327    /// Render a merge as a compact string so ordering assertions read clearly:
1328    /// `"hello"` for unformatted text, `"*bold*"` for formatted, `[name]` for
1329    /// an image, `^label^` for a footnote reference.
1330    fn shape(text: &str, runs: &[FormatRun], images: &[ImageAnchor]) -> String {
1331        shape_with(text, runs, images, &[])
1332    }
1333
1334    fn shape_with(
1335        text: &str,
1336        runs: &[FormatRun],
1337        images: &[ImageAnchor],
1338        notes: &[FootnoteRefAnchor],
1339    ) -> String {
1340        merge_runs_and_anchors(text, runs, &block_anchors(images, notes))
1341            .into_iter()
1342            .map(|p| match p {
1343                InlinePiece::Text { start, end, format } => {
1344                    let s = &text[start as usize..end as usize];
1345                    if format.is_some() {
1346                        format!("*{s}*")
1347                    } else {
1348                        s.to_string()
1349                    }
1350                }
1351                InlinePiece::Image(a) => format!("[{}]", a.name),
1352                InlinePiece::FootnoteRef(a) => format!("^{}^", a.label),
1353            })
1354            .collect::<Vec<_>>()
1355            .join("|")
1356    }
1357
1358    /// A footnote reference weaves exactly as an image does — the whole reason
1359    /// the two share one function instead of getting a second copy of it.
1360    #[test]
1361    fn a_footnote_reference_inside_a_run_splits_it() {
1362        let text = "abcdef";
1363        let runs = [run(0, 6, true)];
1364        assert_eq!(
1365            shape_with(text, &runs, &[], &[fn_anchor(3, "n1")]),
1366            "*abc*|^n1^|*def*"
1367        );
1368    }
1369
1370    /// Images and references are stored in separate lists but occupy one
1371    /// stream. Walking the two lists in sequence rather than merging them by
1372    /// offset would emit every image before every note regardless of where they
1373    /// actually sit — the ordering bug this weave exists to prevent, in a new
1374    /// disguise.
1375    #[test]
1376    fn images_and_references_interleave_by_position() {
1377        let text = "abcdefgh";
1378        assert_eq!(
1379            shape_with(
1380                text,
1381                &[],
1382                &[anchor(6, "img")],
1383                &[fn_anchor(2, "early"), fn_anchor(7, "late")]
1384            ),
1385            "ab|^early^|cdef|[img]|g|^late^|h"
1386        );
1387    }
1388
1389    /// **The regression.** An image anchored inside a formatted run used to be
1390    /// skipped by the run loop (which only tested `offset < run.byte_start`)
1391    /// and swept up by the trailing loop, landing after every run in the block.
1392    /// Put a picture mid-sentence in bold text and every exporter moved it to
1393    /// the end of the paragraph.
1394    #[test]
1395    fn an_image_inside_a_run_splits_it_instead_of_jumping_to_the_end() {
1396        let text = "abcdef";
1397        let runs = [run(0, 6, true)];
1398        let images = [anchor(3, "img")];
1399        assert_eq!(shape(text, &runs, &images), "*abc*|[img]|*def*");
1400    }
1401
1402    #[test]
1403    fn an_image_on_a_run_start_boundary_stays_in_place() {
1404        let text = "abcdef";
1405        let runs = [run(3, 6, true)];
1406        assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "abc|[i]|*def*");
1407    }
1408
1409    /// The `<=` in the in-run loop: an image exactly on a run's end boundary is
1410    /// consumed with that run rather than deferred to the trailing sweep.
1411    #[test]
1412    fn an_image_on_a_run_end_boundary_stays_in_place() {
1413        let text = "abcdef";
1414        let runs = [run(0, 3, true)];
1415        assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "*abc*|[i]|def");
1416    }
1417
1418    #[test]
1419    fn an_image_between_two_runs_lands_between_them() {
1420        let text = "abcdef";
1421        let runs = [run(0, 3, true), run(3, 6, false)];
1422        let out = shape(text, &runs, &[anchor(3, "i")]);
1423        assert_eq!(out, "*abc*|[i]|*def*");
1424    }
1425
1426    #[test]
1427    fn several_images_inside_one_run_keep_their_order() {
1428        let text = "abcdefgh";
1429        let runs = [run(0, 8, true)];
1430        let images = [anchor(2, "a"), anchor(5, "b")];
1431        assert_eq!(shape(text, &runs, &images), "*ab*|[a]|*cde*|[b]|*fgh*");
1432    }
1433
1434    #[test]
1435    fn two_images_at_the_same_offset_both_survive_in_order() {
1436        let text = "abcd";
1437        let runs = [run(0, 4, true)];
1438        let images = [anchor(2, "a"), anchor(2, "b")];
1439        assert_eq!(shape(text, &runs, &images), "*ab*|[a]|[b]|*cd*");
1440    }
1441
1442    #[test]
1443    fn images_with_no_runs_at_all_are_ordered_with_their_gaps() {
1444        let text = "abcdef";
1445        let images = [anchor(0, "a"), anchor(3, "b"), anchor(6, "c")];
1446        assert_eq!(shape(text, &[], &images), "[a]|abc|[b]|def|[c]");
1447    }
1448
1449    #[test]
1450    fn text_uncovered_by_any_run_stays_unformatted() {
1451        let text = "abcdef";
1452        let runs = [run(2, 4, true)];
1453        assert_eq!(shape(text, &runs, &[]), "ab|*cd*|ef");
1454    }
1455
1456    #[test]
1457    fn a_block_with_neither_runs_nor_images_is_one_plain_piece() {
1458        assert_eq!(shape("abc", &[], &[]), "abc");
1459        assert_eq!(shape("", &[], &[]), "");
1460    }
1461
1462    /// Whatever the arrangement, the merge must reproduce the block's bytes
1463    /// exactly once, in order — never dropping or duplicating a slice. The
1464    /// old implementation could regress its cursor and re-emit text twice.
1465    #[test]
1466    fn every_byte_is_emitted_exactly_once_and_in_order() {
1467        let text = "abcdefghij";
1468        let arrangements: [(&[FormatRun], &[ImageAnchor]); 6] = [
1469            (&[], &[]),
1470            (&[run(0, 10, true)], &[anchor(5, "m")]),
1471            (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1472            (&[run(2, 5, true)], &[anchor(0, "a"), anchor(10, "z")]),
1473            (&[run(0, 3, true), run(7, 10, true)], &[anchor(3, "m")]),
1474            (
1475                &[run(1, 4, true), run(4, 9, false)],
1476                &[anchor(1, "a"), anchor(4, "b"), anchor(9, "c")],
1477            ),
1478        ];
1479        for (i, (runs, images)) in arrangements.iter().enumerate() {
1480            let pieces = merge_runs_and_anchors(text, runs, &block_anchors(images, &[]));
1481            let mut cursor = 0u32;
1482            let mut rebuilt = String::new();
1483            for piece in &pieces {
1484                if let InlinePiece::Text { start, end, .. } = piece {
1485                    assert_eq!(*start, cursor, "arrangement {i}: gap or overlap");
1486                    assert!(start < end, "arrangement {i}: empty piece emitted");
1487                    rebuilt.push_str(&text[*start as usize..*end as usize]);
1488                    cursor = *end;
1489                }
1490            }
1491            assert_eq!(cursor, text.len() as u32, "arrangement {i}: truncated");
1492            assert_eq!(rebuilt, text, "arrangement {i}");
1493            let img_count = pieces
1494                .iter()
1495                .filter(|p| matches!(p, InlinePiece::Image(_)))
1496                .count();
1497            assert_eq!(img_count, images.len(), "arrangement {i}: lost an image");
1498        }
1499    }
1500
1501    /// `inline_segments_view` is built on the merge, so it inherits the fix.
1502    #[test]
1503    fn inline_segments_view_places_a_mid_run_image_correctly() {
1504        let segs = inline_segments_view("abcdef", &[run(0, 6, true)], &[anchor(3, "img")], &[]);
1505        assert_eq!(segs.len(), 3);
1506        assert!(matches!(&segs[0].content, InlineContent::Text(t) if t == "abc"));
1507        assert!(matches!(&segs[1].content, InlineContent::Image { name, .. } if name == "img"));
1508        assert!(matches!(&segs[2].content, InlineContent::Text(t) if t == "def"));
1509        // The split keeps the run's formatting on both sides of the image.
1510        assert_eq!(segs[0].fmt_font_bold, Some(true));
1511        assert_eq!(segs[2].fmt_font_bold, Some(true));
1512    }
1513
1514    #[test]
1515    fn inline_segments_view_carries_alt_text_through() {
1516        let mut a = anchor(1, "img");
1517        a.alt = "a black cat".into();
1518        let segs = inline_segments_view("ab", &[], &[a], &[]);
1519        let alt = segs.iter().find_map(|s| match &s.content {
1520            InlineContent::Image { alt, .. } => Some(alt.clone()),
1521            _ => None,
1522        });
1523        assert_eq!(alt.as_deref(), Some("a black cat"));
1524    }
1525
1526    // ── addressable_inline_pieces ───────────────────────────────────────
1527
1528    /// Render an `addressable_inline_pieces` result as `(start, end, label)` triples, so a
1529    /// failing assertion shows the whole span list at once instead of one field at a time.
1530    fn pieces_shape(out: &[AddressableInlinePiece]) -> Vec<(u32, u32, String)> {
1531        out.iter()
1532            .map(|p| {
1533                let label = match &p.content {
1534                    InlineContent::Text(t) => t.clone(),
1535                    InlineContent::Image { name, .. } => format!("[{name}]"),
1536                    InlineContent::FootnoteRef { label } => format!("^{label}^"),
1537                    InlineContent::Empty => String::new(),
1538                };
1539                (p.start, p.end, label)
1540            })
1541            .collect()
1542    }
1543
1544    #[test]
1545    fn a_lone_text_piece_spans_its_char_length() {
1546        let out = addressable_inline_pieces("hello", &[], &[], 0);
1547        assert_eq!(pieces_shape(&out), vec![(0, 5, "hello".to_string())]);
1548    }
1549
1550    #[test]
1551    fn base_char_offset_shifts_every_piece_by_the_same_amount() {
1552        let out = addressable_inline_pieces("hello", &[], &[], 100);
1553        assert_eq!(pieces_shape(&out), vec![(100, 105, "hello".to_string())]);
1554    }
1555
1556    /// The regression this type exists to prevent: a multi-byte character before an anchor
1557    /// must not leak its extra BYTE into the anchor's CHAR position. "café" is 5 bytes (é is
1558    /// 2 bytes in UTF-8) but 4 chars — code that summed byte lengths instead of counting
1559    /// chars would place the image at char 5, one past where it actually sits, and every
1560    /// offset after it would carry the same one-character drift.
1561    #[test]
1562    fn a_multibyte_character_before_an_image_does_not_leak_its_extra_byte_into_the_char_position() {
1563        let text = "café";
1564        assert_eq!(text.len(), 5, "test assumes café is 5 bytes");
1565        assert_eq!(text.chars().count(), 4, "test assumes café is 4 chars");
1566        let images = [anchor(5, "pic")]; // byte_offset 5 == right after "café"'s 5 bytes
1567        let anchors = block_anchors(&images, &[]);
1568        let out = addressable_inline_pieces(text, &[], &anchors, 0);
1569        assert_eq!(
1570            pieces_shape(&out),
1571            vec![(0, 4, "café".to_string()), (4, 5, "[pic]".to_string())]
1572        );
1573    }
1574
1575    /// An image sitting inside a formatted run gets its own one-char span, and the text
1576    /// before/after it still lands at the right char offsets — the boundary this milestone's
1577    /// comment-export use case cares about most: "a comment boundary landing immediately
1578    /// after an inline image."
1579    #[test]
1580    fn an_image_mid_run_gets_a_one_char_span_and_the_trailing_text_resumes_right_after_it() {
1581        let text = "abcdef";
1582        let runs = [run(0, 6, true)];
1583        let images = [anchor(3, "img")];
1584        let anchors = block_anchors(&images, &[]);
1585        let out = addressable_inline_pieces(text, &runs, &anchors, 0);
1586        assert_eq!(
1587            pieces_shape(&out),
1588            vec![
1589                (0, 3, "abc".to_string()),
1590                (3, 4, "[img]".to_string()),
1591                (4, 7, "def".to_string()),
1592            ]
1593        );
1594    }
1595
1596    /// A footnote reference gets a one-char span exactly like an image — the boundary
1597    /// case "a comment boundary landing immediately after a footnote reference."
1598    #[test]
1599    fn a_footnote_reference_gets_a_one_char_span_too() {
1600        let text = "abcdef";
1601        let notes = [fn_anchor(3, "n1")];
1602        let anchors = block_anchors(&[], &notes);
1603        let out = addressable_inline_pieces(text, &[], &anchors, 0);
1604        assert_eq!(
1605            pieces_shape(&out),
1606            vec![
1607                (0, 3, "abc".to_string()),
1608                (3, 4, "^n1^".to_string()),
1609                (4, 7, "def".to_string()),
1610            ]
1611        );
1612    }
1613
1614    /// Whatever the arrangement of runs and anchors, the pieces must tile the block's char
1615    /// space with no gap, no overlap, and no dropped anchor — the char-space analogue of
1616    /// `every_byte_is_emitted_exactly_once_and_in_order` above.
1617    #[test]
1618    fn pieces_are_contiguous_in_char_space_with_no_gaps_or_overlaps() {
1619        let text = "abcdefghij";
1620        let arrangements: [(&[FormatRun], &[ImageAnchor]); 4] = [
1621            (&[], &[]),
1622            (&[run(0, 10, true)], &[anchor(5, "m")]),
1623            (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1624            (&[run(1, 4, true), run(4, 9, false)], &[anchor(9, "c")]),
1625        ];
1626        for (i, (runs, images)) in arrangements.iter().enumerate() {
1627            let anchors = block_anchors(images, &[]);
1628            let out = addressable_inline_pieces(text, runs, &anchors, 7);
1629            let mut cursor = 7u32;
1630            for piece in &out {
1631                assert_eq!(piece.start, cursor, "arrangement {i}: gap or overlap");
1632                assert!(piece.start < piece.end, "arrangement {i}: empty piece");
1633                cursor = piece.end;
1634            }
1635            // Each anchor is a logical character with no bytes of its own in `text`, so
1636            // it adds one char beyond `text`'s own count — same accounting `block_char_length`
1637            // uses for a real (sentinel-bearing) block, just without a sentinel to count here.
1638            assert_eq!(
1639                cursor,
1640                7 + text.chars().count() as u32 + images.len() as u32,
1641                "arrangement {i}: did not tile the whole block"
1642            );
1643        }
1644    }
1645
1646    #[test]
1647    fn coalesce_merges_adjacent_equal_runs() {
1648        let mut rs = vec![run(0, 5, true), run(5, 10, true), run(10, 15, false)];
1649        coalesce_in_place(&mut rs);
1650        assert_eq!(rs.len(), 2);
1651        assert_eq!(rs[0].byte_end, 10);
1652    }
1653
1654    #[test]
1655    fn coalesce_leaves_disjoint_runs_alone() {
1656        let mut rs = vec![run(0, 5, true), run(7, 10, true)];
1657        coalesce_in_place(&mut rs);
1658        assert_eq!(rs.len(), 2);
1659    }
1660
1661    #[test]
1662    fn splice_range_clips_straddling_runs() {
1663        let mut rs = vec![run(0, 20, true)];
1664        splice_range(&mut rs, 5..15, vec![run(5, 15, false)]);
1665        assert_eq!(rs.len(), 3);
1666        assert_eq!(rs[0].byte_end, 5);
1667        assert_eq!(rs[1].format.font_bold, Some(false));
1668        assert_eq!(rs[2].byte_start, 15);
1669    }
1670
1671    #[test]
1672    fn splice_range_empty_replacement_removes_inner_runs() {
1673        let mut rs = vec![run(0, 5, true), run(5, 10, false), run(10, 15, true)];
1674        splice_range(&mut rs, 5..10, vec![]);
1675        // 0..5 bold, then 10..15 bold — after coalesce these are NOT adjacent
1676        // (there's a gap from 5..10 in the run table, meaning "no format").
1677        assert_eq!(rs.len(), 2);
1678        assert_eq!(rs[0].byte_end, 5);
1679        assert_eq!(rs[1].byte_start, 10);
1680    }
1681
1682    #[test]
1683    fn shift_after_moves_downstream() {
1684        let mut rs = vec![run(0, 5, true), run(10, 15, false)];
1685        shift_after(&mut rs, 5, 3);
1686        assert_eq!(rs[0].byte_start, 0); // unchanged
1687        assert_eq!(rs[1].byte_start, 13);
1688        assert_eq!(rs[1].byte_end, 18);
1689    }
1690}
1691
1692/// The adversarial corpus for [`shift_runs_for_replace`].
1693///
1694/// Replace is the one edit that rewrites a writer's prose *in bulk*, so its formatting
1695/// behaviour has to be pinned rather than inherited by accident. Before this module
1696/// there were 11 replace tests in the repo and **not one** of them mentioned
1697/// `FormatRun`: the behaviour was emergent, undecided, and untested.
1698#[cfg(test)]
1699mod replace_policy_tests {
1700    use super::*;
1701
1702    fn fmt(tag: &str) -> CharacterFormat {
1703        CharacterFormat {
1704            font_bold: Some(tag == "B"),
1705            font_italic: Some(tag == "I"),
1706            ..Default::default()
1707        }
1708    }
1709    fn r(start: u32, end: u32, tag: &str) -> FormatRun {
1710        FormatRun {
1711            byte_start: start,
1712            byte_end: end,
1713            format: fmt(tag),
1714        }
1715    }
1716    /// Compact "0..5=B 8..12=I" rendering, so a failure shows the whole run list.
1717    fn show(runs: &[FormatRun]) -> String {
1718        if runs.is_empty() {
1719            return "[]".to_string();
1720        }
1721        runs.iter()
1722            .map(|x| {
1723                let tag = if x.format.font_bold == Some(true) {
1724                    "B"
1725                } else if x.format.font_italic == Some(true) {
1726                    "I"
1727                } else {
1728                    "p"
1729                };
1730                format!("{}..{}={tag}", x.byte_start, x.byte_end)
1731            })
1732            .collect::<Vec<_>>()
1733            .join(" ")
1734    }
1735    fn replace(
1736        runs: &[FormatRun],
1737        start: u32,
1738        end: u32,
1739        n: u32,
1740        policy: ReplaceFormatPolicy,
1741    ) -> Vec<FormatRun> {
1742        let mut runs = runs.to_vec();
1743        shift_runs_for_replace(&mut runs, start, end, n, policy).expect("valid replace");
1744        runs
1745    }
1746
1747    /// **The spec-conformance test.** `InheritPreceding` must be byte-for-byte what
1748    /// today's `shift_runs_for_delete` + `shift_runs_for_insert` produces — anything
1749    /// else silently rewrites the formatting of every replace that ever shipped.
1750    ///
1751    /// Differential, not hand-transcribed: it runs the historical primitives directly
1752    /// and compares, so it stays honest even if their behaviour is ever changed.
1753    #[test]
1754    fn inherit_preceding_matches_the_historical_delete_then_insert() {
1755        let corpus: Vec<(&str, Vec<FormatRun>, u32, u32, u32)> = vec![
1756            ("run ends exactly at start", vec![r(0, 5, "B")], 5, 10, 3),
1757            ("run begins exactly at start", vec![r(5, 8, "B")], 5, 10, 3),
1758            (
1759                "run begins at start, outlives end",
1760                vec![r(5, 20, "B")],
1761                5,
1762                10,
1763                3,
1764            ),
1765            (
1766                "run straddles the whole range",
1767                vec![r(0, 20, "B")],
1768                5,
1769                10,
1770                3,
1771            ),
1772            ("no run touches the start", vec![r(12, 20, "B")], 5, 10, 3),
1773            ("bold tail inside the range", vec![r(9, 13, "B")], 5, 13, 4),
1774            ("pure delete", vec![r(0, 20, "B")], 5, 10, 0),
1775            ("pure insert", vec![r(0, 20, "B")], 5, 5, 3),
1776            (
1777                "same format either side coalesces",
1778                vec![r(0, 5, "B"), r(10, 15, "B")],
1779                5,
1780                10,
1781                3,
1782            ),
1783            (
1784                "different formats either side",
1785                vec![r(0, 5, "B"), r(10, 15, "I")],
1786                5,
1787                10,
1788                3,
1789            ),
1790            ("empty run list", vec![], 5, 10, 3),
1791            ("the only run is consumed", vec![r(5, 10, "B")], 5, 10, 3),
1792            (
1793                "replacement longer than the range",
1794                vec![r(0, 5, "B")],
1795                5,
1796                10,
1797                20,
1798            ),
1799            (
1800                "three runs straddled",
1801                vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")],
1802                2,
1803                7,
1804                4,
1805            ),
1806            (
1807                "gap between two same-format runs is deleted",
1808                vec![r(0, 5, "B"), r(8, 13, "B")],
1809                5,
1810                8,
1811                0,
1812            ),
1813        ];
1814
1815        for (name, runs, start, end, n) in corpus {
1816            // The historical composition, run for real.
1817            let mut expected = runs.clone();
1818            shift_runs_for_delete(&mut expected, start, end);
1819            shift_runs_for_insert(&mut expected, start, n);
1820
1821            let got = replace(&runs, start, end, n, ReplaceFormatPolicy::InheritPreceding);
1822
1823            assert_eq!(
1824                show(&got),
1825                show(&expected),
1826                "InheritPreceding diverged from delete+insert for {name:?} \
1827                 (replace {start}..{end}, n={n})\n  before:   {}\n  historical: {}\n  got:        {}",
1828                show(&runs),
1829                show(&expected),
1830                show(&got),
1831            );
1832        }
1833    }
1834
1835    /// The motivating data loss: renaming a character whose name reads `Auré**lien**`.
1836    /// The default drops the bold — that is what shipped, and it is now visible and
1837    /// chosen rather than emergent. Every other policy is a way to not lose it.
1838    #[test]
1839    fn the_four_policies_diverge_on_a_partly_bold_name() {
1840        // "Auré" plain (bytes 0..5, é is two bytes), "lien" bold (5..9).
1841        let runs = vec![r(5, 9, "B")];
1842        let (start, end, n) = (0, 9, 9); // rename the whole name, same length
1843
1844        use ReplaceFormatPolicy::*;
1845        assert_eq!(
1846            show(&replace(&runs, start, end, n, InheritPreceding)),
1847            "[]",
1848            "the historical default destroys the bold — pinned, not endorsed"
1849        );
1850        assert_eq!(
1851            show(&replace(&runs, start, end, n, PreserveNothing)),
1852            "[]",
1853            "explicitly unformatted"
1854        );
1855        assert_eq!(
1856            show(&replace(&runs, start, end, n, PreserveIfFullyCovered)),
1857            "[]",
1858            "no SINGLE run covers 0..9 — it must fall back to inheritance, not guess"
1859        );
1860        // Bold covers 4 of the 9 bytes, plain covers 5 → plain dominates.
1861        assert_eq!(
1862            show(&replace(&runs, start, end, n, KeepDominantRun)),
1863            "[]",
1864            "plain covers more of the name than the bold does"
1865        );
1866
1867        // …but when the bold covers MOST of the name, KeepDominantRun keeps it.
1868        let mostly_bold = vec![r(1, 9, "B")];
1869        assert_eq!(
1870            show(&replace(&mostly_bold, 0, 9, 9, KeepDominantRun)),
1871            "0..9=B",
1872            "bold covers 8 of 9 bytes — the rename must keep it"
1873        );
1874    }
1875
1876    /// "Fully covered" means ONE run covers the range — not "the runs jointly span it".
1877    /// A gapless Italic+Bold union spanning the range exactly must NOT be treated as
1878    /// covered, or the replacement silently inherits whichever run was looked at first.
1879    #[test]
1880    fn fully_covered_means_a_single_run_not_a_gapless_union() {
1881        let two = vec![r(0, 3, "I"), r(3, 10, "B")];
1882        assert_eq!(
1883            show(&replace(
1884                &two,
1885                0,
1886                10,
1887                4,
1888                ReplaceFormatPolicy::PreserveIfFullyCovered
1889            )),
1890            "[]",
1891            "two different-format runs jointly spanning the range are not 'covered'; \
1892             with no run preceding the start, the fallback is unformatted"
1893        );
1894
1895        // One run that really does cover it, and begins exactly at the start — the case
1896        // InheritPreceding cannot see (a run at `start` never inherits).
1897        let one = vec![r(5, 20, "B")];
1898        assert_eq!(
1899            show(&replace(
1900                &one,
1901                5,
1902                10,
1903                3,
1904                ReplaceFormatPolicy::PreserveIfFullyCovered
1905            )),
1906            "5..18=B",
1907            "a single covering run keeps its format across the rename"
1908        );
1909        assert_eq!(
1910            show(&replace(
1911                &one,
1912                5,
1913                10,
1914                3,
1915                ReplaceFormatPolicy::InheritPreceding
1916            )),
1917            "8..18=B",
1918            "…which the default would have lost: the replacement lands unformatted"
1919        );
1920    }
1921
1922    /// A run that merely *touches* the range must not leak its format to the whole
1923    /// replacement.
1924    #[test]
1925    fn a_partially_overlapping_run_does_not_count_as_covering() {
1926        let runs = vec![r(0, 8, "B")]; // covers only 5..8 of the range 5..12
1927        assert_eq!(
1928            show(&replace(
1929                &runs,
1930                5,
1931                12,
1932                4,
1933                ReplaceFormatPolicy::PreserveIfFullyCovered
1934            )),
1935            "0..9=B",
1936            "not covered → falls back to inheritance, which extends the preceding bold; \
1937             it must NOT format the whole replacement as though bold had covered it"
1938        );
1939    }
1940
1941    /// Ties between two runs resolve to the EARLIEST, deterministically.
1942    ///
1943    /// `Iterator::max_by_key` returns the LAST maximum, so the obvious one-liner would
1944    /// have silently picked the other run here.
1945    #[test]
1946    fn a_dominance_tie_between_two_runs_goes_to_the_earlier() {
1947        let runs = vec![r(0, 3, "B"), r(3, 6, "I")]; // 3 bytes each
1948        assert_eq!(
1949            show(&replace(
1950                &runs,
1951                0,
1952                6,
1953                4,
1954                ReplaceFormatPolicy::KeepDominantRun
1955            )),
1956            "0..4=B",
1957            "a true tie must resolve to the earlier run, not to whichever the iterator \
1958             happened to visit last"
1959        );
1960    }
1961
1962    /// A tie between a run and the unformatted gap goes to the run: losing formatting is
1963    /// the destructive outcome, so it needs a strict majority of *plain* to win.
1964    #[test]
1965    fn a_dominance_tie_against_plain_text_keeps_the_formatting() {
1966        let runs = vec![r(4, 8, "B")]; // 4 bold bytes, 4 plain bytes in 0..8
1967        assert_eq!(
1968            show(&replace(
1969                &runs,
1970                0,
1971                8,
1972                5,
1973                ReplaceFormatPolicy::KeepDominantRun
1974            )),
1975            "0..5=B",
1976            "an even split must keep the formatting rather than silently drop it"
1977        );
1978    }
1979
1980    /// An empty range replaces nothing, so it is an insertion — and every policy that
1981    /// reasons about "what was covered" must defer to the insert convention instead of
1982    /// stripping the format the typed text would have inherited.
1983    #[test]
1984    fn an_empty_range_is_an_insert_and_no_coverage_policy_overrides_it() {
1985        let runs = vec![r(0, 5, "B"), r(5, 10, "I")];
1986        use ReplaceFormatPolicy::*;
1987        for policy in [InheritPreceding, PreserveIfFullyCovered, KeepDominantRun] {
1988            assert_eq!(
1989                show(&replace(&runs, 5, 5, 2, policy)),
1990                "0..7=B 7..12=I",
1991                "{policy:?}: typing at a boundary must inherit the run to the LEFT (Qt \
1992                 convention) — an empty range destroyed no formatting, so there is \
1993                 nothing for a coverage policy to override"
1994            );
1995        }
1996        // The one policy that is an explicit request, not an inference, still applies.
1997        assert_eq!(
1998            show(&replace(&runs, 5, 5, 2, PreserveNothing)),
1999            "0..5=B 7..12=I",
2000            "PreserveNothing asks for unformatted text, and means it even on an insert"
2001        );
2002    }
2003
2004    /// Nothing to do must mean nothing done — no fabricated runs, no lost ones.
2005    #[test]
2006    fn a_zero_width_zero_length_replace_is_the_identity() {
2007        let runs = vec![r(0, 5, "B"), r(7, 12, "I")];
2008        for policy in [
2009            ReplaceFormatPolicy::InheritPreceding,
2010            ReplaceFormatPolicy::PreserveIfFullyCovered,
2011            ReplaceFormatPolicy::KeepDominantRun,
2012            ReplaceFormatPolicy::PreserveNothing,
2013        ] {
2014            assert_eq!(
2015                show(&replace(&runs, 6, 6, 0, policy)),
2016                "0..5=B 7..12=I",
2017                "{policy:?} changed a no-op edit"
2018            );
2019        }
2020    }
2021
2022    /// `PreserveNothing` must leave the region genuinely *unformatted* — not covered by
2023    /// a fabricated run carrying `CharacterFormat::default()`, which is a different
2024    /// thing and would defeat coalescing forever after.
2025    #[test]
2026    fn preserve_nothing_fabricates_no_default_run() {
2027        let runs = vec![r(0, 5, "B")];
2028        let got = replace(&runs, 7, 9, 2, ReplaceFormatPolicy::PreserveNothing);
2029        assert_eq!(show(&got), "0..5=B", "no run may be invented for the gap");
2030        assert!(
2031            got.iter().all(|x| x.byte_start < 7 || x.byte_end > 9),
2032            "the replaced span must carry no run at all"
2033        );
2034    }
2035
2036    /// Offsets are BYTES, not chars. A 4-byte emoji replaced by 2 ASCII bytes must
2037    /// shift downstream runs by -2, not by -1 (chars) or 0.
2038    #[test]
2039    fn offsets_are_bytes_not_characters() {
2040        // "🎉" (4 bytes, bold) + " " + "abcd" (italic).
2041        let runs = vec![r(0, 4, "B"), r(5, 9, "I")];
2042        let got = replace(&runs, 0, 4, 2, ReplaceFormatPolicy::KeepDominantRun);
2043        assert_eq!(
2044            show(&got),
2045            "0..2=B 3..7=I",
2046            "the trailing italic must shift back by the BYTE delta (4 -> 2 = -2)"
2047        );
2048    }
2049
2050    /// Every policy must leave the run list well-formed — sorted, non-overlapping,
2051    /// coalesced, inside the block. This is the invariant a release build no longer
2052    /// merely asserts.
2053    #[test]
2054    fn every_policy_leaves_the_runs_well_formed() {
2055        let setups: Vec<(Vec<FormatRun>, u32, u32, u32, usize)> = vec![
2056            (vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")], 2, 7, 4, 8),
2057            (vec![r(0, 5, "B"), r(8, 13, "B")], 5, 8, 0, 10),
2058            (vec![r(0, 5, "B"), r(7, 12, "B")], 8, 10, 2, 12),
2059            (vec![r(3, 7, "B")], 3, 7, 0, 6),
2060            (vec![], 2, 6, 3, 9),
2061        ];
2062        for (runs, start, end, n, text_len) in setups {
2063            for policy in [
2064                ReplaceFormatPolicy::InheritPreceding,
2065                ReplaceFormatPolicy::PreserveIfFullyCovered,
2066                ReplaceFormatPolicy::KeepDominantRun,
2067                ReplaceFormatPolicy::PreserveNothing,
2068            ] {
2069                let got = replace(&runs, start, end, n, policy);
2070                check_well_formed(&got, text_len).unwrap_or_else(|e| {
2071                    panic!(
2072                        "{policy:?} produced malformed runs from {} (replace {start}..{end}, \
2073                         n={n}): {} — {e}",
2074                        show(&runs),
2075                        show(&got)
2076                    )
2077                });
2078            }
2079        }
2080    }
2081
2082    /// Two same-format runs separated by an untouched gap must stay separate — coalescing
2083    /// is for *adjacent* runs, and over-eager merging would swallow the plain text between
2084    /// them.
2085    #[test]
2086    fn an_untouched_gap_between_equal_runs_survives() {
2087        let runs = vec![r(0, 5, "B"), r(7, 12, "B")];
2088        assert_eq!(
2089            show(&replace(
2090                &runs,
2091                8,
2092                10,
2093                2,
2094                ReplaceFormatPolicy::InheritPreceding
2095            )),
2096            "0..5=B 7..12=B",
2097            "the plain gap at 5..7 must not be swallowed"
2098        );
2099    }
2100
2101    /// An inverted range is refused, not asserted away.
2102    #[test]
2103    fn an_inverted_range_is_an_error_not_a_panic() {
2104        let mut runs = vec![r(0, 5, "B")];
2105        let err =
2106            shift_runs_for_replace(&mut runs, 10, 5, 3, ReplaceFormatPolicy::InheritPreceding)
2107                .expect_err("an inverted range must be rejected");
2108        assert!(matches!(
2109            err,
2110            FormatRunError::ReversedRange { start: 10, end: 5 }
2111        ));
2112        assert_eq!(show(&runs), "0..5=B", "a refused edit must change nothing");
2113    }
2114}
2115
2116/// The runtime guards that replaced the release-mode-invisible `debug_assert!`s.
2117#[cfg(test)]
2118mod invariant_check_tests {
2119    use super::*;
2120
2121    fn run(start: u32, end: u32, bold: bool) -> FormatRun {
2122        FormatRun {
2123            byte_start: start,
2124            byte_end: end,
2125            format: CharacterFormat {
2126                font_bold: Some(bold),
2127                ..Default::default()
2128            },
2129        }
2130    }
2131
2132    /// The whole point: in a **release** build `debug_assert!` is gone, so a violating
2133    /// splice used to sail straight through and build a malformed run list. Now it is
2134    /// reported, and the caller's runs are left exactly as they were.
2135    #[test]
2136    fn a_replacement_outside_the_range_is_rejected_without_mutating() {
2137        let mut runs = vec![run(0, 20, true)];
2138        let before = runs.clone();
2139
2140        let err = try_splice_range(&mut runs, 5..10, vec![run(5, 15, false)])
2141            .expect_err("a replacement run reaching past range.end must be rejected");
2142
2143        assert!(matches!(
2144            err,
2145            FormatRunError::ReplacementOutsideRange {
2146                run_end: 15,
2147                range_end: 10,
2148                ..
2149            }
2150        ));
2151        assert_eq!(
2152            runs, before,
2153            "a rejected splice must not half-apply — validation happens before mutation"
2154        );
2155    }
2156
2157    #[test]
2158    // The inverted range is the whole point of the test — it is what a caller must not
2159    // be able to sneak past a release build.
2160    #[allow(clippy::reversed_empty_ranges)]
2161    fn a_reversed_range_is_rejected() {
2162        let mut runs = vec![run(0, 20, true)];
2163        assert!(matches!(
2164            try_splice_range(&mut runs, 10..5, vec![]),
2165            Err(FormatRunError::ReversedRange { start: 10, end: 5 })
2166        ));
2167    }
2168
2169    #[test]
2170    fn a_legal_splice_still_works_through_the_checked_path() {
2171        let mut runs = vec![run(0, 20, true)];
2172        try_splice_range(&mut runs, 5..15, vec![run(5, 15, false)]).expect("legal");
2173        assert_eq!(runs.len(), 3);
2174        assert_eq!(runs[1].format.font_bold, Some(false));
2175    }
2176
2177    #[test]
2178    fn check_well_formed_catches_what_debug_assert_used_to() {
2179        assert!(check_well_formed(&[], 0).is_ok());
2180        assert!(check_well_formed(&[run(0, 5, true)], 5).is_ok());
2181
2182        assert!(matches!(
2183            check_well_formed(&[run(5, 5, true)], 10),
2184            Err(FormatRunError::EmptyRun { .. })
2185        ));
2186        assert!(matches!(
2187            check_well_formed(&[run(0, 8, true), run(5, 10, false)], 10),
2188            Err(FormatRunError::RunsOverlap { .. })
2189        ));
2190        assert!(matches!(
2191            check_well_formed(&[run(0, 5, true), run(5, 10, true)], 10),
2192            Err(FormatRunError::RunsNotCoalesced { .. })
2193        ));
2194        assert!(matches!(
2195            check_well_formed(&[run(0, 20, true)], 10),
2196            Err(FormatRunError::RunPastEndOfBlock { text_len: 10, .. })
2197        ));
2198    }
2199}