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/// [`shift_runs_for_insert`] for text typed into the block, which also
611/// inherits a format at the start of the block. There nothing precedes the
612/// insertion, and the text takes the format of the run that begins there: the
613/// format of the block's first character, as Qt (`QTextCursor::charFormat` at a
614/// block start), Word and TextEdit give it. So text typed at the start of a
615/// bold paragraph is bold. Anywhere else this is `shift_runs_for_insert`.
616///
617/// A link is not part of that format: text typed before a link that opens the
618/// paragraph is not part of the link, as in Word (its target, its being an
619/// anchor, the names it is the target of and its tooltip are left out, and
620/// the rest of the first character's format is kept).
621///
622/// For typing, not for content that brings its own formats (a paste, an
623/// import), whose unformatted parts must stay unformatted.
624pub fn shift_runs_for_typed_insert(
625    runs: &mut Vec<FormatRun>,
626    byte_offset: u32,
627    inserted_bytes: u32,
628) {
629    if inserted_bytes == 0 {
630        return;
631    }
632    let first = runs
633        .iter()
634        .position(|run| run.byte_start == 0 && run.byte_end > 0);
635    let Some(first) = first.filter(|_| byte_offset == 0) else {
636        shift_runs_for_insert(runs, byte_offset, inserted_bytes);
637        return;
638    };
639    let format = &runs[first].format;
640    let inherited = CharacterFormat {
641        anchor_href: None,
642        anchor_names: Vec::new(),
643        is_anchor: None,
644        tooltip: None,
645        ..format.clone()
646    };
647    if inherited == *format {
648        for (index, run) in runs.iter_mut().enumerate() {
649            if index != first {
650                run.byte_start += inserted_bytes;
651            }
652            run.byte_end += inserted_bytes;
653        }
654        return;
655    }
656    for run in runs.iter_mut() {
657        run.byte_start += inserted_bytes;
658        run.byte_end += inserted_bytes;
659    }
660    if inherited != CharacterFormat::default() {
661        runs.insert(
662            0,
663            FormatRun {
664                byte_start: 0,
665                byte_end: inserted_bytes,
666                format: inherited,
667            },
668        );
669    }
670}
671
672/// Apply a "delete byte range `[byte_start..byte_end)`" mutation to a
673/// block's runs. Splices the range with empty replacement (clipping
674/// straddling runs) and shifts everything past `byte_end` back by the
675/// deleted length. Adjacent runs that end up equal-format are coalesced.
676pub fn shift_runs_for_delete(runs: &mut Vec<FormatRun>, byte_start: u32, byte_end: u32) {
677    if byte_end <= byte_start {
678        return;
679    }
680    splice_range(runs, byte_start..byte_end, Vec::new());
681    let delta = (byte_end - byte_start) as i32;
682    shift_after(runs, byte_end, -delta);
683    // The shift can make a left-clipped run abut a shifted trailing run
684    // with identical format; coalesce once more to restore the invariant.
685    coalesce_in_place(runs);
686}
687
688/// Apply a "replace byte range `[byte_start..byte_end)` with `replacement_bytes` bytes"
689/// mutation to a block's runs, choosing explicitly what the replacement wears.
690///
691/// This is the one edit where the old delete-then-insert composition quietly lost a
692/// writer's formatting: replacing `Auré**lien**` deletes both runs under the range and
693/// then lets the replacement inherit whatever preceded it, so the bold is gone. That
694/// behaviour is still available — and is still the default — but it is now a *decision*
695/// ([`ReplaceFormatPolicy`]) rather than an accident of two functions being called in
696/// sequence.
697///
698/// Additive by design: `shift_runs_for_delete` / `shift_runs_for_insert` are untouched,
699/// because 13 other call sites across delete/insert/paste depend on their exact
700/// behaviour. [`ReplaceFormatPolicy::InheritPreceding`] is implemented *by calling that
701/// very composition*, so the default cannot drift away from what shipped.
702///
703/// Returns `Err` rather than corrupting the block if the range is inverted or the
704/// re-splice would violate the run invariants — see [`FormatRunError`].
705pub fn shift_runs_for_replace(
706    runs: &mut Vec<FormatRun>,
707    byte_start: u32,
708    byte_end: u32,
709    replacement_bytes: u32,
710    policy: ReplaceFormatPolicy,
711) -> Result<(), FormatRunError> {
712    if byte_end < byte_start {
713        return Err(FormatRunError::ReversedRange {
714            start: byte_start,
715            end: byte_end,
716        });
717    }
718
719    // Decide what the replacement wears from the runs as they stand BEFORE the edit —
720    // afterwards the runs under the range are gone and the evidence with them.
721    //
722    // `None` here means "do not override": let the composition below decide, which is
723    // exactly `InheritPreceding`.
724    //
725    // An empty range replaces nothing, so it is an *insertion*, and the two
726    // coverage-based policies have nothing to reason about — they must defer to the
727    // insert convention rather than strip the format the typed text would have
728    // inherited. Only `PreserveNothing`, which is an explicit request for unformatted
729    // text, still applies.
730    let destroys_formatting = byte_end > byte_start;
731    let override_format: Option<Option<CharacterFormat>> = match policy {
732        ReplaceFormatPolicy::InheritPreceding => None,
733        ReplaceFormatPolicy::PreserveNothing => Some(None),
734        ReplaceFormatPolicy::PreserveIfFullyCovered => {
735            covering_format(runs, byte_start, byte_end).map(Some)
736        }
737        ReplaceFormatPolicy::KeepDominantRun if destroys_formatting => {
738            Some(dominant_format(runs, byte_start, byte_end))
739        }
740        ReplaceFormatPolicy::KeepDominantRun => None,
741    };
742
743    // The historical composition. This IS `InheritPreceding`, byte for byte.
744    shift_runs_for_delete(runs, byte_start, byte_end);
745    shift_runs_for_insert(runs, byte_start, replacement_bytes);
746
747    // Every other policy is a targeted re-splice of exactly the replacement's span.
748    if let Some(format) = override_format
749        && replacement_bytes > 0
750    {
751        let span = byte_start..byte_start + replacement_bytes;
752        let replacement = match format {
753            Some(format) => vec![FormatRun {
754                byte_start: span.start,
755                byte_end: span.end,
756                format,
757            }],
758            None => Vec::new(),
759        };
760        try_splice_range(runs, span, replacement)?;
761    }
762    Ok(())
763}
764
765/// The format of the single run covering **all** of `[start..end)`, if one does.
766///
767/// An empty range is covered by nothing: a pure insertion has no formatting of its own
768/// to preserve, so every policy falls back to inheritance there rather than silently
769/// formatting typed text from a run it merely sits next to.
770fn covering_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
771    if end <= start {
772        return None;
773    }
774    runs.iter()
775        .find(|r| r.byte_start <= start && r.byte_end >= end)
776        .map(|r| r.format.clone())
777}
778
779/// The format covering the most bytes of `[start..end)`, or `None` if unformatted text
780/// covers more than any single run.
781///
782/// Gaps count as a candidate, so renaming inside a mostly-plain range stays plain. Ties
783/// go to the formatted run: a tie means the formatting covered at least as much of the
784/// range as its absence did, and dropping it is the destructive outcome.
785fn dominant_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
786    if end <= start {
787        return None;
788    }
789    let span = u64::from(end - start);
790    let mut covered = 0u64;
791    let mut best: Option<(u64, &FormatRun)> = None;
792
793    for r in runs {
794        let lo = r.byte_start.max(start);
795        let hi = r.byte_end.min(end);
796        if hi <= lo {
797            continue;
798        }
799        let overlap = u64::from(hi - lo);
800        covered += overlap;
801        // `>` keeps the EARLIEST run on a tie between two runs, so the result does not
802        // depend on iteration order beyond the list's own sortedness.
803        if best.is_none_or(|(best_overlap, _)| overlap > best_overlap) {
804            best = Some((overlap, r));
805        }
806    }
807
808    let plain = span - covered;
809    match best {
810        Some((overlap, run)) if overlap >= plain => Some(run.format.clone()),
811        _ => None,
812    }
813}
814
815/// Apply an "insert" shift to a block's image anchors. Anchors at or
816/// past the offset move forward by `inserted_bytes`.
817/// Apply an "insert" mutation to a block's footnote references — the rule
818/// [`shift_images_for_insert`] applies, for the same reason.
819pub fn shift_footnote_refs_for_insert(
820    notes: &mut [FootnoteRefAnchor],
821    byte_offset: u32,
822    inserted_bytes: u32,
823) {
824    if inserted_bytes == 0 {
825        return;
826    }
827    for note in notes.iter_mut() {
828        if note.byte_offset >= byte_offset {
829            note.byte_offset += inserted_bytes;
830        }
831    }
832}
833
834pub fn shift_images_for_insert(images: &mut [ImageAnchor], byte_offset: u32, inserted_bytes: u32) {
835    if inserted_bytes == 0 {
836        return;
837    }
838    for img in images.iter_mut() {
839        if img.byte_offset >= byte_offset {
840            img.byte_offset += inserted_bytes;
841        }
842    }
843}
844
845/// Apply a "delete" mutation to a block's image anchors. Anchors whose
846/// `byte_offset` falls inside `[byte_start..byte_end)` are removed;
847/// anchors at or past `byte_end` shift back by the deleted length.
848/// Returns the number of anchors removed.
849pub fn shift_images_for_delete(
850    images: &mut Vec<ImageAnchor>,
851    byte_start: u32,
852    byte_end: u32,
853) -> usize {
854    if byte_end <= byte_start {
855        return 0;
856    }
857    let before = images.len();
858    images.retain(|i| !(i.byte_offset >= byte_start && i.byte_offset < byte_end));
859    let removed = before - images.len();
860    let delta = (byte_end - byte_start) as i32;
861    shift_images_after(images, byte_end, -delta);
862    removed
863}
864
865/// Apply a "delete" mutation to a block's footnote references: the rule
866/// [`shift_images_for_delete`] applies, for the same reason, since a reference
867/// occupies one `U+FFFC` exactly as an image does. References inside
868/// `[byte_start..byte_end)` are removed with the text that held them;
869/// references at or past `byte_end` move back by the deleted length.
870/// Returns the number of references removed.
871///
872/// Every edit that moves a block's images has to move its references too. The
873/// editing use cases used to move only the images, so a reference kept the
874/// byte offset it was loaded with: typing in front of it left it pointing into
875/// the word, a paragraph break in front of it left it past the end of its
876/// block (and every export that sliced the block there panicked), and deleting
877/// the sentence around it left it behind, dangling past the text.
878pub fn shift_footnote_refs_for_delete(
879    notes: &mut Vec<FootnoteRefAnchor>,
880    byte_start: u32,
881    byte_end: u32,
882) -> usize {
883    if byte_end <= byte_start {
884        return 0;
885    }
886    let before = notes.len();
887    notes.retain(|n| !(n.byte_offset >= byte_start && n.byte_offset < byte_end));
888    let removed = before - notes.len();
889    let delta = byte_end - byte_start;
890    for note in notes.iter_mut() {
891        if note.byte_offset >= byte_end {
892            note.byte_offset -= delta;
893        }
894    }
895    removed
896}
897
898/// Translate a logical character offset (counting text characters AND
899/// image positions interleaved by their `byte_offset`) into a UTF-8
900/// byte offset within `plain_text`. Used by writer use cases to map a
901/// document-space char position to the byte position where text edits
902/// should land in `block.plain_text`.
903///
904/// Each image already occupies exactly one character of `plain_text`: the
905/// `U+FFFC` OBJECT REPLACEMENT CHARACTER that `insert_image` mirrors into the
906/// rope, which [`ImageAnchor::byte_offset`] points at. So a logical offset *is*
907/// a character offset and this is a plain char→byte mapping.
908///
909/// `images` is retained in the signature — and deliberately unused — because
910/// getting this wrong is silent and expensive, and callers pass it naturally.
911/// The previous implementation walked the anchor list *in addition to*
912/// `char_indices()`, so every image advanced the logical counter twice. That
913/// dates from the pre-rope model, where an anchor genuinely contributed no
914/// bytes; once the sentinel went into the rope the two representations started
915/// double-counting. The visible effects: selecting across an image returned the
916/// wrong text (an extra sentinel, a missing character), and deleting a range
917/// containing one removed too little.
918pub fn logical_offset_to_byte(plain_text: &str, _images: &[ImageAnchor], char_offset: i64) -> u32 {
919    if char_offset <= 0 {
920        return 0;
921    }
922    plain_text
923        .char_indices()
924        .nth(char_offset as usize)
925        .map(|(b, _)| b as u32)
926        .unwrap_or(plain_text.len() as u32)
927}
928
929/// Split a block's format runs at `byte_offset`. The returned right-hand
930/// vector has its run offsets re-based so they start at byte 0 of the
931/// new (right) block. Straddling runs are split with their `format`
932/// cloned to both halves.
933pub fn split_runs_at(runs: &[FormatRun], byte_offset: u32) -> (Vec<FormatRun>, Vec<FormatRun>) {
934    let mut left = Vec::new();
935    let mut right = Vec::new();
936    for run in runs {
937        if run.byte_end <= byte_offset {
938            left.push(run.clone());
939        } else if run.byte_start >= byte_offset {
940            right.push(FormatRun {
941                byte_start: run.byte_start - byte_offset,
942                byte_end: run.byte_end - byte_offset,
943                format: run.format.clone(),
944            });
945        } else {
946            left.push(FormatRun {
947                byte_start: run.byte_start,
948                byte_end: byte_offset,
949                format: run.format.clone(),
950            });
951            right.push(FormatRun {
952                byte_start: 0,
953                byte_end: run.byte_end - byte_offset,
954                format: run.format.clone(),
955            });
956        }
957    }
958    (left, right)
959}
960
961/// Split block image anchors at `byte_offset`. Anchors at exactly
962/// `byte_offset` go to the right half (rebased to offset 0).
963/// Split footnote references at `byte_offset`, rebasing the right-hand side to
964/// zero — the exact rule [`split_images_at`] applies, because a reference
965/// occupies a block the same way an image does.
966pub fn split_footnote_refs_at(
967    notes: &[FootnoteRefAnchor],
968    byte_offset: u32,
969) -> (Vec<FootnoteRefAnchor>, Vec<FootnoteRefAnchor>) {
970    let mut left = Vec::new();
971    let mut right = Vec::new();
972    for note in notes {
973        if note.byte_offset < byte_offset {
974            left.push(note.clone());
975        } else {
976            let mut new = note.clone();
977            new.byte_offset -= byte_offset;
978            right.push(new);
979        }
980    }
981    (left, right)
982}
983
984pub fn split_images_at(
985    images: &[ImageAnchor],
986    byte_offset: u32,
987) -> (Vec<ImageAnchor>, Vec<ImageAnchor>) {
988    let mut left = Vec::new();
989    let mut right = Vec::new();
990    for img in images {
991        if img.byte_offset < byte_offset {
992            left.push(img.clone());
993        } else {
994            let mut new = img.clone();
995            new.byte_offset -= byte_offset;
996            right.push(new);
997        }
998    }
999    (left, right)
1000}
1001
1002// ─────────────────────────────────────────────────────────────────────
1003// View synthesis: build a Vec<InlineSegment> from format_runs + images.
1004// ─────────────────────────────────────────────────────────────────────
1005
1006/// Copy the `fmt_*` fields of an `InlineSegment` into a `CharacterFormat`.
1007pub fn character_format_from_segment(seg: &InlineSegment) -> CharacterFormat {
1008    CharacterFormat {
1009        font_family: seg.fmt_font_family.clone(),
1010        font_point_size: seg.fmt_font_point_size,
1011        font_weight: seg.fmt_font_weight,
1012        font_bold: seg.fmt_font_bold,
1013        font_italic: seg.fmt_font_italic,
1014        font_underline: seg.fmt_font_underline,
1015        font_overline: seg.fmt_font_overline,
1016        font_strikeout: seg.fmt_font_strikeout,
1017        letter_spacing: seg.fmt_letter_spacing,
1018        word_spacing: seg.fmt_word_spacing,
1019        anchor_href: seg.fmt_anchor_href.clone(),
1020        anchor_names: seg.fmt_anchor_names.clone(),
1021        is_anchor: seg.fmt_is_anchor,
1022        tooltip: seg.fmt_tooltip.clone(),
1023        underline_style: seg.fmt_underline_style.clone(),
1024        vertical_alignment: seg.fmt_vertical_alignment.clone(),
1025    }
1026}
1027
1028/// Apply a `CharacterFormat` onto an `InlineSegment`'s fmt_* fields.
1029pub fn apply_character_format_to_segment(seg: &mut InlineSegment, fmt: &CharacterFormat) {
1030    seg.fmt_font_family = fmt.font_family.clone();
1031    seg.fmt_font_point_size = fmt.font_point_size;
1032    seg.fmt_font_weight = fmt.font_weight;
1033    seg.fmt_font_bold = fmt.font_bold;
1034    seg.fmt_font_italic = fmt.font_italic;
1035    seg.fmt_font_underline = fmt.font_underline;
1036    seg.fmt_font_overline = fmt.font_overline;
1037    seg.fmt_font_strikeout = fmt.font_strikeout;
1038    seg.fmt_letter_spacing = fmt.letter_spacing;
1039    seg.fmt_word_spacing = fmt.word_spacing;
1040    seg.fmt_anchor_href = fmt.anchor_href.clone();
1041    seg.fmt_anchor_names = fmt.anchor_names.clone();
1042    seg.fmt_is_anchor = fmt.is_anchor;
1043    seg.fmt_tooltip = fmt.tooltip.clone();
1044    seg.fmt_underline_style = fmt.underline_style.clone();
1045    seg.fmt_vertical_alignment = fmt.vertical_alignment.clone();
1046}
1047
1048/// One ordered piece of a block's inline content: a run of text, or an image.
1049///
1050/// Produced by [`merge_runs_and_anchors`] and mapped by each caller into its own
1051/// output type.
1052#[derive(Debug, Clone, PartialEq)]
1053pub enum InlinePiece<'a> {
1054    /// Byte range `[start, end)` of the block's `plain_text`. `format` is
1055    /// `None` for bytes no format run covers.
1056    Text {
1057        start: u32,
1058        end: u32,
1059        format: Option<&'a CharacterFormat>,
1060    },
1061    /// An image anchored at this position. Contributes one logical character
1062    /// and zero bytes.
1063    Image(&'a ImageAnchor),
1064    /// A footnote reference anchored at this position. Contributes one logical
1065    /// character and zero bytes, exactly as an image does.
1066    FootnoteRef(&'a FootnoteRefAnchor),
1067}
1068
1069/// Interleave a block's format runs and image anchors into one ordered stream.
1070///
1071/// A block stores three parallel things — the text bytes, a list of formatted
1072/// byte ranges, and a list of image anchors keyed by byte offset — and every
1073/// reader has to weave them back into document order. That weave is fiddly in
1074/// exactly one place: an image anchored *inside* a formatted run has to split
1075/// the run, emitting the text before it, then the image, then the rest of the
1076/// run with the same format.
1077///
1078/// This function exists because that weave was previously written out twice, by
1079/// hand, in two crates, and the two copies disagreed. The version behind
1080/// `inline_segments_view` only checked `img.byte_offset < run.byte_start`, so an
1081/// image inside a run was skipped by the run loop entirely and swept up by the
1082/// trailing loop — landing **after every run in the block**. Insert a picture
1083/// into the middle of a bold sentence and every exporter, and the fragment/copy
1084/// path, moved it to the end of the paragraph.
1085///
1086/// Callers map the returned pieces to their own types; nobody re-derives the
1087/// ordering.
1088pub fn merge_runs_and_anchors<'a>(
1089    plain_text: &str,
1090    runs: &'a [FormatRun],
1091    anchors: &[BlockAnchor<'a>],
1092) -> Vec<InlinePiece<'a>> {
1093    let text_len = plain_text.len() as u32;
1094    let mut out: Vec<InlinePiece<'a>> = Vec::new();
1095    let mut img_iter = anchors.iter().peekable();
1096    // Highest byte offset already emitted. Never moves backwards.
1097    let mut cursor: u32 = 0;
1098
1099    /// Bytes an anchor occupies in `plain_text`.
1100    ///
1101    /// `insert_image` mirrors a `U+FFFC` OBJECT REPLACEMENT CHARACTER into the
1102    /// rope at the anchor's `byte_offset`, so an image's own character sits in
1103    /// the text and text resuming after the image must step over it. Emitting
1104    /// both the image piece *and* the sentinel yields the image twice — which
1105    /// is what made a selection across an image read back with a doubled
1106    /// sentinel and a missing following character. A footnote reference is
1107    /// mirrored the same way and steps over the same three bytes.
1108    ///
1109    /// Checked rather than assumed: `U+FFFC` also marks table anchors, and not
1110    /// every writer of an `ImageAnchor` mirrors one (the test harness writes
1111    /// anchors directly). An anchor without a sentinel is still handled, it
1112    /// simply consumes no bytes.
1113    fn sentinel_len(plain_text: &str, byte_offset: u32) -> u32 {
1114        let at = byte_offset as usize;
1115        if plain_text.len() >= at + 3 && plain_text.as_bytes()[at..at + 3] == [0xEF, 0xBF, 0xBC] {
1116            3
1117        } else {
1118            0
1119        }
1120    }
1121
1122    let push_text = |out: &mut Vec<InlinePiece<'a>>,
1123                     start: u32,
1124                     end: u32,
1125                     format: Option<&'a CharacterFormat>| {
1126        if start < end {
1127            out.push(InlinePiece::Text { start, end, format });
1128        }
1129    };
1130
1131    /// The piece an anchor contributes, whichever kind it is.
1132    fn piece<'a>(anchor: &BlockAnchor<'a>) -> InlinePiece<'a> {
1133        match *anchor {
1134            BlockAnchor::Image(i) => InlinePiece::Image(i),
1135            BlockAnchor::FootnoteRef(f) => InlinePiece::FootnoteRef(f),
1136        }
1137    }
1138
1139    for run in runs {
1140        // Anchors strictly before this run: unformatted gap text, then the anchor.
1141        while let Some(anchor) = img_iter.peek() {
1142            let at = anchor.byte_offset();
1143            if at >= run.byte_start {
1144                break;
1145            }
1146            push_text(&mut out, cursor, at, None);
1147            out.push(piece(anchor));
1148            cursor = cursor.max(at + sentinel_len(plain_text, at));
1149            img_iter.next();
1150        }
1151
1152        // Unformatted gap between the last emission and the run's start.
1153        push_text(&mut out, cursor, run.byte_start, None);
1154        cursor = cursor.max(run.byte_start);
1155
1156        // Anchors inside the run split it, keeping the run's format on both
1157        // sides. `<=` so an anchor sitting exactly on the run's end boundary is
1158        // consumed here rather than deferred — deferring it is what produced
1159        // the out-of-order emission described above.
1160        while let Some(anchor) = img_iter.peek() {
1161            let at = anchor.byte_offset();
1162            if at > run.byte_end {
1163                break;
1164            }
1165            push_text(&mut out, cursor, at, Some(&run.format));
1166            out.push(piece(anchor));
1167            cursor = cursor.max(at + sentinel_len(plain_text, at));
1168            img_iter.next();
1169        }
1170
1171        push_text(&mut out, cursor, run.byte_end, Some(&run.format));
1172        cursor = cursor.max(run.byte_end);
1173    }
1174
1175    // Anchors past the last run.
1176    for anchor in img_iter {
1177        let at = anchor.byte_offset();
1178        push_text(&mut out, cursor, at, None);
1179        out.push(piece(anchor));
1180        cursor = cursor.max(at + sentinel_len(plain_text, at));
1181    }
1182
1183    push_text(&mut out, cursor, text_len, None);
1184
1185    out
1186}
1187
1188/// [`InlinePiece`], but positioned in the document's own **addressable character space**
1189/// rather than as byte offsets local to the block's `plain_text`.
1190///
1191/// `InlinePiece::Text { start, end, .. }` is a byte range good for slicing `plain_text` and
1192/// nothing else: it carries no notion of where in the *document* that range sits. Every
1193/// offset the rest of this crate deals out — `TextDocument::to_addressable_text()`, `find_all`
1194/// match positions, a block's own `document_position` — lives in one **character** space, and
1195/// a caller that reconstructs a document position by summing `InlinePiece` text lengths drifts
1196/// the moment a block holds a multi-byte character before the point in question, or an inline
1197/// image/footnote reference at all — their `U+FFFC` sentinel is three bytes but one char (see
1198/// `sentinel_len` on [`merge_runs_and_anchors`]). That is the same "offset from one space,
1199/// string from another" bug class the public API's `TextDocument::to_addressable_text()`
1200/// exists to close for whole-document offsets (see its doc comment), one level down, inside
1201/// a single block.
1202///
1203/// Built by [`addressable_inline_pieces`] (pure — block-local character space, `base_char_offset`
1204/// left at `0`) or [`crate::format_runs_query::addressable_inline_pieces_for_block`]
1205/// (store-aware — adds the block's own `document_position` so `start`/`end` land in the
1206/// *document's* space). Every downstream consumer that needs a piece boundary in that space —
1207/// a comment's stored quote, a DOCX/ODT comment marker split at an arbitrary character — reads
1208/// `start`/`end` straight off this type instead of re-deriving them by hand.
1209#[derive(Debug, Clone, PartialEq)]
1210pub struct AddressableInlinePiece {
1211    /// `[start, end)` in the addressable character space. `end - start` is always `1` for
1212    /// [`InlineContent::Image`] and [`InlineContent::FootnoteRef`] — the sentinel counts as
1213    /// exactly one character, matching how the document itself counts it — and equals the
1214    /// piece's own text's `chars().count()` for [`InlineContent::Text`].
1215    pub start: u32,
1216    pub end: u32,
1217    pub content: InlineContent,
1218    pub format: CharacterFormat,
1219}
1220
1221/// Build a block's [`AddressableInlinePiece`]s from its `plain_text`, format runs, and
1222/// anchors, offset by `base_char_offset` — the character position this block's own first
1223/// piece should start at.
1224///
1225/// Layered on [`merge_runs_and_anchors`] rather than duplicating its weave: the only thing
1226/// added here is the byte→char conversion (`plain_text[start..end].chars().count()` is the
1227/// only correct way to size a UTF-8 slice in the character space every other offset in this
1228/// crate uses — NOT `end - start`, which is a byte count) and a running `base_char_offset`
1229/// accumulator. Pass `0` to get offsets relative to this block alone, which is what this
1230/// module's own tests do; [`crate::format_runs_query::addressable_inline_pieces_for_block`]
1231/// passes the block's own `document_position` instead, to land in document-wide space.
1232pub fn addressable_inline_pieces(
1233    plain_text: &str,
1234    runs: &[FormatRun],
1235    anchors: &[BlockAnchor<'_>],
1236    base_char_offset: u32,
1237) -> Vec<AddressableInlinePiece> {
1238    let pieces = merge_runs_and_anchors(plain_text, runs, anchors);
1239    let mut out = Vec::with_capacity(pieces.len());
1240    let mut cursor = base_char_offset;
1241    for piece in pieces {
1242        match piece {
1243            InlinePiece::Text { start, end, format } => {
1244                let text = &plain_text[start as usize..end as usize];
1245                let len = text.chars().count() as u32;
1246                out.push(AddressableInlinePiece {
1247                    start: cursor,
1248                    end: cursor + len,
1249                    content: InlineContent::Text(text.to_string()),
1250                    format: format.cloned().unwrap_or_default(),
1251                });
1252                cursor += len;
1253            }
1254            InlinePiece::Image(anchor) => {
1255                out.push(AddressableInlinePiece {
1256                    start: cursor,
1257                    end: cursor + 1,
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                    format: anchor.format.clone(),
1266                });
1267                cursor += 1;
1268            }
1269            InlinePiece::FootnoteRef(anchor) => {
1270                out.push(AddressableInlinePiece {
1271                    start: cursor,
1272                    end: cursor + 1,
1273                    content: InlineContent::FootnoteRef {
1274                        label: anchor.label.clone(),
1275                    },
1276                    format: anchor.format.clone(),
1277                });
1278                cursor += 1;
1279            }
1280        }
1281    }
1282    out
1283}
1284
1285/// Synthesize a `Vec<InlineSegment>` view of a block from its
1286/// `plain_text`, `format_runs`, and `block_images`. Returns segments
1287/// in document order: a Text segment per format run (with a fallback
1288/// default-format segment for any uncovered bytes), and an Image
1289/// segment per anchor at its byte offset.
1290///
1291/// The canonical reader-side accessor for per-segment data — there is
1292/// no persistent inline-element table; this view is computed fresh
1293/// each call.
1294pub fn inline_segments_view(
1295    plain_text: &str,
1296    runs: &[FormatRun],
1297    images: &[ImageAnchor],
1298    footnote_refs: &[FootnoteRefAnchor],
1299) -> Vec<InlineSegment> {
1300    let bytes = plain_text.as_bytes();
1301    let default_format = CharacterFormat::default();
1302
1303    merge_runs_and_anchors(plain_text, runs, &block_anchors(images, footnote_refs))
1304        .into_iter()
1305        .map(|piece| match piece {
1306            InlinePiece::Text { start, end, format } => {
1307                let slice = &bytes[start as usize..end as usize];
1308                let text = std::str::from_utf8(slice)
1309                    .expect("block plain_text must be valid UTF-8")
1310                    .to_string();
1311                let mut seg = InlineSegment {
1312                    content: InlineContent::Text(text),
1313                    ..Default::default()
1314                };
1315                apply_character_format_to_segment(&mut seg, format.unwrap_or(&default_format));
1316                seg
1317            }
1318            InlinePiece::Image(anchor) => {
1319                let mut seg = InlineSegment {
1320                    content: InlineContent::Image {
1321                        name: anchor.name.clone(),
1322                        alt: anchor.alt.clone(),
1323                        width: anchor.width,
1324                        height: anchor.height,
1325                        quality: anchor.quality,
1326                    },
1327                    ..Default::default()
1328                };
1329                apply_character_format_to_segment(&mut seg, &anchor.format);
1330                seg
1331            }
1332            InlinePiece::FootnoteRef(anchor) => {
1333                let mut seg = InlineSegment {
1334                    content: InlineContent::FootnoteRef {
1335                        label: anchor.label.clone(),
1336                    },
1337                    ..Default::default()
1338                };
1339                apply_character_format_to_segment(&mut seg, &anchor.format);
1340                seg
1341            }
1342        })
1343        .collect()
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348    use super::*;
1349
1350    fn run(s: u32, e: u32, bold: bool) -> FormatRun {
1351        FormatRun {
1352            byte_start: s,
1353            byte_end: e,
1354            format: CharacterFormat {
1355                font_bold: Some(bold),
1356                ..Default::default()
1357            },
1358        }
1359    }
1360
1361    #[test]
1362    fn empty_runs_are_well_formed() {
1363        debug_assert_well_formed(&[], 0);
1364        debug_assert_well_formed(&[], 100);
1365    }
1366
1367    // ── shift_runs_for_typed_insert ───────────────────────────────────────
1368
1369    fn link(s: u32, e: u32, bold: Option<bool>) -> FormatRun {
1370        FormatRun {
1371            byte_start: s,
1372            byte_end: e,
1373            format: CharacterFormat {
1374                font_bold: bold,
1375                anchor_href: Some("https://example.org".into()),
1376                anchor_names: vec!["target".into()],
1377                is_anchor: Some(true),
1378                tooltip: Some("Example".into()),
1379                ..Default::default()
1380            },
1381        }
1382    }
1383
1384    #[test]
1385    fn typed_at_the_start_of_a_block_extends_its_first_run() {
1386        let mut runs = vec![run(0, 4, true), run(4, 8, false)];
1387        shift_runs_for_typed_insert(&mut runs, 0, 2);
1388        assert_eq!(runs, vec![run(0, 6, true), run(6, 10, false)]);
1389    }
1390
1391    #[test]
1392    fn typed_before_a_link_at_the_start_of_a_block_is_not_part_of_the_link() {
1393        let mut runs = vec![link(0, 4, Some(true)), run(4, 8, false)];
1394        shift_runs_for_typed_insert(&mut runs, 0, 2);
1395        assert_eq!(
1396            runs,
1397            vec![run(0, 2, true), link(2, 6, Some(true)), run(6, 10, false)],
1398            "the typed text keeps the bold and leaves the link out"
1399        );
1400        debug_assert_well_formed(&runs, 10);
1401
1402        let mut runs = vec![link(0, 4, None)];
1403        shift_runs_for_typed_insert(&mut runs, 0, 2);
1404        assert_eq!(runs, vec![link(2, 6, None)], "a bare link leaves it plain");
1405        debug_assert_well_formed(&runs, 6);
1406    }
1407
1408    // ── merge_runs_and_anchors ────────────────────────────────────────────
1409
1410    fn anchor(at: u32, name: &str) -> ImageAnchor {
1411        ImageAnchor {
1412            byte_offset: at,
1413            name: name.into(),
1414            alt: String::new(),
1415            width: 10,
1416            height: 10,
1417            quality: 100,
1418            format: CharacterFormat::default(),
1419        }
1420    }
1421
1422    fn fn_anchor(at: u32, label: &str) -> FootnoteRefAnchor {
1423        FootnoteRefAnchor {
1424            byte_offset: at,
1425            label: label.into(),
1426            format: CharacterFormat::default(),
1427        }
1428    }
1429
1430    /// Render a merge as a compact string so ordering assertions read clearly:
1431    /// `"hello"` for unformatted text, `"*bold*"` for formatted, `[name]` for
1432    /// an image, `^label^` for a footnote reference.
1433    fn shape(text: &str, runs: &[FormatRun], images: &[ImageAnchor]) -> String {
1434        shape_with(text, runs, images, &[])
1435    }
1436
1437    fn shape_with(
1438        text: &str,
1439        runs: &[FormatRun],
1440        images: &[ImageAnchor],
1441        notes: &[FootnoteRefAnchor],
1442    ) -> String {
1443        merge_runs_and_anchors(text, runs, &block_anchors(images, notes))
1444            .into_iter()
1445            .map(|p| match p {
1446                InlinePiece::Text { start, end, format } => {
1447                    let s = &text[start as usize..end as usize];
1448                    if format.is_some() {
1449                        format!("*{s}*")
1450                    } else {
1451                        s.to_string()
1452                    }
1453                }
1454                InlinePiece::Image(a) => format!("[{}]", a.name),
1455                InlinePiece::FootnoteRef(a) => format!("^{}^", a.label),
1456            })
1457            .collect::<Vec<_>>()
1458            .join("|")
1459    }
1460
1461    /// A footnote reference weaves exactly as an image does — the whole reason
1462    /// the two share one function instead of getting a second copy of it.
1463    #[test]
1464    fn a_footnote_reference_inside_a_run_splits_it() {
1465        let text = "abcdef";
1466        let runs = [run(0, 6, true)];
1467        assert_eq!(
1468            shape_with(text, &runs, &[], &[fn_anchor(3, "n1")]),
1469            "*abc*|^n1^|*def*"
1470        );
1471    }
1472
1473    /// Images and references are stored in separate lists but occupy one
1474    /// stream. Walking the two lists in sequence rather than merging them by
1475    /// offset would emit every image before every note regardless of where they
1476    /// actually sit — the ordering bug this weave exists to prevent, in a new
1477    /// disguise.
1478    #[test]
1479    fn images_and_references_interleave_by_position() {
1480        let text = "abcdefgh";
1481        assert_eq!(
1482            shape_with(
1483                text,
1484                &[],
1485                &[anchor(6, "img")],
1486                &[fn_anchor(2, "early"), fn_anchor(7, "late")]
1487            ),
1488            "ab|^early^|cdef|[img]|g|^late^|h"
1489        );
1490    }
1491
1492    /// **The regression.** An image anchored inside a formatted run used to be
1493    /// skipped by the run loop (which only tested `offset < run.byte_start`)
1494    /// and swept up by the trailing loop, landing after every run in the block.
1495    /// Put a picture mid-sentence in bold text and every exporter moved it to
1496    /// the end of the paragraph.
1497    #[test]
1498    fn an_image_inside_a_run_splits_it_instead_of_jumping_to_the_end() {
1499        let text = "abcdef";
1500        let runs = [run(0, 6, true)];
1501        let images = [anchor(3, "img")];
1502        assert_eq!(shape(text, &runs, &images), "*abc*|[img]|*def*");
1503    }
1504
1505    #[test]
1506    fn an_image_on_a_run_start_boundary_stays_in_place() {
1507        let text = "abcdef";
1508        let runs = [run(3, 6, true)];
1509        assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "abc|[i]|*def*");
1510    }
1511
1512    /// The `<=` in the in-run loop: an image exactly on a run's end boundary is
1513    /// consumed with that run rather than deferred to the trailing sweep.
1514    #[test]
1515    fn an_image_on_a_run_end_boundary_stays_in_place() {
1516        let text = "abcdef";
1517        let runs = [run(0, 3, true)];
1518        assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "*abc*|[i]|def");
1519    }
1520
1521    #[test]
1522    fn an_image_between_two_runs_lands_between_them() {
1523        let text = "abcdef";
1524        let runs = [run(0, 3, true), run(3, 6, false)];
1525        let out = shape(text, &runs, &[anchor(3, "i")]);
1526        assert_eq!(out, "*abc*|[i]|*def*");
1527    }
1528
1529    #[test]
1530    fn several_images_inside_one_run_keep_their_order() {
1531        let text = "abcdefgh";
1532        let runs = [run(0, 8, true)];
1533        let images = [anchor(2, "a"), anchor(5, "b")];
1534        assert_eq!(shape(text, &runs, &images), "*ab*|[a]|*cde*|[b]|*fgh*");
1535    }
1536
1537    #[test]
1538    fn two_images_at_the_same_offset_both_survive_in_order() {
1539        let text = "abcd";
1540        let runs = [run(0, 4, true)];
1541        let images = [anchor(2, "a"), anchor(2, "b")];
1542        assert_eq!(shape(text, &runs, &images), "*ab*|[a]|[b]|*cd*");
1543    }
1544
1545    #[test]
1546    fn images_with_no_runs_at_all_are_ordered_with_their_gaps() {
1547        let text = "abcdef";
1548        let images = [anchor(0, "a"), anchor(3, "b"), anchor(6, "c")];
1549        assert_eq!(shape(text, &[], &images), "[a]|abc|[b]|def|[c]");
1550    }
1551
1552    #[test]
1553    fn text_uncovered_by_any_run_stays_unformatted() {
1554        let text = "abcdef";
1555        let runs = [run(2, 4, true)];
1556        assert_eq!(shape(text, &runs, &[]), "ab|*cd*|ef");
1557    }
1558
1559    #[test]
1560    fn a_block_with_neither_runs_nor_images_is_one_plain_piece() {
1561        assert_eq!(shape("abc", &[], &[]), "abc");
1562        assert_eq!(shape("", &[], &[]), "");
1563    }
1564
1565    /// Whatever the arrangement, the merge must reproduce the block's bytes
1566    /// exactly once, in order — never dropping or duplicating a slice. The
1567    /// old implementation could regress its cursor and re-emit text twice.
1568    #[test]
1569    fn every_byte_is_emitted_exactly_once_and_in_order() {
1570        let text = "abcdefghij";
1571        let arrangements: [(&[FormatRun], &[ImageAnchor]); 6] = [
1572            (&[], &[]),
1573            (&[run(0, 10, true)], &[anchor(5, "m")]),
1574            (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1575            (&[run(2, 5, true)], &[anchor(0, "a"), anchor(10, "z")]),
1576            (&[run(0, 3, true), run(7, 10, true)], &[anchor(3, "m")]),
1577            (
1578                &[run(1, 4, true), run(4, 9, false)],
1579                &[anchor(1, "a"), anchor(4, "b"), anchor(9, "c")],
1580            ),
1581        ];
1582        for (i, (runs, images)) in arrangements.iter().enumerate() {
1583            let pieces = merge_runs_and_anchors(text, runs, &block_anchors(images, &[]));
1584            let mut cursor = 0u32;
1585            let mut rebuilt = String::new();
1586            for piece in &pieces {
1587                if let InlinePiece::Text { start, end, .. } = piece {
1588                    assert_eq!(*start, cursor, "arrangement {i}: gap or overlap");
1589                    assert!(start < end, "arrangement {i}: empty piece emitted");
1590                    rebuilt.push_str(&text[*start as usize..*end as usize]);
1591                    cursor = *end;
1592                }
1593            }
1594            assert_eq!(cursor, text.len() as u32, "arrangement {i}: truncated");
1595            assert_eq!(rebuilt, text, "arrangement {i}");
1596            let img_count = pieces
1597                .iter()
1598                .filter(|p| matches!(p, InlinePiece::Image(_)))
1599                .count();
1600            assert_eq!(img_count, images.len(), "arrangement {i}: lost an image");
1601        }
1602    }
1603
1604    /// `inline_segments_view` is built on the merge, so it inherits the fix.
1605    #[test]
1606    fn inline_segments_view_places_a_mid_run_image_correctly() {
1607        let segs = inline_segments_view("abcdef", &[run(0, 6, true)], &[anchor(3, "img")], &[]);
1608        assert_eq!(segs.len(), 3);
1609        assert!(matches!(&segs[0].content, InlineContent::Text(t) if t == "abc"));
1610        assert!(matches!(&segs[1].content, InlineContent::Image { name, .. } if name == "img"));
1611        assert!(matches!(&segs[2].content, InlineContent::Text(t) if t == "def"));
1612        // The split keeps the run's formatting on both sides of the image.
1613        assert_eq!(segs[0].fmt_font_bold, Some(true));
1614        assert_eq!(segs[2].fmt_font_bold, Some(true));
1615    }
1616
1617    #[test]
1618    fn inline_segments_view_carries_alt_text_through() {
1619        let mut a = anchor(1, "img");
1620        a.alt = "a black cat".into();
1621        let segs = inline_segments_view("ab", &[], &[a], &[]);
1622        let alt = segs.iter().find_map(|s| match &s.content {
1623            InlineContent::Image { alt, .. } => Some(alt.clone()),
1624            _ => None,
1625        });
1626        assert_eq!(alt.as_deref(), Some("a black cat"));
1627    }
1628
1629    // ── addressable_inline_pieces ───────────────────────────────────────
1630
1631    /// Render an `addressable_inline_pieces` result as `(start, end, label)` triples, so a
1632    /// failing assertion shows the whole span list at once instead of one field at a time.
1633    fn pieces_shape(out: &[AddressableInlinePiece]) -> Vec<(u32, u32, String)> {
1634        out.iter()
1635            .map(|p| {
1636                let label = match &p.content {
1637                    InlineContent::Text(t) => t.clone(),
1638                    InlineContent::Image { name, .. } => format!("[{name}]"),
1639                    InlineContent::FootnoteRef { label } => format!("^{label}^"),
1640                    InlineContent::Empty => String::new(),
1641                };
1642                (p.start, p.end, label)
1643            })
1644            .collect()
1645    }
1646
1647    #[test]
1648    fn a_lone_text_piece_spans_its_char_length() {
1649        let out = addressable_inline_pieces("hello", &[], &[], 0);
1650        assert_eq!(pieces_shape(&out), vec![(0, 5, "hello".to_string())]);
1651    }
1652
1653    #[test]
1654    fn base_char_offset_shifts_every_piece_by_the_same_amount() {
1655        let out = addressable_inline_pieces("hello", &[], &[], 100);
1656        assert_eq!(pieces_shape(&out), vec![(100, 105, "hello".to_string())]);
1657    }
1658
1659    /// The regression this type exists to prevent: a multi-byte character before an anchor
1660    /// must not leak its extra BYTE into the anchor's CHAR position. "café" is 5 bytes (é is
1661    /// 2 bytes in UTF-8) but 4 chars — code that summed byte lengths instead of counting
1662    /// chars would place the image at char 5, one past where it actually sits, and every
1663    /// offset after it would carry the same one-character drift.
1664    #[test]
1665    fn a_multibyte_character_before_an_image_does_not_leak_its_extra_byte_into_the_char_position() {
1666        let text = "café";
1667        assert_eq!(text.len(), 5, "test assumes café is 5 bytes");
1668        assert_eq!(text.chars().count(), 4, "test assumes café is 4 chars");
1669        let images = [anchor(5, "pic")]; // byte_offset 5 == right after "café"'s 5 bytes
1670        let anchors = block_anchors(&images, &[]);
1671        let out = addressable_inline_pieces(text, &[], &anchors, 0);
1672        assert_eq!(
1673            pieces_shape(&out),
1674            vec![(0, 4, "café".to_string()), (4, 5, "[pic]".to_string())]
1675        );
1676    }
1677
1678    /// An image sitting inside a formatted run gets its own one-char span, and the text
1679    /// before/after it still lands at the right char offsets — the boundary this milestone's
1680    /// comment-export use case cares about most: "a comment boundary landing immediately
1681    /// after an inline image."
1682    #[test]
1683    fn an_image_mid_run_gets_a_one_char_span_and_the_trailing_text_resumes_right_after_it() {
1684        let text = "abcdef";
1685        let runs = [run(0, 6, true)];
1686        let images = [anchor(3, "img")];
1687        let anchors = block_anchors(&images, &[]);
1688        let out = addressable_inline_pieces(text, &runs, &anchors, 0);
1689        assert_eq!(
1690            pieces_shape(&out),
1691            vec![
1692                (0, 3, "abc".to_string()),
1693                (3, 4, "[img]".to_string()),
1694                (4, 7, "def".to_string()),
1695            ]
1696        );
1697    }
1698
1699    /// A footnote reference gets a one-char span exactly like an image — the boundary
1700    /// case "a comment boundary landing immediately after a footnote reference."
1701    #[test]
1702    fn a_footnote_reference_gets_a_one_char_span_too() {
1703        let text = "abcdef";
1704        let notes = [fn_anchor(3, "n1")];
1705        let anchors = block_anchors(&[], &notes);
1706        let out = addressable_inline_pieces(text, &[], &anchors, 0);
1707        assert_eq!(
1708            pieces_shape(&out),
1709            vec![
1710                (0, 3, "abc".to_string()),
1711                (3, 4, "^n1^".to_string()),
1712                (4, 7, "def".to_string()),
1713            ]
1714        );
1715    }
1716
1717    /// Whatever the arrangement of runs and anchors, the pieces must tile the block's char
1718    /// space with no gap, no overlap, and no dropped anchor — the char-space analogue of
1719    /// `every_byte_is_emitted_exactly_once_and_in_order` above.
1720    #[test]
1721    fn pieces_are_contiguous_in_char_space_with_no_gaps_or_overlaps() {
1722        let text = "abcdefghij";
1723        let arrangements: [(&[FormatRun], &[ImageAnchor]); 4] = [
1724            (&[], &[]),
1725            (&[run(0, 10, true)], &[anchor(5, "m")]),
1726            (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1727            (&[run(1, 4, true), run(4, 9, false)], &[anchor(9, "c")]),
1728        ];
1729        for (i, (runs, images)) in arrangements.iter().enumerate() {
1730            let anchors = block_anchors(images, &[]);
1731            let out = addressable_inline_pieces(text, runs, &anchors, 7);
1732            let mut cursor = 7u32;
1733            for piece in &out {
1734                assert_eq!(piece.start, cursor, "arrangement {i}: gap or overlap");
1735                assert!(piece.start < piece.end, "arrangement {i}: empty piece");
1736                cursor = piece.end;
1737            }
1738            // Each anchor is a logical character with no bytes of its own in `text`, so
1739            // it adds one char beyond `text`'s own count — same accounting `block_char_length`
1740            // uses for a real (sentinel-bearing) block, just without a sentinel to count here.
1741            assert_eq!(
1742                cursor,
1743                7 + text.chars().count() as u32 + images.len() as u32,
1744                "arrangement {i}: did not tile the whole block"
1745            );
1746        }
1747    }
1748
1749    #[test]
1750    fn coalesce_merges_adjacent_equal_runs() {
1751        let mut rs = vec![run(0, 5, true), run(5, 10, true), run(10, 15, false)];
1752        coalesce_in_place(&mut rs);
1753        assert_eq!(rs.len(), 2);
1754        assert_eq!(rs[0].byte_end, 10);
1755    }
1756
1757    #[test]
1758    fn coalesce_leaves_disjoint_runs_alone() {
1759        let mut rs = vec![run(0, 5, true), run(7, 10, true)];
1760        coalesce_in_place(&mut rs);
1761        assert_eq!(rs.len(), 2);
1762    }
1763
1764    #[test]
1765    fn splice_range_clips_straddling_runs() {
1766        let mut rs = vec![run(0, 20, true)];
1767        splice_range(&mut rs, 5..15, vec![run(5, 15, false)]);
1768        assert_eq!(rs.len(), 3);
1769        assert_eq!(rs[0].byte_end, 5);
1770        assert_eq!(rs[1].format.font_bold, Some(false));
1771        assert_eq!(rs[2].byte_start, 15);
1772    }
1773
1774    #[test]
1775    fn splice_range_empty_replacement_removes_inner_runs() {
1776        let mut rs = vec![run(0, 5, true), run(5, 10, false), run(10, 15, true)];
1777        splice_range(&mut rs, 5..10, vec![]);
1778        // 0..5 bold, then 10..15 bold — after coalesce these are NOT adjacent
1779        // (there's a gap from 5..10 in the run table, meaning "no format").
1780        assert_eq!(rs.len(), 2);
1781        assert_eq!(rs[0].byte_end, 5);
1782        assert_eq!(rs[1].byte_start, 10);
1783    }
1784
1785    #[test]
1786    fn shift_after_moves_downstream() {
1787        let mut rs = vec![run(0, 5, true), run(10, 15, false)];
1788        shift_after(&mut rs, 5, 3);
1789        assert_eq!(rs[0].byte_start, 0); // unchanged
1790        assert_eq!(rs[1].byte_start, 13);
1791        assert_eq!(rs[1].byte_end, 18);
1792    }
1793}
1794
1795/// The adversarial corpus for [`shift_runs_for_replace`].
1796///
1797/// Replace is the one edit that rewrites a writer's prose *in bulk*, so its formatting
1798/// behaviour has to be pinned rather than inherited by accident. Before this module
1799/// there were 11 replace tests in the repo and **not one** of them mentioned
1800/// `FormatRun`: the behaviour was emergent, undecided, and untested.
1801#[cfg(test)]
1802mod replace_policy_tests {
1803    use super::*;
1804
1805    fn fmt(tag: &str) -> CharacterFormat {
1806        CharacterFormat {
1807            font_bold: Some(tag == "B"),
1808            font_italic: Some(tag == "I"),
1809            ..Default::default()
1810        }
1811    }
1812    fn r(start: u32, end: u32, tag: &str) -> FormatRun {
1813        FormatRun {
1814            byte_start: start,
1815            byte_end: end,
1816            format: fmt(tag),
1817        }
1818    }
1819    /// Compact "0..5=B 8..12=I" rendering, so a failure shows the whole run list.
1820    fn show(runs: &[FormatRun]) -> String {
1821        if runs.is_empty() {
1822            return "[]".to_string();
1823        }
1824        runs.iter()
1825            .map(|x| {
1826                let tag = if x.format.font_bold == Some(true) {
1827                    "B"
1828                } else if x.format.font_italic == Some(true) {
1829                    "I"
1830                } else {
1831                    "p"
1832                };
1833                format!("{}..{}={tag}", x.byte_start, x.byte_end)
1834            })
1835            .collect::<Vec<_>>()
1836            .join(" ")
1837    }
1838    fn replace(
1839        runs: &[FormatRun],
1840        start: u32,
1841        end: u32,
1842        n: u32,
1843        policy: ReplaceFormatPolicy,
1844    ) -> Vec<FormatRun> {
1845        let mut runs = runs.to_vec();
1846        shift_runs_for_replace(&mut runs, start, end, n, policy).expect("valid replace");
1847        runs
1848    }
1849
1850    /// **The spec-conformance test.** `InheritPreceding` must be byte-for-byte what
1851    /// today's `shift_runs_for_delete` + `shift_runs_for_insert` produces — anything
1852    /// else silently rewrites the formatting of every replace that ever shipped.
1853    ///
1854    /// Differential, not hand-transcribed: it runs the historical primitives directly
1855    /// and compares, so it stays honest even if their behaviour is ever changed.
1856    #[test]
1857    fn inherit_preceding_matches_the_historical_delete_then_insert() {
1858        let corpus: Vec<(&str, Vec<FormatRun>, u32, u32, u32)> = vec![
1859            ("run ends exactly at start", vec![r(0, 5, "B")], 5, 10, 3),
1860            ("run begins exactly at start", vec![r(5, 8, "B")], 5, 10, 3),
1861            (
1862                "run begins at start, outlives end",
1863                vec![r(5, 20, "B")],
1864                5,
1865                10,
1866                3,
1867            ),
1868            (
1869                "run straddles the whole range",
1870                vec![r(0, 20, "B")],
1871                5,
1872                10,
1873                3,
1874            ),
1875            ("no run touches the start", vec![r(12, 20, "B")], 5, 10, 3),
1876            ("bold tail inside the range", vec![r(9, 13, "B")], 5, 13, 4),
1877            ("pure delete", vec![r(0, 20, "B")], 5, 10, 0),
1878            ("pure insert", vec![r(0, 20, "B")], 5, 5, 3),
1879            (
1880                "same format either side coalesces",
1881                vec![r(0, 5, "B"), r(10, 15, "B")],
1882                5,
1883                10,
1884                3,
1885            ),
1886            (
1887                "different formats either side",
1888                vec![r(0, 5, "B"), r(10, 15, "I")],
1889                5,
1890                10,
1891                3,
1892            ),
1893            ("empty run list", vec![], 5, 10, 3),
1894            ("the only run is consumed", vec![r(5, 10, "B")], 5, 10, 3),
1895            (
1896                "replacement longer than the range",
1897                vec![r(0, 5, "B")],
1898                5,
1899                10,
1900                20,
1901            ),
1902            (
1903                "three runs straddled",
1904                vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")],
1905                2,
1906                7,
1907                4,
1908            ),
1909            (
1910                "gap between two same-format runs is deleted",
1911                vec![r(0, 5, "B"), r(8, 13, "B")],
1912                5,
1913                8,
1914                0,
1915            ),
1916        ];
1917
1918        for (name, runs, start, end, n) in corpus {
1919            // The historical composition, run for real.
1920            let mut expected = runs.clone();
1921            shift_runs_for_delete(&mut expected, start, end);
1922            shift_runs_for_insert(&mut expected, start, n);
1923
1924            let got = replace(&runs, start, end, n, ReplaceFormatPolicy::InheritPreceding);
1925
1926            assert_eq!(
1927                show(&got),
1928                show(&expected),
1929                "InheritPreceding diverged from delete+insert for {name:?} \
1930                 (replace {start}..{end}, n={n})\n  before:   {}\n  historical: {}\n  got:        {}",
1931                show(&runs),
1932                show(&expected),
1933                show(&got),
1934            );
1935        }
1936    }
1937
1938    /// The motivating data loss: renaming a character whose name reads `Auré**lien**`.
1939    /// The default drops the bold — that is what shipped, and it is now visible and
1940    /// chosen rather than emergent. Every other policy is a way to not lose it.
1941    #[test]
1942    fn the_four_policies_diverge_on_a_partly_bold_name() {
1943        // "Auré" plain (bytes 0..5, é is two bytes), "lien" bold (5..9).
1944        let runs = vec![r(5, 9, "B")];
1945        let (start, end, n) = (0, 9, 9); // rename the whole name, same length
1946
1947        use ReplaceFormatPolicy::*;
1948        assert_eq!(
1949            show(&replace(&runs, start, end, n, InheritPreceding)),
1950            "[]",
1951            "the historical default destroys the bold — pinned, not endorsed"
1952        );
1953        assert_eq!(
1954            show(&replace(&runs, start, end, n, PreserveNothing)),
1955            "[]",
1956            "explicitly unformatted"
1957        );
1958        assert_eq!(
1959            show(&replace(&runs, start, end, n, PreserveIfFullyCovered)),
1960            "[]",
1961            "no SINGLE run covers 0..9 — it must fall back to inheritance, not guess"
1962        );
1963        // Bold covers 4 of the 9 bytes, plain covers 5 → plain dominates.
1964        assert_eq!(
1965            show(&replace(&runs, start, end, n, KeepDominantRun)),
1966            "[]",
1967            "plain covers more of the name than the bold does"
1968        );
1969
1970        // …but when the bold covers MOST of the name, KeepDominantRun keeps it.
1971        let mostly_bold = vec![r(1, 9, "B")];
1972        assert_eq!(
1973            show(&replace(&mostly_bold, 0, 9, 9, KeepDominantRun)),
1974            "0..9=B",
1975            "bold covers 8 of 9 bytes — the rename must keep it"
1976        );
1977    }
1978
1979    /// "Fully covered" means ONE run covers the range — not "the runs jointly span it".
1980    /// A gapless Italic+Bold union spanning the range exactly must NOT be treated as
1981    /// covered, or the replacement silently inherits whichever run was looked at first.
1982    #[test]
1983    fn fully_covered_means_a_single_run_not_a_gapless_union() {
1984        let two = vec![r(0, 3, "I"), r(3, 10, "B")];
1985        assert_eq!(
1986            show(&replace(
1987                &two,
1988                0,
1989                10,
1990                4,
1991                ReplaceFormatPolicy::PreserveIfFullyCovered
1992            )),
1993            "[]",
1994            "two different-format runs jointly spanning the range are not 'covered'; \
1995             with no run preceding the start, the fallback is unformatted"
1996        );
1997
1998        // One run that really does cover it, and begins exactly at the start — the case
1999        // InheritPreceding cannot see (a run at `start` never inherits).
2000        let one = vec![r(5, 20, "B")];
2001        assert_eq!(
2002            show(&replace(
2003                &one,
2004                5,
2005                10,
2006                3,
2007                ReplaceFormatPolicy::PreserveIfFullyCovered
2008            )),
2009            "5..18=B",
2010            "a single covering run keeps its format across the rename"
2011        );
2012        assert_eq!(
2013            show(&replace(
2014                &one,
2015                5,
2016                10,
2017                3,
2018                ReplaceFormatPolicy::InheritPreceding
2019            )),
2020            "8..18=B",
2021            "…which the default would have lost: the replacement lands unformatted"
2022        );
2023    }
2024
2025    /// A run that merely *touches* the range must not leak its format to the whole
2026    /// replacement.
2027    #[test]
2028    fn a_partially_overlapping_run_does_not_count_as_covering() {
2029        let runs = vec![r(0, 8, "B")]; // covers only 5..8 of the range 5..12
2030        assert_eq!(
2031            show(&replace(
2032                &runs,
2033                5,
2034                12,
2035                4,
2036                ReplaceFormatPolicy::PreserveIfFullyCovered
2037            )),
2038            "0..9=B",
2039            "not covered → falls back to inheritance, which extends the preceding bold; \
2040             it must NOT format the whole replacement as though bold had covered it"
2041        );
2042    }
2043
2044    /// Ties between two runs resolve to the EARLIEST, deterministically.
2045    ///
2046    /// `Iterator::max_by_key` returns the LAST maximum, so the obvious one-liner would
2047    /// have silently picked the other run here.
2048    #[test]
2049    fn a_dominance_tie_between_two_runs_goes_to_the_earlier() {
2050        let runs = vec![r(0, 3, "B"), r(3, 6, "I")]; // 3 bytes each
2051        assert_eq!(
2052            show(&replace(
2053                &runs,
2054                0,
2055                6,
2056                4,
2057                ReplaceFormatPolicy::KeepDominantRun
2058            )),
2059            "0..4=B",
2060            "a true tie must resolve to the earlier run, not to whichever the iterator \
2061             happened to visit last"
2062        );
2063    }
2064
2065    /// A tie between a run and the unformatted gap goes to the run: losing formatting is
2066    /// the destructive outcome, so it needs a strict majority of *plain* to win.
2067    #[test]
2068    fn a_dominance_tie_against_plain_text_keeps_the_formatting() {
2069        let runs = vec![r(4, 8, "B")]; // 4 bold bytes, 4 plain bytes in 0..8
2070        assert_eq!(
2071            show(&replace(
2072                &runs,
2073                0,
2074                8,
2075                5,
2076                ReplaceFormatPolicy::KeepDominantRun
2077            )),
2078            "0..5=B",
2079            "an even split must keep the formatting rather than silently drop it"
2080        );
2081    }
2082
2083    /// An empty range replaces nothing, so it is an insertion — and every policy that
2084    /// reasons about "what was covered" must defer to the insert convention instead of
2085    /// stripping the format the typed text would have inherited.
2086    #[test]
2087    fn an_empty_range_is_an_insert_and_no_coverage_policy_overrides_it() {
2088        let runs = vec![r(0, 5, "B"), r(5, 10, "I")];
2089        use ReplaceFormatPolicy::*;
2090        for policy in [InheritPreceding, PreserveIfFullyCovered, KeepDominantRun] {
2091            assert_eq!(
2092                show(&replace(&runs, 5, 5, 2, policy)),
2093                "0..7=B 7..12=I",
2094                "{policy:?}: typing at a boundary must inherit the run to the LEFT (Qt \
2095                 convention) — an empty range destroyed no formatting, so there is \
2096                 nothing for a coverage policy to override"
2097            );
2098        }
2099        // The one policy that is an explicit request, not an inference, still applies.
2100        assert_eq!(
2101            show(&replace(&runs, 5, 5, 2, PreserveNothing)),
2102            "0..5=B 7..12=I",
2103            "PreserveNothing asks for unformatted text, and means it even on an insert"
2104        );
2105    }
2106
2107    /// Nothing to do must mean nothing done — no fabricated runs, no lost ones.
2108    #[test]
2109    fn a_zero_width_zero_length_replace_is_the_identity() {
2110        let runs = vec![r(0, 5, "B"), r(7, 12, "I")];
2111        for policy in [
2112            ReplaceFormatPolicy::InheritPreceding,
2113            ReplaceFormatPolicy::PreserveIfFullyCovered,
2114            ReplaceFormatPolicy::KeepDominantRun,
2115            ReplaceFormatPolicy::PreserveNothing,
2116        ] {
2117            assert_eq!(
2118                show(&replace(&runs, 6, 6, 0, policy)),
2119                "0..5=B 7..12=I",
2120                "{policy:?} changed a no-op edit"
2121            );
2122        }
2123    }
2124
2125    /// `PreserveNothing` must leave the region genuinely *unformatted* — not covered by
2126    /// a fabricated run carrying `CharacterFormat::default()`, which is a different
2127    /// thing and would defeat coalescing forever after.
2128    #[test]
2129    fn preserve_nothing_fabricates_no_default_run() {
2130        let runs = vec![r(0, 5, "B")];
2131        let got = replace(&runs, 7, 9, 2, ReplaceFormatPolicy::PreserveNothing);
2132        assert_eq!(show(&got), "0..5=B", "no run may be invented for the gap");
2133        assert!(
2134            got.iter().all(|x| x.byte_start < 7 || x.byte_end > 9),
2135            "the replaced span must carry no run at all"
2136        );
2137    }
2138
2139    /// Offsets are BYTES, not chars. A 4-byte emoji replaced by 2 ASCII bytes must
2140    /// shift downstream runs by -2, not by -1 (chars) or 0.
2141    #[test]
2142    fn offsets_are_bytes_not_characters() {
2143        // "🎉" (4 bytes, bold) + " " + "abcd" (italic).
2144        let runs = vec![r(0, 4, "B"), r(5, 9, "I")];
2145        let got = replace(&runs, 0, 4, 2, ReplaceFormatPolicy::KeepDominantRun);
2146        assert_eq!(
2147            show(&got),
2148            "0..2=B 3..7=I",
2149            "the trailing italic must shift back by the BYTE delta (4 -> 2 = -2)"
2150        );
2151    }
2152
2153    /// Every policy must leave the run list well-formed — sorted, non-overlapping,
2154    /// coalesced, inside the block. This is the invariant a release build no longer
2155    /// merely asserts.
2156    #[test]
2157    fn every_policy_leaves_the_runs_well_formed() {
2158        let setups: Vec<(Vec<FormatRun>, u32, u32, u32, usize)> = vec![
2159            (vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")], 2, 7, 4, 8),
2160            (vec![r(0, 5, "B"), r(8, 13, "B")], 5, 8, 0, 10),
2161            (vec![r(0, 5, "B"), r(7, 12, "B")], 8, 10, 2, 12),
2162            (vec![r(3, 7, "B")], 3, 7, 0, 6),
2163            (vec![], 2, 6, 3, 9),
2164        ];
2165        for (runs, start, end, n, text_len) in setups {
2166            for policy in [
2167                ReplaceFormatPolicy::InheritPreceding,
2168                ReplaceFormatPolicy::PreserveIfFullyCovered,
2169                ReplaceFormatPolicy::KeepDominantRun,
2170                ReplaceFormatPolicy::PreserveNothing,
2171            ] {
2172                let got = replace(&runs, start, end, n, policy);
2173                check_well_formed(&got, text_len).unwrap_or_else(|e| {
2174                    panic!(
2175                        "{policy:?} produced malformed runs from {} (replace {start}..{end}, \
2176                         n={n}): {} — {e}",
2177                        show(&runs),
2178                        show(&got)
2179                    )
2180                });
2181            }
2182        }
2183    }
2184
2185    /// Two same-format runs separated by an untouched gap must stay separate — coalescing
2186    /// is for *adjacent* runs, and over-eager merging would swallow the plain text between
2187    /// them.
2188    #[test]
2189    fn an_untouched_gap_between_equal_runs_survives() {
2190        let runs = vec![r(0, 5, "B"), r(7, 12, "B")];
2191        assert_eq!(
2192            show(&replace(
2193                &runs,
2194                8,
2195                10,
2196                2,
2197                ReplaceFormatPolicy::InheritPreceding
2198            )),
2199            "0..5=B 7..12=B",
2200            "the plain gap at 5..7 must not be swallowed"
2201        );
2202    }
2203
2204    /// An inverted range is refused, not asserted away.
2205    #[test]
2206    fn an_inverted_range_is_an_error_not_a_panic() {
2207        let mut runs = vec![r(0, 5, "B")];
2208        let err =
2209            shift_runs_for_replace(&mut runs, 10, 5, 3, ReplaceFormatPolicy::InheritPreceding)
2210                .expect_err("an inverted range must be rejected");
2211        assert!(matches!(
2212            err,
2213            FormatRunError::ReversedRange { start: 10, end: 5 }
2214        ));
2215        assert_eq!(show(&runs), "0..5=B", "a refused edit must change nothing");
2216    }
2217}
2218
2219/// The runtime guards that replaced the release-mode-invisible `debug_assert!`s.
2220#[cfg(test)]
2221mod invariant_check_tests {
2222    use super::*;
2223
2224    fn run(start: u32, end: u32, bold: bool) -> FormatRun {
2225        FormatRun {
2226            byte_start: start,
2227            byte_end: end,
2228            format: CharacterFormat {
2229                font_bold: Some(bold),
2230                ..Default::default()
2231            },
2232        }
2233    }
2234
2235    /// The whole point: in a **release** build `debug_assert!` is gone, so a violating
2236    /// splice used to sail straight through and build a malformed run list. Now it is
2237    /// reported, and the caller's runs are left exactly as they were.
2238    #[test]
2239    fn a_replacement_outside_the_range_is_rejected_without_mutating() {
2240        let mut runs = vec![run(0, 20, true)];
2241        let before = runs.clone();
2242
2243        let err = try_splice_range(&mut runs, 5..10, vec![run(5, 15, false)])
2244            .expect_err("a replacement run reaching past range.end must be rejected");
2245
2246        assert!(matches!(
2247            err,
2248            FormatRunError::ReplacementOutsideRange {
2249                run_end: 15,
2250                range_end: 10,
2251                ..
2252            }
2253        ));
2254        assert_eq!(
2255            runs, before,
2256            "a rejected splice must not half-apply — validation happens before mutation"
2257        );
2258    }
2259
2260    #[test]
2261    // The inverted range is the whole point of the test — it is what a caller must not
2262    // be able to sneak past a release build.
2263    #[allow(clippy::reversed_empty_ranges)]
2264    fn a_reversed_range_is_rejected() {
2265        let mut runs = vec![run(0, 20, true)];
2266        assert!(matches!(
2267            try_splice_range(&mut runs, 10..5, vec![]),
2268            Err(FormatRunError::ReversedRange { start: 10, end: 5 })
2269        ));
2270    }
2271
2272    #[test]
2273    fn a_legal_splice_still_works_through_the_checked_path() {
2274        let mut runs = vec![run(0, 20, true)];
2275        try_splice_range(&mut runs, 5..15, vec![run(5, 15, false)]).expect("legal");
2276        assert_eq!(runs.len(), 3);
2277        assert_eq!(runs[1].format.font_bold, Some(false));
2278    }
2279
2280    #[test]
2281    fn check_well_formed_catches_what_debug_assert_used_to() {
2282        assert!(check_well_formed(&[], 0).is_ok());
2283        assert!(check_well_formed(&[run(0, 5, true)], 5).is_ok());
2284
2285        assert!(matches!(
2286            check_well_formed(&[run(5, 5, true)], 10),
2287            Err(FormatRunError::EmptyRun { .. })
2288        ));
2289        assert!(matches!(
2290            check_well_formed(&[run(0, 8, true), run(5, 10, false)], 10),
2291            Err(FormatRunError::RunsOverlap { .. })
2292        ));
2293        assert!(matches!(
2294            check_well_formed(&[run(0, 5, true), run(5, 10, true)], 10),
2295            Err(FormatRunError::RunsNotCoalesced { .. })
2296        ));
2297        assert!(matches!(
2298            check_well_formed(&[run(0, 20, true)], 10),
2299            Err(FormatRunError::RunPastEndOfBlock { text_len: 10, .. })
2300        ));
2301    }
2302}