1
//! Pure functions for editing a `Vec<InlineContent>` based on selections.
2
//!
3
//! Entry points: [`edit_text`] (single edit, multiple cursors),
4
//! [`edit_text_multi`] (per-cursor text), and [`inspect_delete`]
5
//! (preview what a delete would remove).
6

            
7
use azul_core::selection::{
8
    CursorAffinity, GraphemeClusterId, Selection, SelectionRange, TextCursor,
9
};
10

            
11
use crate::text3::cache::{BreakType, ClearType, InlineBreak, InlineContent, StyledRun};
12

            
13
/// An enum representing a single text editing action.
14
#[derive(Debug, Clone)]
15
pub enum TextEdit {
16
    /// Insert the given string at the cursor position.
17
    Insert(String),
18
    /// Delete one grapheme cluster before the cursor (Backspace).
19
    DeleteBackward,
20
    /// Delete one grapheme cluster after the cursor (Delete key).
21
    DeleteForward,
22
}
23

            
24
3038
const fn selection_start_run(selection: &Selection) -> u32 {
25
3038
    match selection {
26
2995
        Selection::Cursor(c) => c.cluster_id.source_run,
27
43
        Selection::Range(r) => r.start.cluster_id.source_run,
28
    }
29
3038
}
30

            
31
3038
const fn selection_start_byte(selection: &Selection) -> u32 {
32
3038
    match selection {
33
2995
        Selection::Cursor(c) => c.cluster_id.start_byte_in_run,
34
43
        Selection::Range(r) => r.start.cluster_id.start_byte_in_run,
35
    }
36
3038
}
37

            
38
/// Sorts selections from the end of the document to the beginning so that
39
/// applying an edit at one selection does not invalidate the byte offsets of
40
/// selections still to be processed.
41
3004
fn sort_selections_back_to_front(selections: &[Selection]) -> Vec<Selection> {
42
3004
    let mut sorted = selections.to_vec();
43
3004
    sorted.sort_by(|a, b| {
44
42
        let cursor_a = match a {
45
41
            Selection::Cursor(c) => c,
46
1
            Selection::Range(r) => &r.start,
47
        };
48
42
        let cursor_b = match b {
49
42
            Selection::Cursor(c) => c,
50
            Selection::Range(r) => &r.start,
51
        };
52
42
        cursor_b.cluster_id.cmp(&cursor_a.cluster_id) // Reverse sort
53
42
    });
54
3004
    sorted
55
3004
}
56

            
57
/// Shifts every already-processed cursor sitting at or after `edit_byte` in
58
/// `edit_run` by `byte_offset_change`, clamping to zero.
59
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded layout/render numeric cast
60
3042
fn adjust_cursors(
61
3042
    selections: &mut [Selection],
62
3042
    edit_run: u32,
63
3042
    edit_byte: u32,
64
3042
    byte_offset_change: i32,
65
3042
) {
66
3042
    for sel in selections.iter_mut() {
67
45
        if let Selection::Cursor(cursor) = sel {
68
44
            if cursor.cluster_id.source_run == edit_run
69
43
                && cursor.cluster_id.start_byte_in_run >= edit_byte
70
42
            {
71
42
                cursor.cluster_id.start_byte_in_run =
72
42
                    (cursor.cluster_id.start_byte_in_run as i32 + byte_offset_change).max(0) as u32;
73
42
            }
74
1
        }
75
    }
76
3042
}
77

            
78
/// Shifts the `source_run` index of every already-processed cursor that sits in a
79
/// run AFTER `boundary_run`, by `run_count_change` (negative when runs were removed
80
/// or merged), clamping so it never drops to or below the surviving boundary run.
81
///
82
/// Needed because edits do not only change byte offsets within a run — a multi-run
83
/// delete (or a cross-run backspace/forward-delete, or removing an inline image)
84
/// changes the NUMBER of runs. Since cursors are processed back-to-front, a
85
/// previously-processed (later-in-document) cursor whose run comes after the edit
86
/// would otherwise keep a stale `source_run` pointing one-or-more runs too high —
87
/// landing on the wrong run or going out of bounds entirely.
88
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded layout/render numeric cast
89
3042
fn adjust_cursor_runs(selections: &mut [Selection], boundary_run: u32, run_count_change: i32) {
90
3042
    if run_count_change == 0 {
91
2945
        return;
92
97
    }
93
101
    for sel in selections.iter_mut() {
94
11
        if let Selection::Cursor(cursor) = sel {
95
10
            if cursor.cluster_id.source_run > boundary_run {
96
6
                let shifted = (cursor.cluster_id.source_run as i32 + run_count_change)
97
6
                    .max(boundary_run as i32);
98
6
                cursor.cluster_id.source_run = shifted as u32;
99
6
            }
100
1
        }
101
    }
102
3042
}
103

            
104
/// What an edit did to the text, run by run (U3-a): one
105
/// [`RunTextChange`](azul_core::selection::RunTextChange) per text run whose
106
/// text differs between `old` and `new`, all relative to the OLD content -
107
/// the input `MultiCursorState::shift_peers_across` moves peers' carets by.
108
///
109
/// Empty when the run COUNT changed: an edit that split or merged runs has
110
/// no run-stable mapping, and a wrong shift is worse than a stale caret (the
111
/// peer is re-placed by the app's next snapshot either way). Typing, pasting
112
/// and deleting inside a run - every keystroke in a plain text field - keep
113
/// the count.
114
#[must_use]
115
#[allow(clippy::cast_possible_truncation)] // run counts are bounded far below u32
116
3166
pub fn run_text_changes(
117
3166
    old: &[InlineContent],
118
3166
    new: &[InlineContent],
119
3166
) -> Vec<azul_core::selection::RunTextChange> {
120
3166
    if old.len() != new.len() {
121
        return Vec::new();
122
3166
    }
123
3166
    old.iter()
124
3166
        .zip(new)
125
3166
        .enumerate()
126
3556
        .filter_map(|(i, (o, n))| match (o, n) {
127
3366
            (InlineContent::Text(o), InlineContent::Text(n)) => {
128
3366
                azul_core::selection::RunTextChange::between(i as u32, &o.text, &n.text)
129
            }
130
190
            _ => None,
131
3556
        })
132
3166
        .collect()
133
3166
}
134

            
135
/// Byte length of the text in the run at `run_idx`, or 0 for non-text / missing runs.
136
/// The full caret-moving description of an edit (U3-a, U3-a-i): the byte
137
/// changes per run when the run count is unchanged, else a `RunRemap` from
138
/// the runs common to both ends plus the change to the concatenated middle.
139
#[must_use]
140
#[allow(clippy::cast_possible_truncation)] // run text is bounded far below u32
141
3286
pub fn run_text_diff(
142
3286
    old: &[InlineContent],
143
3286
    new: &[InlineContent],
144
3286
) -> azul_core::selection::RunTextDiff {
145
    use azul_core::selection::{RunRemap, RunTextChange, RunTextDiff};
146
3286
    if old.len() == new.len() {
147
3166
        return RunTextDiff {
148
3166
            remap: None,
149
3166
            changes: run_text_changes(old, new),
150
3166
        };
151
120
    }
152
710
    fn text_of(c: &InlineContent) -> &str {
153
710
        match c {
154
500
            InlineContent::Text(r) => &r.text,
155
210
            _ => "",
156
        }
157
710
    }
158
120
    let shorter = old.len().min(new.len());
159
120
    let mut prefix = 0;
160
340
    while prefix < shorter && old[prefix] == new[prefix] {
161
220
        prefix += 1;
162
220
    }
163
120
    let mut suffix = 0;
164
330
    while suffix < shorter - prefix && old[old.len() - 1 - suffix] == new[new.len() - 1 - suffix] {
165
210
        suffix += 1;
166
210
    }
167
120
    let old_mid = &old[prefix..old.len() - suffix];
168
120
    let new_mid = &new[prefix..new.len() - suffix];
169
120
    let concat_old: String = old_mid.iter().map(text_of).collect();
170
120
    let concat_new: String = new_mid.iter().map(text_of).collect();
171
    RunTextDiff {
172
        remap: Some(RunRemap {
173
120
            first: prefix as u32,
174
120
            old_lens: old_mid.iter().map(|c| text_of(c).len() as u32).collect(),
175
240
            new_lens: new_mid.iter().map(|c| text_of(c).len() as u32).collect(),
176
120
            middle: RunTextChange::between(0, &concat_old, &concat_new),
177
120
            prev_len: prefix
178
120
                .checked_sub(1)
179
120
                .and_then(|i| new.get(i))
180
120
                .map(|c| text_of(c).len() as u32),
181
        }),
182
120
        changes: Vec::new(),
183
    }
184
3286
}
185

            
186
6075
fn run_text_len(content: &[InlineContent], run_idx: u32) -> usize {
187
6075
    match content.get(run_idx as usize) {
188
6065
        Some(InlineContent::Text(run)) => run.text.len(),
189
10
        _ => 0,
190
    }
191
6075
}
192

            
193
/// The primary entry point for text modification. Takes the current content and selections,
194
/// applies an edit, and returns the new content and the resulting cursor positions.
195
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // bounded layout/render numeric cast
196
#[must_use]
197
56
pub fn edit_text(
198
56
    content: &[InlineContent],
199
56
    selections: &[Selection],
200
56
    edit: &TextEdit,
201
56
) -> (Vec<InlineContent>, Vec<Selection>) {
202
56
    match edit_text_outcome(content, selections, edit) {
203
        EditOutcome::Applied {
204
53
            content,
205
53
            selections,
206
53
        } => (content, selections),
207
1
        EditOutcome::NoOp(EditNoOp::NoSelection) => (content.to_vec(), Vec::new()),
208
        EditOutcome::NoOp(EditNoOp::EverySelectionMissed) => {
209
2
            (content.to_vec(), selections.to_vec())
210
        }
211
    }
212
56
}
213

            
214
/// Why [`edit_text_outcome`] applied nothing.
215
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216
pub enum EditNoOp {
217
    /// There was no cursor/selection to apply the edit at.
218
    NoSelection,
219
    /// Every selection's splice left the content untouched — a cursor pointing
220
    /// at a run that does not exist (an un-seeded empty editable: the caller
221
    /// owns seeding ONE empty styled run, see `apply_one_text_changeset`), a
222
    /// cursor on a non-Text item, a corrupt byte offset, or a delete at the
223
    /// document edge.
224
    EverySelectionMissed,
225
}
226

            
227
/// Outcome of [`edit_text_outcome`] — either the edited state, or the REASON
228
/// nothing changed. `edit_text` erases this distinction back into the old
229
/// tuple shape ("success, nothing happened"), which is exactly how a dropped
230
/// first keystroke stayed invisible: prefer this function in production code
231
/// and treat `NoOp` explicitly (skip undo recording, skip cache writes).
232
#[derive(Debug, Clone, PartialEq)]
233
pub enum EditOutcome {
234
    Applied {
235
        content: Vec<InlineContent>,
236
        selections: Vec<Selection>,
237
    },
238
    NoOp(EditNoOp),
239
}
240

            
241
/// [`edit_text`], but the no-op channel is explicit. Appliedness is tracked
242
/// from the byte/run-count deltas already computed per selection — no content
243
/// comparison. An insert of `""` counts as a miss (both deltas zero).
244
#[must_use]
245
3000
pub fn edit_text_outcome(
246
3000
    content: &[InlineContent],
247
3000
    selections: &[Selection],
248
3000
    edit: &TextEdit,
249
3000
) -> EditOutcome {
250
3000
    if selections.is_empty() {
251
2
        return EditOutcome::NoOp(EditNoOp::NoSelection);
252
2998
    }
253

            
254
2998
    let mut new_content = content.to_vec();
255
2998
    let mut new_selections = Vec::new();
256
2998
    let mut any_applied = false;
257

            
258
    // To handle multiple cursors correctly, we must process edits
259
    // from the end of the document to the beginning. This ensures that
260
    // earlier edits do not invalidate the indices of later edits.
261
2998
    let sorted_selections = sort_selections_back_to_front(selections);
262

            
263
6028
    for selection in sorted_selections {
264
3030
        let edit_run = selection_start_run(&selection);
265
3030
        let edit_byte = selection_start_byte(&selection);
266
3030

            
267
3030
        // Measure the affected run before and after the edit so we can shift
268
3030
        // previously-processed cursors by the ACTUAL byte delta. The old code
269
3030
        // hardcoded -1 for any delete, which mis-tracked multi-byte graphemes.
270
3030
        let old_run_len = run_text_len(&new_content, edit_run);
271
3030
        let old_run_count = new_content.len();
272
3030
        let (temp_content, new_cursor) = apply_edit_to_selection(&new_content, &selection, edit);
273
3030
        let new_run_len = run_text_len(&temp_content, edit_run);
274
3030
        let byte_offset_change = new_run_len as i32 - old_run_len as i32;
275
3030
        let run_count_change = temp_content.len() as i32 - old_run_count as i32;
276
3030
        // "Applied" is decided on the CONTENT, not on the byte / run deltas.
277
3030
        // The deltas catch the silent-fallthrough tail of `insert_text` and a
278
3030
        // delete at the edge, but overwriting a one-character selection with
279
3030
        // one character moves neither a byte nor a run boundary - and that
280
3030
        // used to read as a miss, so the whole edit came back as
281
3030
        // `EverySelectionMissed` and was dropped (found by a seat's Shift+Right,
282
3030
        // type "Z" over "b", 9b-ii-a-i-d-ii-b).
283
3030
        any_applied |= temp_content != new_content;
284
3030

            
285
3030
        // Adjust all previously-processed cursors in the same run that come after this position
286
3030
        adjust_cursors(&mut new_selections, edit_run, edit_byte, byte_offset_change);
287
3030
        // If the edit changed the run COUNT (multi-run delete / cross-run delete /
288
3030
        // image removal), reindex later cursors whose run sits after this edit.
289
3030
        adjust_cursor_runs(&mut new_selections, edit_run, run_count_change);
290
3030

            
291
3030
        new_content = temp_content;
292
3030
        new_selections.push(Selection::Cursor(new_cursor));
293
3030
    }
294

            
295
2998
    if !any_applied {
296
24
        return EditOutcome::NoOp(EditNoOp::EverySelectionMissed);
297
2974
    }
298

            
299
    // The new selections were added in reverse order, so we reverse them back.
300
2974
    new_selections.reverse();
301

            
302
2974
    EditOutcome::Applied {
303
2974
        content: new_content,
304
2974
        selections: new_selections,
305
2974
    }
306
3000
}
307

            
308
/// Applies a single edit to a single selection.
309
///
310
/// When the selection is a Range:
311
/// - `Insert`: deletes the range, then inserts text at the collapsed cursor
312
/// - `DeleteBackward`/`DeleteForward`: deletes the range ONLY (the range deletion replaces the
313
///   character-level delete — pressing Backspace with a selection should remove the selection, not
314
///   the selection + 1 char)
315
#[must_use]
316
3038
pub fn apply_edit_to_selection(
317
3038
    content: &[InlineContent],
318
3038
    selection: &Selection,
319
3038
    edit: &TextEdit,
320
3038
) -> (Vec<InlineContent>, TextCursor) {
321
3038
    let mut new_content = content.to_vec();
322

            
323
3038
    match selection {
324
44
        Selection::Range(range) => {
325
            // Delete the range first
326
44
            let (content_after_delete, cursor_pos) = delete_range(&new_content, range);
327
44
            match edit {
328
                // Insert: replace the deleted range with new text
329
21
                TextEdit::Insert(text_to_insert) => {
330
21
                    let mut c = content_after_delete;
331
21
                    insert_text(&c, &cursor_pos, text_to_insert)
332
                }
333
                // Delete: range deletion is sufficient — don't delete again
334
                TextEdit::DeleteBackward | TextEdit::DeleteForward => {
335
23
                    (content_after_delete, cursor_pos)
336
                }
337
            }
338
        }
339
2994
        Selection::Cursor(cursor) => match edit {
340
2922
            TextEdit::Insert(text_to_insert) => insert_text(&new_content, cursor, text_to_insert),
341
52
            TextEdit::DeleteBackward => delete_backward(&new_content, cursor),
342
20
            TextEdit::DeleteForward => delete_forward(&new_content, cursor),
343
        },
344
    }
345
3038
}
346

            
347
/// Absolute byte offset of a cursor within its run's text, honoring affinity.
348
///
349
/// `Leading` = at the start of the referenced grapheme cluster; `Trailing` =
350
/// after it. This mirrors the affinity handling in `insert_text` /
351
/// `delete_backward` / `delete_forward`, and is what lets a select-all range
352
/// (whose end cursor is `Trailing` on the last cluster) cover the whole text.
353
607
pub(crate) fn cursor_byte_offset_in_run(text: &str, cursor: &TextCursor) -> usize {
354
    use unicode_segmentation::UnicodeSegmentation;
355
607
    let csb = cursor.cluster_id.start_byte_in_run as usize;
356
607
    match cursor.affinity {
357
468
        CursorAffinity::Leading => csb.min(text.len()),
358
        CursorAffinity::Trailing => {
359
139
            if csb >= text.len() {
360
13
                text.len()
361
            } else {
362
126
                text[csb..]
363
126
                    .grapheme_indices(true)
364
126
                    .next()
365
126
                    .map_or(text.len(), |(_, g)| csb + g.len())
366
            }
367
        }
368
    }
369
607
}
370

            
371
/// Deletes the content within a given range.
372
///
373
/// Handles:
374
/// - Deletions within a single text run.
375
/// - Deletions spanning multiple runs: the start/end runs are truncated, the runs strictly between
376
///   them are dropped, and the two truncated runs are merged when they share the same style.
377
///
378
/// Non-text items (images, etc.) at the boundaries are left intact (their text
379
/// offset resolves to 0), while intermediate non-text items are dropped along
380
/// with the rest of the spanned content.
381
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
382
#[must_use]
383
67
pub fn delete_range(
384
67
    content: &[InlineContent],
385
67
    range: &SelectionRange,
386
67
) -> (Vec<InlineContent>, TextCursor) {
387
67
    let mut new_content = content.to_vec();
388
67
    let start_run_idx = range.start.cluster_id.source_run as usize;
389
67
    let end_run_idx = range.end.cluster_id.source_run as usize;
390

            
391
    // The range may be "backward" (start after end) when the user selected
392
    // right-to-left, e.g. Shift+Home or Shift+Left. Normalize to [lo, hi] so the
393
    // deletion is direction-agnostic. The old `start_byte <= end_byte` guard
394
    // skipped the drain for backward ranges, so Delete/Backspace (and type-to-
395
    // replace) silently did nothing on such selections.
396
67
    let mut cursor_after = range.start;
397
67
    if start_run_idx == end_run_idx {
398
52
        if let Some(InlineContent::Text(run)) = new_content.get_mut(start_run_idx) {
399
49
            let a = cursor_byte_offset_in_run(&run.text, &range.start);
400
49
            let b = cursor_byte_offset_in_run(&run.text, &range.end);
401
49
            let lo = a.min(b);
402
49
            let hi = a.max(b);
403
49
            if hi <= run.text.len() && lo < hi {
404
48
                let mut t = String::from(&*run.text);
405
48
                t.drain(lo..hi);
406
48
                run.text = alloc::sync::Arc::from(t.as_str());
407
48
                // Collapse the caret to the start of the deleted region (the low
408
48
                // end), regardless of the original selection direction.
409
48
                cursor_after = TextCursor {
410
48
                    cluster_id: GraphemeClusterId {
411
48
                        source_run: start_run_idx as u32,
412
48
                        start_byte_in_run: lo as u32,
413
48
                    },
414
48
                    affinity: CursorAffinity::Leading,
415
48
                };
416
48
            }
417
3
        } else if start_run_idx < new_content.len() && range.start != range.end {
418
1
            // The selection covers a single NON-text run (inline image / object /
419
1
            // shape). A byte-offset drain can't remove it; delete the whole item and
420
1
            // collapse the caret to its former index. `range.start != range.end`
421
1
            // guards against a zero-width (collapsed) selection deleting the item.
422
1
            new_content.remove(start_run_idx);
423
1
            cursor_after = TextCursor {
424
1
                cluster_id: GraphemeClusterId {
425
1
                    source_run: start_run_idx as u32,
426
1
                    start_byte_in_run: 0,
427
1
                },
428
1
                affinity: CursorAffinity::Leading,
429
1
            };
430
2
        }
431
    } else {
432
        // Multi-run deletion.
433
        //
434
        // Normalize direction so `lo` precedes `hi` in document order (the range
435
        // may be backward if the user selected right-to-left across runs). Then:
436
        //   1. truncate the start (lo) run to the text BEFORE the selection,
437
        //   2. truncate the end (hi) run to the text AFTER the selection,
438
        //   3. drop every run strictly between them,
439
        //   4. merge the two truncated runs when they share the same style.
440
15
        let (lo_run, lo_cursor, hi_run, hi_cursor) = if start_run_idx <= end_run_idx {
441
14
            (start_run_idx, range.start, end_run_idx, range.end)
442
        } else {
443
1
            (end_run_idx, range.end, start_run_idx, range.start)
444
        };
445

            
446
        // Affinity-aware byte offsets within the two boundary runs. Non-text
447
        // boundary runs resolve to 0 (nothing to truncate there).
448
15
        let lo_byte = match new_content.get(lo_run) {
449
15
            Some(InlineContent::Text(run)) => cursor_byte_offset_in_run(&run.text, &lo_cursor),
450
            _ => 0,
451
        };
452
15
        let hi_byte = match new_content.get(hi_run) {
453
14
            Some(InlineContent::Text(run)) => cursor_byte_offset_in_run(&run.text, &hi_cursor),
454
1
            _ => 0,
455
        };
456

            
457
        // 1. Keep only text[..lo_byte] in the start run; remember the head length (the collapse
458
        //    point for the caret).
459
15
        let head_len = if let Some(InlineContent::Text(run)) = new_content.get_mut(lo_run) {
460
15
            let cut = lo_byte.min(run.text.len());
461
15
            let mut t = String::from(&*run.text);
462
15
            t.truncate(cut);
463
15
            run.text = alloc::sync::Arc::from(t.as_str());
464
15
            cut
465
        } else {
466
            0
467
        };
468

            
469
        // 2. Keep only text[hi_byte..] in the end run.
470
15
        if let Some(InlineContent::Text(run)) = new_content.get_mut(hi_run) {
471
14
            let cut = hi_byte.min(run.text.len());
472
14
            let mut t = String::from(&*run.text);
473
14
            t.drain(..cut);
474
14
            run.text = alloc::sync::Arc::from(t.as_str());
475
14
        }
476

            
477
        // 3. Drop the intermediate runs. After draining, the end run sits at `lo_run + 1`. Clamp
478
        //    the end so a bogus out-of-range `hi_run` can never panic the drain.
479
15
        let drain_end = hi_run.min(new_content.len());
480
15
        if drain_end > lo_run + 1 {
481
11
            new_content.drain((lo_run + 1)..drain_end);
482
14
        }
483
15
        let tail_idx = lo_run + 1;
484

            
485
        // 4. Merge head and tail when both are text with matching style. Compared by value
486
        //    (`StyleProperties: PartialEq`) so runs that were split from one DOM element — or
487
        //    otherwise carry identical styling — re-join into a single run, while genuinely
488
        //    different styles stay separate.
489
15
        let mergeable = matches!(
490
15
            (new_content.get(lo_run), new_content.get(tail_idx)),
491
14
            (Some(InlineContent::Text(a)), Some(InlineContent::Text(b)))
492
14
                if a.style == b.style
493
        );
494
15
        if mergeable {
495
13
            if let InlineContent::Text(tail) = new_content.remove(tail_idx) {
496
13
                if let Some(InlineContent::Text(head)) = new_content.get_mut(lo_run) {
497
13
                    let mut t = String::from(&*head.text);
498
13
                    t.push_str(&tail.text);
499
13
                    head.text = alloc::sync::Arc::from(t.as_str());
500
13
                }
501
            }
502
2
        }
503

            
504
        // Collapse the caret to the join point (start of the deleted region).
505
15
        cursor_after = TextCursor {
506
15
            cluster_id: GraphemeClusterId {
507
15
                source_run: lo_run as u32,
508
15
                start_byte_in_run: head_len as u32,
509
15
            },
510
15
            affinity: CursorAffinity::Leading,
511
15
        };
512
    }
513

            
514
67
    (new_content, cursor_after) // caret at the start of the deleted range
515
67
}
516

            
517
/// Inserts text at a cursor position.
518
///
519
/// The cursor's affinity determines the exact insertion point:
520
/// - `Leading`: Insert at the start of the referenced cluster (`start_byte_in_run`)
521
/// - `Trailing`: Insert at the end of the referenced cluster (after the grapheme)
522
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
523
#[must_use]
524
2977
pub fn insert_text(
525
2977
    content: &[InlineContent],
526
2977
    cursor: &TextCursor,
527
2977
    text_to_insert: &str,
528
2977
) -> (Vec<InlineContent>, TextCursor) {
529
    use unicode_segmentation::UnicodeSegmentation;
530
2977
    let cursor = &sanitize_cursor(content, cursor);
531

            
532
    // A newline is a STRUCTURAL forced break, not a shapeable character. A raw
533
    // '\n' left inside a Text run renders as .notdef (tofu): the shaper only
534
    // treats an `InlineContent::LineBreak` item as a forced break, which is why
535
    // a <br> and every preserved DOM newline are turned into one in
536
    // `solver3/fc.rs`. Route an insert that carries newlines through that SAME
537
    // model — split it into Text segments joined by hard `LineBreak` items — so
538
    // a typed Enter in a multi-line field and a multi-line paste both land as
539
    // real line breaks instead of a tofu glyph. (Single-line hosts veto '\n'
540
    // upstream in `widgets::text_input`, so this path only runs where newlines
541
    // are meant to break.)
542
2977
    if text_to_insert.contains('\n') {
543
94
        return insert_text_with_line_breaks(content, cursor, text_to_insert);
544
2883
    }
545

            
546
2883
    let mut new_content = content.to_vec();
547
2883
    let run_idx = cursor.cluster_id.source_run as usize;
548
2883
    let cluster_start_byte = cursor.cluster_id.start_byte_in_run as usize;
549

            
550
2883
    if let Some(InlineContent::Text(run)) = new_content.get_mut(run_idx) {
551
        // Calculate the actual insertion byte offset based on affinity
552
2878
        let byte_offset = match cursor.affinity {
553
            CursorAffinity::Leading => {
554
                // Insert at the start of the cluster
555
2756
                cluster_start_byte
556
            }
557
            CursorAffinity::Trailing => {
558
                // Insert at the end of the cluster - find the next grapheme boundary
559
                // We need to find where this grapheme cluster ends
560
122
                if cluster_start_byte >= run.text.len() {
561
                    // Cursor is at/past end of run - insert at end
562
1
                    run.text.len()
563
                } else {
564
                    // Find the grapheme that starts at cluster_start_byte and get its end
565
121
                    run.text[cluster_start_byte..]
566
121
                        .grapheme_indices(true)
567
121
                        .next()
568
121
                        .map_or(run.text.len(), |(_, grapheme)| {
569
121
                            cluster_start_byte + grapheme.len()
570
121
                        })
571
                }
572
            }
573
        };
574

            
575
2878
        if byte_offset <= run.text.len() {
576
2878
            let mut t = String::from(&*run.text);
577
2878
            t.insert_str(byte_offset, text_to_insert);
578
2878
            run.text = alloc::sync::Arc::from(t.as_str());
579

            
580
2878
            let new_cursor = TextCursor {
581
2878
                cluster_id: GraphemeClusterId {
582
2878
                    source_run: run_idx as u32,
583
2878
                    start_byte_in_run: (byte_offset + text_to_insert.len()) as u32,
584
2878
                },
585
2878
                affinity: CursorAffinity::Leading,
586
2878
            };
587
2878
            return (new_content, new_cursor);
588
        }
589
5
    }
590

            
591
    // If insertion failed, return original state
592
5
    (content.to_vec(), *cursor)
593
2977
}
594

            
595
/// Insert text that CONTAINS one or more newlines at the cursor, splitting the
596
/// target Text run and emitting hard [`InlineContent::LineBreak`] items between
597
/// the segments (see [`insert_text`] for why a raw `'\n'` cannot stay in a run).
598
///
599
/// `"a\nb"` inserted mid-run `"XY|Z"` becomes `Text("XYa") · LineBreak · Text("bZ")`,
600
/// the caret landing at the start of `b` (i.e. just after the break). The
601
/// trailing text of the original run rides on the LAST new segment, so the caret
602
/// sits between the inserted text and the old tail exactly as a plain insert
603
/// would. The style and source node of the split run are carried onto every new
604
/// segment.
605
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
606
#[must_use]
607
94
fn insert_text_with_line_breaks(
608
94
    content: &[InlineContent],
609
94
    cursor: &TextCursor,
610
94
    text_to_insert: &str,
611
94
) -> (Vec<InlineContent>, TextCursor) {
612
    use unicode_segmentation::UnicodeSegmentation;
613

            
614
94
    let cursor = &sanitize_cursor(content, cursor);
615
94
    let run_idx = cursor.cluster_id.source_run as usize;
616
94
    let cluster_start_byte = cursor.cluster_id.start_byte_in_run as usize;
617

            
618
    // Only a Text run can be split around a caret; anything else is a no-op
619
    // (mirrors `insert_text`, which silently leaves a non-text run alone).
620
94
    let Some(InlineContent::Text(run)) = content.get(run_idx) else {
621
        return (content.to_vec(), *cursor);
622
    };
623
94
    let run = run.clone();
624

            
625
    // Same affinity → byte-offset resolution as `insert_text`.
626
94
    let byte_offset = match cursor.affinity {
627
73
        CursorAffinity::Leading => cluster_start_byte,
628
        CursorAffinity::Trailing => {
629
21
            if cluster_start_byte >= run.text.len() {
630
1
                run.text.len()
631
            } else {
632
20
                run.text[cluster_start_byte..]
633
20
                    .grapheme_indices(true)
634
20
                    .next()
635
20
                    .map_or(run.text.len(), |(_, g)| cluster_start_byte + g.len())
636
            }
637
        }
638
    };
639
94
    if byte_offset > run.text.len() {
640
        return (content.to_vec(), *cursor);
641
94
    }
642

            
643
94
    let head = &run.text[..byte_offset];
644
94
    let tail = &run.text[byte_offset..];
645

            
646
    // At least two segments, since the caller guaranteed a '\n'.
647
94
    let segments: Vec<&str> = text_to_insert.split('\n').collect();
648

            
649
189
    let mk_run = |text: String| {
650
189
        InlineContent::Text(StyledRun {
651
189
            text: alloc::sync::Arc::from(text.as_str()),
652
189
            style: run.style.clone(),
653
189
            logical_start_byte: 0,
654
189
            source_node_id: run.source_node_id,
655
189
        })
656
189
    };
657
95
    let mk_break = || {
658
95
        InlineContent::LineBreak(InlineBreak {
659
95
            break_type: BreakType::Hard,
660
95
            clear: ClearType::None,
661
95
            content_index: 0,
662
95
        })
663
95
    };
664

            
665
    // head+seg0 · [break · seg]... with the original tail appended to the last
666
    // segment.
667
94
    let mut items: Vec<InlineContent> = Vec::with_capacity(segments.len() * 2);
668
94
    let last = segments.len() - 1;
669
189
    for (i, seg) in segments.iter().enumerate() {
670
189
        if i > 0 {
671
95
            items.push(mk_break());
672
95
        }
673
189
        let text = match (i, i == last) {
674
            (0, true) => format!("{head}{seg}{tail}"),
675
94
            (0, false) => format!("{head}{seg}"),
676
94
            (_, true) => format!("{seg}{tail}"),
677
1
            (_, false) => (*seg).to_string(),
678
        };
679
189
        items.push(mk_run(text));
680
    }
681

            
682
    // The caret sits at the START of the original tail on the last new run:
683
    // after the last inserted segment, before the old trailing text.
684
94
    let last_run_new_idx = run_idx + items.len() - 1;
685
94
    let caret_byte = segments[last].len();
686

            
687
94
    let mut new_content = content.to_vec();
688
94
    new_content.splice(run_idx..=run_idx, items);
689

            
690
94
    let new_cursor = TextCursor {
691
94
        cluster_id: GraphemeClusterId {
692
94
            source_run: last_run_new_idx as u32,
693
94
            start_byte_in_run: caret_byte as u32,
694
94
        },
695
94
        affinity: CursorAffinity::Leading,
696
94
    };
697
94
    (new_content, new_cursor)
698
94
}
699

            
700
/// Deletes one grapheme cluster backward from the cursor.
701
///
702
/// The cursor's affinity determines the actual cursor position:
703
/// - `Leading`: Cursor is at start of cluster, delete the previous grapheme
704
/// - `Trailing`: Cursor is at end of cluster, delete the current grapheme
705
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
706
#[allow(clippy::too_many_lines)] // cohesive grapheme-deletion routine: one branch per cursor affinity
707
#[must_use]
708
/// Clamp a (possibly STALE) cursor to the given content: the run index into
709
/// range, the byte to a valid char boundary of that run's text (past-the-end
710
/// snaps to the end, mid-UTF-8 snaps down to the cluster start).
711
///
712
/// A cursor can legitimately outlive the text it was minted against - the
713
/// content pipeline replaces run text underneath it (a widget resetting its
714
/// value, an overlay entry retiring, a reconcile swapping generations) and
715
/// the cursor is only re-seated on the NEXT layout pass. Between those two
716
/// moments an edit used to slice `text[..stale_byte]` and ABORT the process
717
/// (device crash: `AzWidgets` Backspace, 2026-08-29). An edit against a stale
718
/// cursor must degrade to a clamped edit, never a panic; the `debug_asserts`
719
/// keep the PRODUCER of such a cursor loud in dev builds.
720
3208
fn sanitize_cursor(content: &[InlineContent], cursor: &TextCursor) -> TextCursor {
721
3208
    let mut c = *cursor;
722
    // An out-of-range RUN index keeps the ops' documented NO-OP semantics
723
    // (redirecting to a different run would edit text the user never
724
    // targeted) - only the BYTE within the addressed text run is repaired.
725
3208
    if let Some(InlineContent::Text(run)) = content.get(c.cluster_id.source_run as usize) {
726
3192
        let byte = c.cluster_id.start_byte_in_run as usize;
727
3192
        let len = run.text.len();
728
3192
        if byte > len {
729
3
            // LOUD, BUT NOT FATAL. This was `debug_assert!(false, ..)`, which
730
3
            // made the documented degradation path ABORT in dev builds -
731
3
            // including the three `insert_text_*_past_the_end_*` tests below,
732
3
            // which exist to pin the 2026-08-29 contract that a stale past-end
733
3
            // cursor CLAMPS so the keystroke lands instead of being dropped.
734
3
            // It also contradicted this function's own sentence: an edit
735
3
            // against a stale cursor "must degrade to a clamped edit, never a
736
3
            // panic". Past-the-end is a SUPPORTED input; the producer is still
737
3
            // worth naming, so dev builds say so and carry on.
738
3
            //
739
3
            // The char-boundary arm below keeps its `debug_assert!`: a cursor
740
3
            // pointing INTO a UTF-8 sequence is malformed rather than merely
741
3
            // stale, and nothing documents it as supported.
742
3
            #[cfg(debug_assertions)]
743
3
            {
744
3
                eprintln!(
745
3
                    "[azul][text] cursor byte {byte} is past the run text (len {len}) - a stale \
746
3
                     cursor survived a content swap; clamping to the end"
747
3
                );
748
3
            }
749
3
            c.cluster_id.start_byte_in_run = len as u32;
750
3189
        } else if !run.text.is_char_boundary(byte) {
751
            debug_assert!(
752
                false,
753
                "cursor byte {byte} is not a char boundary of the run text - a stale cursor \
754
                 survived a content swap",
755
            );
756
            let mut b = byte;
757
            while b > 0 && !run.text.is_char_boundary(b) {
758
                b -= 1;
759
            }
760
            c.cluster_id.start_byte_in_run = b as u32;
761
3189
        }
762
16
    }
763
3208
    c
764
3208
}
765

            
766
#[must_use]
767
95
pub fn delete_backward(
768
95
    content: &[InlineContent],
769
95
    cursor: &TextCursor,
770
95
) -> (Vec<InlineContent>, TextCursor) {
771
    use unicode_segmentation::UnicodeSegmentation;
772
95
    let cursor = &sanitize_cursor(content, cursor);
773
95
    let mut new_content = content.to_vec();
774
95
    let run_idx = cursor.cluster_id.source_run as usize;
775
95
    let cluster_start_byte = cursor.cluster_id.start_byte_in_run as usize;
776

            
777
    // Non-text run (inline image / object / shape) under the cursor. A grapheme
778
    // drain can't act on it, so handle it explicitly instead of silently no-op'ing.
779
95
    if new_content.get(run_idx).is_some()
780
92
        && !matches!(new_content.get(run_idx), Some(InlineContent::Text(_)))
781
    {
782
2
        return match cursor.affinity {
783
            // Caret sits AFTER the item — Backspace removes the item itself.
784
            CursorAffinity::Trailing => {
785
1
                new_content.remove(run_idx);
786
1
                (
787
1
                    new_content,
788
1
                    TextCursor {
789
1
                        cluster_id: GraphemeClusterId {
790
1
                            source_run: run_idx as u32,
791
1
                            start_byte_in_run: 0,
792
1
                        },
793
1
                        affinity: CursorAffinity::Leading,
794
1
                    },
795
1
                )
796
            }
797
            // Caret sits BEFORE the item — Backspace acts on the previous run.
798
2
            CursorAffinity::Leading if run_idx > 0 => {
799
1
                let prev_byte = match content.get(run_idx - 1) {
800
1
                    Some(InlineContent::Text(r)) => r.text.len() as u32,
801
                    _ => 0,
802
                };
803
1
                delete_backward(
804
1
                    content,
805
1
                    &TextCursor {
806
1
                        cluster_id: GraphemeClusterId {
807
1
                            source_run: (run_idx - 1) as u32,
808
1
                            start_byte_in_run: prev_byte,
809
1
                        },
810
1
                        affinity: CursorAffinity::Trailing,
811
1
                    },
812
                )
813
            }
814
1
            CursorAffinity::Leading => (content.to_vec(), *cursor),
815
        };
816
92
    }
817

            
818
92
    if let Some(InlineContent::Text(run)) = new_content.get_mut(run_idx) {
819
        // Calculate the actual cursor byte offset based on affinity
820
89
        let byte_offset = match cursor.affinity {
821
57
            CursorAffinity::Leading => cluster_start_byte,
822
            CursorAffinity::Trailing => {
823
                // Cursor is at end of cluster - find the next grapheme boundary
824
32
                if cluster_start_byte >= run.text.len() {
825
11
                    run.text.len()
826
                } else {
827
21
                    run.text[cluster_start_byte..]
828
21
                        .grapheme_indices(true)
829
21
                        .next()
830
21
                        .map_or(run.text.len(), |(_, grapheme)| {
831
21
                            cluster_start_byte + grapheme.len()
832
21
                        })
833
                }
834
            }
835
        };
836

            
837
89
        if byte_offset > 0 {
838
74
            let prev_grapheme_start = run.text[..byte_offset]
839
74
                .grapheme_indices(true)
840
74
                .next_back()
841
74
                .map_or(0, |(i, _)| i);
842
74
            let mut t = String::from(&*run.text);
843
74
            t.drain(prev_grapheme_start..byte_offset);
844
74
            run.text = alloc::sync::Arc::from(t.as_str());
845

            
846
74
            let new_cursor = TextCursor {
847
74
                cluster_id: GraphemeClusterId {
848
74
                    source_run: run_idx as u32,
849
74
                    start_byte_in_run: prev_grapheme_start as u32,
850
74
                },
851
74
                affinity: CursorAffinity::Leading,
852
74
            };
853
74
            return (new_content, new_cursor);
854
15
        } else if run_idx > 0 {
855
            // Handle deleting across run boundaries.
856
3
            match content.get(run_idx - 1).cloned() {
857
                // Previous run is text — merge the two runs.
858
1
                Some(InlineContent::Text(prev_run)) => {
859
1
                    let mut merged_text = String::from(&*prev_run.text);
860
1
                    let new_cursor_byte_offset = merged_text.len();
861
1
                    merged_text.push_str(&run.text);
862

            
863
1
                    new_content[run_idx - 1] = InlineContent::Text(StyledRun {
864
1
                        text: alloc::sync::Arc::from(merged_text.as_str()),
865
1
                        style: prev_run.style,
866
1
                        logical_start_byte: prev_run.logical_start_byte,
867
1
                        source_node_id: prev_run.source_node_id,
868
1
                    });
869
1
                    new_content.remove(run_idx);
870

            
871
1
                    let new_cursor = TextCursor {
872
1
                        cluster_id: GraphemeClusterId {
873
1
                            source_run: (run_idx - 1) as u32,
874
1
                            start_byte_in_run: new_cursor_byte_offset as u32,
875
1
                        },
876
1
                        affinity: CursorAffinity::Leading,
877
1
                    };
878
1
                    return (new_content, new_cursor);
879
                }
880
                // Previous run is a non-text item — Backspace removes it.
881
                Some(_) => {
882
2
                    new_content.remove(run_idx - 1);
883
2
                    let new_cursor = TextCursor {
884
2
                        cluster_id: GraphemeClusterId {
885
2
                            source_run: (run_idx - 1) as u32,
886
2
                            start_byte_in_run: 0,
887
2
                        },
888
2
                        affinity: CursorAffinity::Leading,
889
2
                    };
890
2
                    return (new_content, new_cursor);
891
                }
892
                None => {}
893
            }
894
12
        }
895
3
    }
896

            
897
15
    (content.to_vec(), *cursor)
898
95
}
899

            
900
/// Deletes one grapheme cluster forward from the cursor.
901
///
902
/// The cursor's affinity determines the actual cursor position:
903
/// - `Leading`: Cursor is at start of cluster, delete the current grapheme
904
/// - `Trailing`: Cursor is at end of cluster, delete the next grapheme
905
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
906
#[must_use]
907
42
pub fn delete_forward(
908
42
    content: &[InlineContent],
909
42
    cursor: &TextCursor,
910
42
) -> (Vec<InlineContent>, TextCursor) {
911
    use unicode_segmentation::UnicodeSegmentation;
912
42
    let cursor = &sanitize_cursor(content, cursor);
913
42
    let mut new_content = content.to_vec();
914
42
    let run_idx = cursor.cluster_id.source_run as usize;
915
42
    let cluster_start_byte = cursor.cluster_id.start_byte_in_run as usize;
916

            
917
    // Non-text run (inline image / object / shape) under the cursor.
918
42
    if new_content.get(run_idx).is_some()
919
40
        && !matches!(new_content.get(run_idx), Some(InlineContent::Text(_)))
920
    {
921
2
        return match cursor.affinity {
922
            // Caret sits BEFORE the item — Delete removes the item itself.
923
            CursorAffinity::Leading => {
924
1
                new_content.remove(run_idx);
925
1
                (
926
1
                    new_content,
927
1
                    TextCursor {
928
1
                        cluster_id: GraphemeClusterId {
929
1
                            source_run: run_idx as u32,
930
1
                            start_byte_in_run: 0,
931
1
                        },
932
1
                        affinity: CursorAffinity::Leading,
933
1
                    },
934
1
                )
935
            }
936
            // Caret sits AFTER the item — Delete acts on the next run.
937
2
            CursorAffinity::Trailing if run_idx + 1 < content.len() => delete_forward(
938
1
                content,
939
1
                &TextCursor {
940
1
                    cluster_id: GraphemeClusterId {
941
1
                        source_run: (run_idx + 1) as u32,
942
1
                        start_byte_in_run: 0,
943
1
                    },
944
1
                    affinity: CursorAffinity::Leading,
945
1
                },
946
            ),
947
1
            CursorAffinity::Trailing => (content.to_vec(), *cursor),
948
        };
949
39
    }
950

            
951
39
    if let Some(InlineContent::Text(run)) = new_content.get_mut(run_idx) {
952
        // Calculate the actual cursor byte offset based on affinity
953
37
        let byte_offset = match cursor.affinity {
954
37
            CursorAffinity::Leading => cluster_start_byte,
955
            CursorAffinity::Trailing => {
956
                // Cursor is at end of cluster - find the next grapheme boundary
957
                if cluster_start_byte >= run.text.len() {
958
                    run.text.len()
959
                } else {
960
                    run.text[cluster_start_byte..]
961
                        .grapheme_indices(true)
962
                        .next()
963
                        .map_or(run.text.len(), |(_, grapheme)| {
964
                            cluster_start_byte + grapheme.len()
965
                        })
966
                }
967
            }
968
        };
969

            
970
37
        if byte_offset < run.text.len() {
971
23
            let next_grapheme_end = run.text[byte_offset..]
972
23
                .grapheme_indices(true)
973
23
                .nth(1)
974
23
                .map_or(run.text.len(), |(i, _)| byte_offset + i);
975
23
            let mut t = String::from(&*run.text);
976
23
            t.drain(byte_offset..next_grapheme_end);
977
23
            run.text = alloc::sync::Arc::from(t.as_str());
978

            
979
            // Cursor position stays at the same byte offset but with Leading affinity
980
23
            let new_cursor = TextCursor {
981
23
                cluster_id: GraphemeClusterId {
982
23
                    source_run: run_idx as u32,
983
23
                    start_byte_in_run: byte_offset as u32,
984
23
                },
985
23
                affinity: CursorAffinity::Leading,
986
23
            };
987
23
            return (new_content, new_cursor);
988
14
        } else if run_idx < content.len() - 1 {
989
            // Handle deleting across run boundaries.
990
3
            match content.get(run_idx + 1).cloned() {
991
                // Next run is text — merge the two runs.
992
1
                Some(InlineContent::Text(next_run)) => {
993
1
                    let mut merged_text = String::from(&*run.text);
994
1
                    merged_text.push_str(&next_run.text);
995

            
996
1
                    new_content[run_idx] = InlineContent::Text(StyledRun {
997
1
                        text: alloc::sync::Arc::from(merged_text.as_str()),
998
1
                        style: run.style.clone(),
999
1
                        logical_start_byte: run.logical_start_byte,
1
                        source_node_id: run.source_node_id,
1
                    });
1
                    new_content.remove(run_idx + 1);
1
                    return (new_content, *cursor);
                }
                // Next run is a non-text item — Delete removes it.
                Some(_) => {
2
                    new_content.remove(run_idx + 1);
2
                    return (new_content, *cursor);
                }
                None => {}
            }
11
        }
2
    }
13
    (content.to_vec(), *cursor)
42
}
/// Edit text with different text per selection (for N-lines-to-N-cursors paste).
///
/// Each selection gets its own text inserted. Selections are processed back-to-front
/// to avoid index invalidation. Returns the new content and updated cursors.
///
/// # Panics
///
/// Panics if `texts.len() != selections.len()`.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // bounded layout/render numeric cast
#[must_use]
4
pub fn edit_text_multi(
4
    content: &[InlineContent],
4
    selections: &[Selection],
4
    texts: &[&str],
4
) -> (Vec<InlineContent>, Vec<Selection>) {
4
    assert_eq!(
4
        selections.len(),
4
        texts.len(),
1
        "edit_text_multi: selections and texts must have the same length"
    );
3
    if selections.is_empty() {
1
        return (content.to_vec(), Vec::new());
2
    }
2
    let mut new_content = content.to_vec();
2
    let mut new_selections = Vec::new();
    // Pair selections with their text, sort back-to-front
2
    let mut pairs: Vec<(Selection, &str)> = selections
2
        .iter()
2
        .copied()
2
        .zip(texts.iter().copied())
2
        .collect();
2
    pairs.sort_by(|a, b| {
2
        let cursor_a = match &a.0 {
2
            Selection::Cursor(c) => c,
            Selection::Range(r) => &r.start,
        };
2
        let cursor_b = match &b.0 {
2
            Selection::Cursor(c) => c,
            Selection::Range(r) => &r.start,
        };
2
        cursor_b.cluster_id.cmp(&cursor_a.cluster_id) // Reverse sort
2
    });
6
    for (selection, text) in &pairs {
4
        let edit = TextEdit::Insert((*text).to_string());
4

            
4
        let edit_run = selection_start_run(selection);
4
        let edit_byte = selection_start_byte(selection);
4

            
4
        let old_run_len = run_text_len(&new_content, edit_run);
4
        let old_run_count = new_content.len();
4
        let (temp_content, new_cursor) = apply_edit_to_selection(&new_content, selection, &edit);
4
        let new_run_len = run_text_len(&temp_content, edit_run);
4
        let byte_offset_change = new_run_len as i32 - old_run_len as i32;
4
        let run_count_change = temp_content.len() as i32 - old_run_count as i32;
4

            
4
        adjust_cursors(&mut new_selections, edit_run, edit_byte, byte_offset_change);
4
        adjust_cursor_runs(&mut new_selections, edit_run, run_count_change);
4

            
4
        new_content = temp_content;
4
        new_selections.push(Selection::Cursor(new_cursor));
4
    }
2
    new_selections.reverse();
2
    (new_content, new_selections)
3
}
/// Returns the range and text that a delete operation would remove, without
/// actually modifying the content.
///
/// Useful for callbacks that need to inspect
/// pending deletes. Returns `None` if nothing would be deleted.
#[must_use]
14
pub fn inspect_delete(
14
    content: &[InlineContent],
14
    selection: &Selection,
14
    forward: bool,
14
) -> Option<(SelectionRange, String)> {
14
    match selection {
1
        Selection::Range(range) => {
            // If there's already a selection, that's what would be deleted
1
            let deleted_text = extract_text_in_range(content, range);
1
            Some((*range, deleted_text))
        }
13
        Selection::Cursor(cursor) => {
            // No selection - would delete one grapheme cluster
13
            if forward {
7
                inspect_delete_forward(content, cursor)
            } else {
6
                inspect_delete_backward(content, cursor)
            }
        }
    }
14
}
/// Inspect what would be deleted by delete-forward (Delete key)
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
7
fn inspect_delete_forward(
7
    content: &[InlineContent],
7
    cursor: &TextCursor,
7
) -> Option<(SelectionRange, String)> {
    use unicode_segmentation::UnicodeSegmentation;
7
    let run_idx = cursor.cluster_id.source_run as usize;
7
    if let Some(InlineContent::Text(run)) = content.get(run_idx) {
        // Honor cursor affinity, mirroring delete_forward — a Trailing cursor
        // sits after its grapheme, so the raw start_byte_in_run is wrong here.
5
        let byte_offset = cursor_byte_offset_in_run(&run.text, cursor);
5
        if byte_offset < run.text.len() {
            // Delete within same run
2
            let next_grapheme_end = run.text[byte_offset..]
2
                .grapheme_indices(true)
2
                .nth(1)
2
                .map_or(run.text.len(), |(i, _)| byte_offset + i);
2
            let deleted_text = run.text[byte_offset..next_grapheme_end].to_string();
2
            let range = SelectionRange {
2
                start: *cursor,
2
                end: TextCursor {
2
                    cluster_id: GraphemeClusterId {
2
                        source_run: run_idx as u32,
2
                        start_byte_in_run: next_grapheme_end as u32,
2
                    },
2
                    affinity: CursorAffinity::Leading,
2
                },
2
            };
2
            return Some((range, deleted_text));
3
        } else if run_idx < content.len() - 1 {
            // Would delete across run boundary
2
            if let Some(InlineContent::Text(next_run)) = content.get(run_idx + 1) {
1
                let deleted_text = next_run.text.graphemes(true).next()?.to_string();
1
                let next_grapheme_end = next_run
1
                    .text
1
                    .grapheme_indices(true)
1
                    .nth(1)
1
                    .map_or(next_run.text.len(), |(i, _)| i);
1
                let range = SelectionRange {
1
                    start: *cursor,
1
                    end: TextCursor {
1
                        cluster_id: GraphemeClusterId {
1
                            source_run: (run_idx + 1) as u32,
1
                            start_byte_in_run: next_grapheme_end as u32,
1
                        },
1
                        affinity: CursorAffinity::Leading,
1
                    },
1
                };
1
                return Some((range, deleted_text));
1
            }
1
        }
2
    }
4
    None // At end of document, nothing to delete
7
}
/// Inspect what would be deleted by delete-backward (Backspace key)
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
6
fn inspect_delete_backward(
6
    content: &[InlineContent],
6
    cursor: &TextCursor,
6
) -> Option<(SelectionRange, String)> {
    use unicode_segmentation::UnicodeSegmentation;
6
    let run_idx = cursor.cluster_id.source_run as usize;
6
    if let Some(InlineContent::Text(run)) = content.get(run_idx) {
        // Honor cursor affinity, mirroring delete_backward — a Trailing cursor
        // sits after its grapheme, so the raw start_byte_in_run is wrong here.
4
        let byte_offset = cursor_byte_offset_in_run(&run.text, cursor);
4
        if byte_offset > 0 {
            // Delete within same run
1
            let prev_grapheme_start = run.text[..byte_offset]
1
                .grapheme_indices(true)
1
                .next_back()
1
                .map_or(0, |(i, _)| i);
1
            let deleted_text = run.text[prev_grapheme_start..byte_offset].to_string();
1
            let range = SelectionRange {
1
                start: TextCursor {
1
                    cluster_id: GraphemeClusterId {
1
                        source_run: run_idx as u32,
1
                        start_byte_in_run: prev_grapheme_start as u32,
1
                    },
1
                    affinity: CursorAffinity::Leading,
1
                },
1
                end: *cursor,
1
            };
1
            return Some((range, deleted_text));
3
        } else if run_idx > 0 {
            // Would delete across run boundary
2
            if let Some(InlineContent::Text(prev_run)) = content.get(run_idx - 1) {
1
                let deleted_text = prev_run.text.graphemes(true).next_back()?.to_string();
1
                let prev_grapheme_start = prev_run.text[..]
1
                    .grapheme_indices(true)
1
                    .next_back()
1
                    .map_or(0, |(i, _)| i);
1
                let range = SelectionRange {
1
                    start: TextCursor {
1
                        cluster_id: GraphemeClusterId {
1
                            source_run: (run_idx - 1) as u32,
1
                            start_byte_in_run: prev_grapheme_start as u32,
1
                        },
1
                        affinity: CursorAffinity::Leading,
1
                    },
1
                    end: *cursor,
1
                };
1
                return Some((range, deleted_text));
1
            }
1
        }
2
    }
4
    None // At start of document, nothing to delete
6
}
/// Extract the text within a selection range
9
fn extract_text_in_range(content: &[InlineContent], range: &SelectionRange) -> String {
9
    let start_run = range.start.cluster_id.source_run as usize;
9
    let end_run = range.end.cluster_id.source_run as usize;
9
    let start_byte = range.start.cluster_id.start_byte_in_run as usize;
9
    let end_byte = range.end.cluster_id.start_byte_in_run as usize;
9
    if start_run == end_run {
        // Single run
7
        if let Some(InlineContent::Text(run)) = content.get(start_run) {
5
            if start_byte <= end_byte && end_byte <= run.text.len() {
3
                return run.text[start_byte..end_byte].to_string();
2
            }
2
        }
    } else {
        // Multi-run selection (simplified - full implementation would handle images, etc.)
2
        let mut result = String::new();
6
        for (idx, item) in content.iter().enumerate() {
6
            if let InlineContent::Text(run) = item {
5
                if idx == start_run {
                    // First run - from start_byte to end
2
                    if start_byte < run.text.len() {
2
                        result.push_str(&run.text[start_byte..]);
2
                    }
3
                } else if idx > start_run && idx < end_run {
1
                    // Middle runs - entire text
1
                    result.push_str(&run.text);
2
                } else if idx == end_run {
                    // Last run - from 0 to end_byte
2
                    if end_byte <= run.text.len() {
2
                        result.push_str(&run.text[..end_byte]);
2
                    }
2
                    break;
                }
1
            }
        }
2
        return result;
    }
4
    String::new()
9
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use std::sync::Arc;
    use unicode_segmentation::UnicodeSegmentation;
    use super::*;
    use crate::text3::cache::StyleProperties;
    // ---------------------------------------------------------------- helpers
    fn style_a() -> Arc<StyleProperties> {
        Arc::new(StyleProperties::default())
    }
    /// A style that compares unequal to [`style_a`] (`StyleProperties: PartialEq`),
    /// so `delete_range`'s style-based run merge can be exercised both ways.
    fn style_b() -> Arc<StyleProperties> {
        Arc::new(StyleProperties {
            font_size_px: 99.0,
            ..StyleProperties::default()
        })
    }
    fn text(s: &str) -> InlineContent {
        InlineContent::Text(StyledRun {
            text: Arc::from(s),
            style: style_a(),
            logical_start_byte: 0,
            source_node_id: None,
        })
    }
    fn text_styled(s: &str, style: Arc<StyleProperties>) -> InlineContent {
        InlineContent::Text(StyledRun {
            text: Arc::from(s),
            style,
            logical_start_byte: 0,
            source_node_id: None,
        })
    }
    /// A non-text inline item (stands in for an inline image / object / shape).
    /// `Tab` is the cheapest such variant to build — it carries only a style.
    fn obj() -> InlineContent {
        InlineContent::Tab { style: style_a() }
    }
    /// `InlineContent` has no `PartialEq`, so compare a printable projection:
    /// text runs render as their text, everything else as `<obj>`.
    fn dump(content: &[InlineContent]) -> Vec<String> {
        content
            .iter()
            .map(|c| match c {
                InlineContent::Text(r) => String::from(&*r.text),
                _ => "<obj>".to_string(),
            })
            .collect()
    }
    fn lead(run: u32, byte: u32) -> TextCursor {
        TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: run,
                start_byte_in_run: byte,
            },
            affinity: CursorAffinity::Leading,
        }
    }
    fn trail(run: u32, byte: u32) -> TextCursor {
        TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: run,
                start_byte_in_run: byte,
            },
            affinity: CursorAffinity::Trailing,
        }
    }
    fn range_sel(start: TextCursor, end: TextCursor) -> Selection {
        Selection::Range(SelectionRange { start, end })
    }
    fn cursor_of(sel: &Selection) -> TextCursor {
        match sel {
            Selection::Cursor(c) => *c,
            Selection::Range(r) => r.start,
        }
    }
    /// A ZWJ emoji family: 👨(4) + ZWJ(3) + 👩(4) + ZWJ(3) + 👧(4) = 18 bytes,
    /// but exactly ONE extended grapheme cluster.
    const FAMILY: &str = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";
    #[test]
    fn family_constant_is_one_grapheme_of_18_bytes() {
        // Guards the fixture the grapheme tests below rely on.
        assert_eq!(FAMILY.len(), 18);
        assert_eq!(FAMILY.graphemes(true).count(), 1);
    }
    // ------------------------------------------- selection_start_run / _byte
    #[test]
    fn selection_start_run_and_byte_read_the_cursor() {
        let sel = Selection::Cursor(lead(3, 7));
        assert_eq!(selection_start_run(&sel), 3);
        assert_eq!(selection_start_byte(&sel), 7);
    }
    #[test]
    fn selection_start_run_and_byte_read_range_start_not_end() {
        // Even for a BACKWARD range (start after end) the raw `start` is reported.
        let sel = range_sel(lead(9, 40), lead(1, 2));
        assert_eq!(selection_start_run(&sel), 9);
        assert_eq!(selection_start_byte(&sel), 40);
    }
    #[test]
    fn selection_start_accessors_survive_u32_max() {
        let sel = Selection::Cursor(trail(u32::MAX, u32::MAX));
        assert_eq!(selection_start_run(&sel), u32::MAX);
        assert_eq!(selection_start_byte(&sel), u32::MAX);
        let sel = range_sel(lead(u32::MAX, u32::MAX), lead(0, 0));
        assert_eq!(selection_start_run(&sel), u32::MAX);
        assert_eq!(selection_start_byte(&sel), u32::MAX);
    }
    // ------------------------------------------ sort_selections_back_to_front
    #[test]
    fn sort_back_to_front_empty_and_single() {
        assert!(sort_selections_back_to_front(&[]).is_empty());
        let one = [Selection::Cursor(lead(0, 0))];
        assert_eq!(sort_selections_back_to_front(&one).len(), 1);
    }
    #[test]
    fn sort_back_to_front_is_descending_by_cluster_id() {
        let sels = [
            Selection::Cursor(lead(0, 0)),
            Selection::Cursor(lead(2, 5)),
            Selection::Cursor(lead(1, 3)),
            Selection::Cursor(lead(2, 1)),
        ];
        let sorted = sort_selections_back_to_front(&sels);
        let keys: Vec<(u32, u32)> = sorted
            .iter()
            .map(|s| {
                let c = cursor_of(s).cluster_id;
                (c.source_run, c.start_byte_in_run)
            })
            .collect();
        assert_eq!(keys, vec![(2, 5), (2, 1), (1, 3), (0, 0)]);
        // Monotonically non-increasing — the invariant the multi-cursor edit loop
        // depends on for its byte offsets to stay valid.
        assert!(keys.windows(2).all(|w| w[0] >= w[1]));
    }
    #[test]
    fn sort_back_to_front_is_a_permutation_with_duplicates() {
        let sels = [
            Selection::Cursor(lead(1, 1)),
            Selection::Cursor(lead(1, 1)),
            Selection::Cursor(lead(0, 0)),
        ];
        let sorted = sort_selections_back_to_front(&sels);
        assert_eq!(sorted.len(), 3);
        let mut got: Vec<Selection> = sorted;
        let mut want: Vec<Selection> = sels.to_vec();
        got.sort();
        want.sort();
        assert_eq!(got, want);
    }
    #[test]
    fn sort_back_to_front_keys_ranges_on_their_start() {
        // Range starts at run 5; the plain cursor is at run 0 -> range sorts first.
        let sels = [
            Selection::Cursor(lead(0, 0)),
            range_sel(lead(5, 0), lead(0, 0)),
        ];
        let sorted = sort_selections_back_to_front(&sels);
        assert!(matches!(sorted[0], Selection::Range(_)));
        assert!(matches!(sorted[1], Selection::Cursor(_)));
    }
    #[test]
    fn sort_back_to_front_handles_u32_max_keys() {
        let sels = [
            Selection::Cursor(lead(u32::MAX, u32::MAX)),
            Selection::Cursor(lead(0, 0)),
        ];
        let sorted = sort_selections_back_to_front(&sels);
        assert_eq!(cursor_of(&sorted[0]).cluster_id.source_run, u32::MAX);
    }
    // ------------------------------------------------------- adjust_cursors
    fn byte_at(sels: &[Selection], i: usize) -> u32 {
        cursor_of(&sels[i]).cluster_id.start_byte_in_run
    }
    #[test]
    fn adjust_cursors_empty_slice_is_a_noop() {
        let mut sels: Vec<Selection> = Vec::new();
        adjust_cursors(&mut sels, 0, 0, i32::MIN);
        assert!(sels.is_empty());
    }
    #[test]
    fn adjust_cursors_zero_change_leaves_everything_alone() {
        let mut sels = vec![
            Selection::Cursor(lead(0, 0)),
            Selection::Cursor(lead(0, 10)),
        ];
        adjust_cursors(&mut sels, 0, 0, 0);
        assert_eq!(byte_at(&sels, 0), 0);
        assert_eq!(byte_at(&sels, 1), 10);
    }
    #[test]
    fn adjust_cursors_only_shifts_at_or_after_edit_byte_in_the_edit_run() {
        let mut sels = vec![
            Selection::Cursor(lead(0, 2)), // before edit_byte -> untouched
            Selection::Cursor(lead(0, 5)), // AT edit_byte     -> shifted
            Selection::Cursor(lead(0, 9)), // after edit_byte  -> shifted
            Selection::Cursor(lead(1, 0)), // other run        -> untouched
        ];
        adjust_cursors(&mut sels, 0, 5, 3);
        assert_eq!(byte_at(&sels, 0), 2);
        assert_eq!(byte_at(&sels, 1), 8);
        assert_eq!(byte_at(&sels, 2), 12);
        assert_eq!(byte_at(&sels, 3), 0);
    }
    #[test]
    fn adjust_cursors_negative_change_clamps_at_zero() {
        let mut sels = vec![Selection::Cursor(lead(0, 3))];
        adjust_cursors(&mut sels, 0, 0, -100);
        assert_eq!(byte_at(&sels, 0), 0, "documented clamp-to-zero");
    }
    #[test]
    fn adjust_cursors_i32_extremes_do_not_panic() {
        // i32::MAX applied to byte 0 saturates the offset, not the process.
        let mut sels = vec![Selection::Cursor(lead(0, 0))];
        adjust_cursors(&mut sels, 0, 0, i32::MAX);
        assert_eq!(byte_at(&sels, 0), i32::MAX as u32);
        // i32::MIN applied to byte 0 clamps to zero rather than wrapping.
        let mut sels = vec![Selection::Cursor(lead(0, 0))];
        adjust_cursors(&mut sels, 0, 0, i32::MIN);
        assert_eq!(byte_at(&sels, 0), 0);
    }
    #[test]
    fn adjust_cursors_u32_max_byte_collapses_to_zero() {
        // NOTE (reported): `start_byte_in_run as i32` WRAPS — u32::MAX becomes -1,
        // so a no-op (+0) adjustment silently relocates the cursor to byte 0.
        // Not reachable from real 2 GiB-run content, but it is the current behavior.
        let mut sels = vec![Selection::Cursor(lead(0, u32::MAX))];
        adjust_cursors(&mut sels, 0, 0, 0);
        assert_eq!(byte_at(&sels, 0), 0);
    }
    #[test]
    fn adjust_cursors_never_touches_range_selections() {
        let mut sels = vec![range_sel(lead(0, 4), lead(0, 8))];
        adjust_cursors(&mut sels, 0, 0, 100);
        match &sels[0] {
            Selection::Range(r) => {
                assert_eq!(r.start.cluster_id.start_byte_in_run, 4);
                assert_eq!(r.end.cluster_id.start_byte_in_run, 8);
            }
            Selection::Cursor(_) => panic!("range must stay a range"),
        }
    }
    // --------------------------------------------------- adjust_cursor_runs
    fn run_at(sels: &[Selection], i: usize) -> u32 {
        cursor_of(&sels[i]).cluster_id.source_run
    }
    #[test]
    fn adjust_cursor_runs_zero_change_returns_early() {
        let mut sels = vec![Selection::Cursor(lead(u32::MAX, 0))];
        adjust_cursor_runs(&mut sels, 0, 0);
        assert_eq!(
            run_at(&sels, 0),
            u32::MAX,
            "zero change must not touch runs"
        );
    }
    #[test]
    fn adjust_cursor_runs_shifts_only_runs_strictly_after_the_boundary() {
        let mut sels = vec![
            Selection::Cursor(lead(0, 0)), // before boundary -> untouched
            Selection::Cursor(lead(1, 0)), // AT boundary     -> untouched
            Selection::Cursor(lead(2, 0)), // after           -> -1
            Selection::Cursor(lead(3, 0)), // after           -> -1
        ];
        adjust_cursor_runs(&mut sels, 1, -1);
        assert_eq!(run_at(&sels, 0), 0);
        assert_eq!(run_at(&sels, 1), 1);
        assert_eq!(run_at(&sels, 2), 1);
        assert_eq!(run_at(&sels, 3), 2);
    }
    #[test]
    fn adjust_cursor_runs_positive_change_shifts_up() {
        let mut sels = vec![Selection::Cursor(lead(2, 0))];
        adjust_cursor_runs(&mut sels, 0, 3);
        assert_eq!(run_at(&sels, 0), 5);
    }
    #[test]
    fn adjust_cursor_runs_negative_overshoot_clamps_to_the_boundary_run() {
        let mut sels = vec![Selection::Cursor(lead(3, 0))];
        adjust_cursor_runs(&mut sels, 1, -100);
        assert_eq!(run_at(&sels, 0), 1, "never drops below the surviving run");
    }
    #[test]
    fn adjust_cursor_runs_i32_min_clamps_instead_of_wrapping() {
        // 3 + i32::MIN stays inside i32 (no overflow) and the clamp catches it.
        let mut sels = vec![Selection::Cursor(lead(3, 0))];
        adjust_cursor_runs(&mut sels, 2, i32::MIN);
        assert_eq!(run_at(&sels, 0), 2);
        let mut sels = vec![Selection::Cursor(lead(1, 0))];
        adjust_cursor_runs(&mut sels, 0, i32::MIN);
        assert_eq!(run_at(&sels, 0), 0);
    }
    #[test]
    fn adjust_cursor_runs_i32_max_is_inert_when_no_cursor_qualifies() {
        // Every cursor is at/below the boundary, so the huge delta is never applied.
        let mut sels = vec![Selection::Cursor(lead(0, 0)), Selection::Cursor(lead(5, 0))];
        adjust_cursor_runs(&mut sels, 5, i32::MAX);
        assert_eq!(run_at(&sels, 0), 0);
        assert_eq!(run_at(&sels, 1), 5);
    }
    #[test]
    fn adjust_cursor_runs_never_touches_range_selections() {
        let mut sels = vec![range_sel(lead(9, 0), lead(9, 1))];
        adjust_cursor_runs(&mut sels, 0, -5);
        match &sels[0] {
            Selection::Range(r) => assert_eq!(r.start.cluster_id.source_run, 9),
            Selection::Cursor(_) => panic!("range must stay a range"),
        }
    }
    // ---------------------------------------------------------- run_text_len
    #[test]
    fn run_text_len_counts_bytes_not_chars() {
        let content = vec![text("héllo")]; // é is 2 bytes -> 6 bytes, 5 chars
        assert_eq!(run_text_len(&content, 0), 6);
        assert_eq!(content_text_chars(&content), 5);
    }
    fn content_text_chars(content: &[InlineContent]) -> usize {
        content
            .iter()
            .map(|c| match c {
                InlineContent::Text(r) => r.text.chars().count(),
                _ => 0,
            })
            .sum()
    }
    #[test]
    fn run_text_len_zero_for_empty_missing_and_non_text_runs() {
        let content = vec![text(""), obj()];
        assert_eq!(run_text_len(&content, 0), 0, "empty text run");
        assert_eq!(run_text_len(&content, 1), 0, "non-text run");
        assert_eq!(run_text_len(&content, 2), 0, "one past the end");
        assert_eq!(run_text_len(&content, u32::MAX), 0, "u32::MAX index");
        assert_eq!(run_text_len(&[], 0), 0, "empty content");
    }
    // ------------------------------------------------------------- edit_text
    #[test]
    fn edit_text_empty_selections_returns_content_unchanged() {
        let content = vec![text("hello")];
        let (new_content, sels) = edit_text(&content, &[], &TextEdit::Insert("x".into()));
        assert_eq!(dump(&new_content), vec!["hello"]);
        assert!(sels.is_empty());
    }
    #[test]
    fn edit_text_on_empty_content_does_not_panic() {
        let (new_content, sels) = edit_text(
            &[],
            &[Selection::Cursor(lead(0, 0))],
            &TextEdit::Insert("x".into()),
        );
        assert!(new_content.is_empty());
        assert_eq!(sels.len(), 1, "the cursor survives, unmoved");
        assert_eq!(cursor_of(&sels[0]), lead(0, 0));
    }
    #[test]
    fn edit_text_out_of_range_cursor_is_a_noop_not_a_panic() {
        let content = vec![text("hi")];
        let (new_content, sels) = edit_text(
            &content,
            &[Selection::Cursor(lead(u32::MAX, 0))],
            &TextEdit::DeleteBackward,
        );
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(sels.len(), 1);
    }
    #[test]
    fn edit_text_multi_cursor_insert_keeps_both_cursors_correct() {
        // Two cursors in the same run: the earlier edit must shift the later cursor
        // by the ACTUAL byte delta (this is what adjust_cursors exists for).
        let content = vec![text("hello")];
        let sels = [Selection::Cursor(lead(0, 0)), Selection::Cursor(lead(0, 3))];
        let (new_content, new_sels) = edit_text(&content, &sels, &TextEdit::Insert("X".into()));
        assert_eq!(dump(&new_content), vec!["XhelXlo"]);
        assert_eq!(cursor_of(&new_sels[0]), lead(0, 1));
        assert_eq!(cursor_of(&new_sels[1]), lead(0, 5));
    }
    #[test]
    fn edit_text_multi_cursor_insert_shifts_by_multibyte_length_not_one() {
        // Inserting a 4-byte emoji must move the trailing cursor by 4 bytes.
        let content = vec![text("ab")];
        let sels = [Selection::Cursor(lead(0, 0)), Selection::Cursor(lead(0, 2))];
        let (new_content, new_sels) = edit_text(&content, &sels, &TextEdit::Insert("👍".into()));
        assert_eq!(dump(&new_content), vec!["👍ab👍"]);
        assert_eq!(cursor_of(&new_sels[0]), lead(0, 4));
        assert_eq!(cursor_of(&new_sels[1]), lead(0, 10)); // 4 + "ab" + 4
    }
    #[test]
    fn edit_text_backspace_with_a_range_deletes_the_range_only() {
        // Regression guard for the documented rule: Backspace on a selection removes
        // the selection, NOT the selection plus one more grapheme.
        let content = vec![text("hello")];
        let sel = [range_sel(lead(0, 1), lead(0, 3))];
        let (new_content, _) = edit_text(&content, &sel, &TextEdit::DeleteBackward);
        assert_eq!(dump(&new_content), vec!["hlo"]);
    }
    // ------------------------------------------------ apply_edit_to_selection
    #[test]
    fn apply_edit_range_insert_replaces_the_range() {
        let content = vec![text("hello")];
        let sel = range_sel(lead(0, 1), lead(0, 4));
        let (new_content, cursor) =
            apply_edit_to_selection(&content, &sel, &TextEdit::Insert("EY".into()));
        assert_eq!(dump(&new_content), vec!["hEYo"]);
        assert_eq!(cursor, lead(0, 3));
    }
    #[test]
    fn apply_edit_range_delete_forward_deletes_range_only() {
        let content = vec![text("hello")];
        let sel = range_sel(lead(0, 1), lead(0, 3));
        let (new_content, cursor) =
            apply_edit_to_selection(&content, &sel, &TextEdit::DeleteForward);
        assert_eq!(dump(&new_content), vec!["hlo"]);
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn apply_edit_cursor_insert_of_empty_string_only_moves_the_caret() {
        let content = vec![text("hello")];
        let sel = Selection::Cursor(lead(0, 2));
        let (new_content, cursor) =
            apply_edit_to_selection(&content, &sel, &TextEdit::Insert(String::new()));
        assert_eq!(dump(&new_content), vec!["hello"]);
        assert_eq!(cursor, lead(0, 2));
    }
    // ------------------------------------------------ cursor_byte_offset_in_run
    #[test]
    fn cursor_byte_offset_leading_clamps_past_the_end() {
        assert_eq!(cursor_byte_offset_in_run("hi", &lead(0, 999)), 2);
        assert_eq!(cursor_byte_offset_in_run("hi", &lead(0, u32::MAX)), 2);
        assert_eq!(cursor_byte_offset_in_run("", &lead(0, 5)), 0);
    }
    #[test]
    fn cursor_byte_offset_trailing_clamps_past_the_end() {
        assert_eq!(cursor_byte_offset_in_run("hi", &trail(0, 2)), 2);
        assert_eq!(cursor_byte_offset_in_run("hi", &trail(0, u32::MAX)), 2);
        assert_eq!(cursor_byte_offset_in_run("", &trail(0, 0)), 0);
    }
    #[test]
    fn cursor_byte_offset_trailing_lands_after_the_whole_grapheme() {
        // Combining sequence: "e" + U+0301 is one cluster of 3 bytes.
        assert_eq!(cursor_byte_offset_in_run("e\u{0301}x", &trail(0, 0)), 3);
        // A 4-byte astral char.
        assert_eq!(cursor_byte_offset_in_run("👍x", &trail(0, 0)), 4);
        // A ZWJ emoji family is ONE cluster — a char-wise implementation would
        // return 4 here instead of 18.
        assert_eq!(cursor_byte_offset_in_run(FAMILY, &trail(0, 0)), 18);
    }
    #[test]
    fn cursor_byte_offset_leading_is_the_raw_offset() {
        assert_eq!(cursor_byte_offset_in_run(FAMILY, &lead(0, 0)), 0);
        assert_eq!(cursor_byte_offset_in_run("abc", &lead(0, 1)), 1);
    }
    // ---------------------------------------------------------- delete_range
    #[test]
    fn delete_range_within_one_run() {
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(0, 3),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["hlo"]);
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn delete_range_backward_range_is_normalized() {
        // Right-to-left selection (Shift+Left / Shift+Home): start is AFTER end.
        // It must delete the same bytes as the forward range, not silently no-op.
        let content = vec![text("hello")];
        let backward = SelectionRange {
            start: lead(0, 3),
            end: lead(0, 1),
        };
        let (new_content, cursor) = delete_range(&content, &backward);
        assert_eq!(dump(&new_content), vec!["hlo"]);
        assert_eq!(cursor, lead(0, 1), "caret collapses to the LOW end");
    }
    #[test]
    fn delete_range_collapsed_range_deletes_nothing() {
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 2),
            end: lead(0, 2),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["hello"]);
        assert_eq!(cursor, lead(0, 2));
    }
    #[test]
    fn delete_range_select_all_with_trailing_end_covers_the_last_cluster() {
        // The end cursor of a select-all sits Trailing on the last cluster; the
        // affinity-aware offset is what makes the final grapheme part of the range.
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 0),
            end: trail(0, 4),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec![""]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_range_spanning_runs_merges_matching_styles() {
        let content = vec![text("abc"), text("def")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(1, 2),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["af"], "same style -> one run");
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn delete_range_spanning_runs_keeps_differing_styles_apart() {
        let content = vec![text_styled("abc", style_a()), text_styled("def", style_b())];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(1, 2),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(
            dump(&new_content),
            vec!["a", "f"],
            "styles differ -> no merge"
        );
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn delete_range_drops_the_runs_strictly_between_the_boundaries() {
        let content = vec![text("abc"), text("XYZ"), obj(), text("def")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(3, 2),
        };
        let (new_content, _) = delete_range(&content, &r);
        assert_eq!(
            dump(&new_content),
            vec!["af"],
            "middle text AND obj dropped"
        );
    }
    #[test]
    fn delete_range_over_a_single_non_text_item_removes_it() {
        let content = vec![text("ab"), obj(), text("cd")];
        // start != end (affinity differs) so the guard against a zero-width delete passes.
        let r = SelectionRange {
            start: lead(1, 0),
            end: trail(1, 0),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["ab", "cd"]);
        assert_eq!(cursor, lead(1, 0));
    }
    #[test]
    fn delete_range_collapsed_on_a_non_text_item_keeps_it() {
        let content = vec![text("ab"), obj()];
        let r = SelectionRange {
            start: lead(1, 0),
            end: lead(1, 0),
        };
        let (new_content, _) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["ab", "<obj>"]);
    }
    #[test]
    fn delete_range_out_of_bounds_runs_do_not_panic() {
        let content = vec![text("ab")];
        // Both ends past the end (same-run path).
        let r = SelectionRange {
            start: lead(99, 0),
            end: lead(99, 5),
        };
        let (new_content, _) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec!["ab"]);
        // Multi-run path with a bogus `hi_run` — the drain must be clamped.
        let r = SelectionRange {
            start: lead(0, 0),
            end: lead(u32::MAX, 0),
        };
        let (new_content, cursor) = delete_range(&content, &r);
        assert_eq!(dump(&new_content), vec![""]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_range_backward_across_runs_is_normalized() {
        let content = vec![text("abc"), text("def")];
        let backward = SelectionRange {
            start: lead(1, 2),
            end: lead(0, 1),
        };
        let (new_content, cursor) = delete_range(&content, &backward);
        assert_eq!(dump(&new_content), vec!["af"]);
        assert_eq!(cursor, lead(0, 1));
    }
    // ---------------------------------------------------------- insert_text
    #[test]
    fn insert_text_leading_inserts_before_the_cluster() {
        let content = vec![text("hello")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 2), "XY");
        assert_eq!(dump(&new_content), vec!["heXYllo"]);
        assert_eq!(cursor, lead(0, 4));
    }
    #[test]
    fn insert_text_trailing_inserts_after_the_whole_grapheme() {
        // Trailing on the 4-byte emoji must land at byte 4, not byte 1.
        let content = vec![text("👍z")];
        let (new_content, cursor) = insert_text(&content, &trail(0, 0), "X");
        assert_eq!(dump(&new_content), vec!["👍Xz"]);
        assert_eq!(cursor, lead(0, 5));
    }
    #[test]
    fn insert_text_trailing_past_the_end_appends() {
        let content = vec![text("hi")];
        let (new_content, cursor) = insert_text(&content, &trail(0, 999), "!");
        assert_eq!(dump(&new_content), vec!["hi!"]);
        assert_eq!(cursor, lead(0, 3));
    }
    #[test]
    fn insert_text_leading_past_the_end_clamps_to_the_end() {
        // CONTRACT CHANGE (2026-08-29): a Leading offset beyond the run used
        // to DROP the insert - the silent lost-keystroke channel, and the
        // same stale-cursor family whose delete twin ABORTED the app on
        // device. A stale past-end cursor now clamps to the end: the typed
        // character lands where the user was looking (after the text).
        let content = vec![text("hi")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 999), "!");
        assert_eq!(dump(&new_content), vec!["hi!"]);
        assert_eq!(cursor, lead(0, 3));
    }
    #[test]
    fn insert_text_into_missing_or_non_text_run_is_a_noop() {
        let content = vec![obj()];
        let (new_content, cursor) = insert_text(&content, &lead(0, 0), "x");
        assert_eq!(dump(&new_content), vec!["<obj>"]);
        assert_eq!(cursor, lead(0, 0));
        let (new_content, cursor) = insert_text(&content, &lead(u32::MAX, 0), "x");
        assert_eq!(dump(&new_content), vec!["<obj>"]);
        assert_eq!(cursor, lead(u32::MAX, 0));
        let (new_content, _) = insert_text(&[], &lead(0, 0), "x");
        assert!(new_content.is_empty());
    }
    #[test]
    fn insert_text_empty_string_leaves_the_text_alone() {
        let content = vec![text("hi")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 1), "");
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn insert_text_cursor_advances_by_bytes_not_chars() {
        let content = vec![text("")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 0), FAMILY);
        assert_eq!(dump(&new_content), vec![FAMILY]);
        assert_eq!(cursor, lead(0, 18));
    }
    #[test]
    fn insert_text_of_a_huge_string_does_not_panic() {
        let big = "a".repeat(200_000);
        let content = vec![text("hi")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 1), &big);
        assert_eq!(run_text_len(&new_content, 0), 200_002);
        assert_eq!(cursor, lead(0, 200_001));
    }
    #[test]
    fn insert_newline_splits_the_run_around_a_hard_line_break() {
        // Enter in the middle of a run: "hello|world" -> "hello" · <break> ·
        // "world", caret at the START of the new line. A raw '\n' left in the
        // run would shape to tofu.
        let content = vec![text("helloworld")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 5), "\n");
        assert_eq!(dump(&new_content), vec!["hello", "<obj>", "world"]);
        assert!(
            matches!(new_content.get(1), Some(InlineContent::LineBreak(_))),
            "the middle item must be a LineBreak, not a text run with '\\n'"
        );
        assert_eq!(cursor, lead(2, 0));
    }
    #[test]
    fn insert_newline_at_the_end_appends_an_empty_trailing_line() {
        let content = vec![text("hi")];
        let (new_content, cursor) = insert_text(&content, &trail(0, 999), "\n");
        assert_eq!(dump(&new_content), vec!["hi", "<obj>", ""]);
        assert_eq!(cursor, lead(2, 0));
    }
    #[test]
    fn insert_multiline_paste_emits_one_break_per_newline_with_the_tail_on_the_last_line() {
        // "X|Z" with "a\nb" pasted -> "Xa" · <break> · "bZ", caret between the
        // pasted "b" and the original tail "Z".
        let content = vec![text("XZ")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 1), "a\nb");
        assert_eq!(dump(&new_content), vec!["Xa", "<obj>", "bZ"]);
        assert_eq!(cursor, lead(2, 1));
    }
    #[test]
    fn insert_two_newlines_makes_a_blank_line_between_two_breaks() {
        let content = vec![text("ab")];
        let (new_content, cursor) = insert_text(&content, &lead(0, 1), "\n\n");
        // "a" · break · "" · break · "b"
        assert_eq!(dump(&new_content), vec!["a", "<obj>", "", "<obj>", "b"]);
        assert_eq!(cursor, lead(4, 0));
    }
    // ------------------------------------------------------- delete_backward
    #[test]
    fn delete_backward_on_empty_content_is_a_noop() {
        let (new_content, cursor) = delete_backward(&[], &lead(0, 0));
        assert!(new_content.is_empty());
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_backward_at_the_start_of_the_document_is_a_noop() {
        let content = vec![text("hi")];
        let (new_content, cursor) = delete_backward(&content, &lead(0, 0));
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_backward_removes_a_whole_grapheme_cluster() {
        let content = vec![text(&format!("a{FAMILY}"))];
        let (new_content, cursor) = delete_backward(&content, &lead(0, 19));
        assert_eq!(dump(&new_content), vec!["a"], "all 18 bytes go at once");
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn delete_backward_trailing_affinity_removes_the_current_cluster() {
        let content = vec![text("ab")];
        let (new_content, cursor) = delete_backward(&content, &trail(0, 0));
        assert_eq!(dump(&new_content), vec!["b"]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_backward_merges_across_a_run_boundary() {
        let content = vec![text("ab"), text("cd")];
        let (new_content, cursor) = delete_backward(&content, &lead(1, 0));
        assert_eq!(dump(&new_content), vec!["abcd"]);
        assert_eq!(cursor, lead(0, 2), "caret sits at the join point");
    }
    #[test]
    fn delete_backward_removes_a_non_text_item_sitting_before_the_caret() {
        let content = vec![text("ab"), obj(), text("cd")];
        let (new_content, cursor) = delete_backward(&content, &lead(2, 0));
        assert_eq!(dump(&new_content), vec!["ab", "cd"]);
        assert_eq!(cursor, lead(1, 0));
    }
    #[test]
    fn delete_backward_with_the_caret_after_a_non_text_item_removes_the_item() {
        let content = vec![text("ab"), obj()];
        let (new_content, _) = delete_backward(&content, &trail(1, 0));
        assert_eq!(dump(&new_content), vec!["ab"]);
    }
    #[test]
    fn delete_backward_with_the_caret_before_a_non_text_item_acts_on_the_previous_run() {
        let content = vec![text("ab"), obj()];
        let (new_content, cursor) = delete_backward(&content, &lead(1, 0));
        assert_eq!(dump(&new_content), vec!["a", "<obj>"], "the item survives");
        assert_eq!(cursor, lead(0, 1));
    }
    #[test]
    fn delete_backward_before_a_leading_non_text_item_at_run_zero_is_a_noop() {
        let content = vec![obj()];
        let (new_content, cursor) = delete_backward(&content, &lead(0, 0));
        assert_eq!(dump(&new_content), vec!["<obj>"]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_backward_out_of_range_run_is_a_noop() {
        let content = vec![text("hi")];
        let (new_content, cursor) = delete_backward(&content, &lead(u32::MAX, u32::MAX));
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(cursor, lead(u32::MAX, u32::MAX));
    }
    // -------------------------------------------------------- delete_forward
    #[test]
    fn delete_forward_on_empty_content_is_a_noop() {
        let (new_content, cursor) = delete_forward(&[], &lead(0, 0));
        assert!(new_content.is_empty());
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_forward_at_the_end_of_the_document_is_a_noop() {
        let content = vec![text("hi")];
        let (new_content, cursor) = delete_forward(&content, &lead(0, 2));
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(cursor, lead(0, 2));
    }
    #[test]
    fn delete_forward_removes_a_whole_grapheme_cluster() {
        let content = vec![text(&format!("{FAMILY}z"))];
        let (new_content, cursor) = delete_forward(&content, &lead(0, 0));
        assert_eq!(dump(&new_content), vec!["z"]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_forward_merges_across_a_run_boundary() {
        let content = vec![text("ab"), text("cd")];
        let (new_content, cursor) = delete_forward(&content, &lead(0, 2));
        assert_eq!(dump(&new_content), vec!["abcd"]);
        assert_eq!(cursor, lead(0, 2));
    }
    #[test]
    fn delete_forward_removes_a_non_text_item_sitting_after_the_caret() {
        let content = vec![text("ab"), obj()];
        let (new_content, _) = delete_forward(&content, &lead(0, 2));
        assert_eq!(dump(&new_content), vec!["ab"]);
    }
    #[test]
    fn delete_forward_with_the_caret_before_a_non_text_item_removes_the_item() {
        let content = vec![obj(), text("ab")];
        let (new_content, cursor) = delete_forward(&content, &lead(0, 0));
        assert_eq!(dump(&new_content), vec!["ab"]);
        assert_eq!(cursor, lead(0, 0));
    }
    #[test]
    fn delete_forward_with_the_caret_after_a_non_text_item_acts_on_the_next_run() {
        let content = vec![obj(), text("ab")];
        let (new_content, cursor) = delete_forward(&content, &trail(0, 0));
        assert_eq!(dump(&new_content), vec!["<obj>", "b"], "the item survives");
        assert_eq!(cursor, lead(1, 0));
    }
    #[test]
    fn delete_forward_after_a_trailing_non_text_item_at_the_last_run_is_a_noop() {
        let content = vec![text("ab"), obj()];
        let (new_content, cursor) = delete_forward(&content, &trail(1, 0));
        assert_eq!(dump(&new_content), vec!["ab", "<obj>"]);
        assert_eq!(cursor, trail(1, 0));
    }
    #[test]
    fn delete_forward_out_of_range_run_is_a_noop() {
        let content = vec![text("hi")];
        let (new_content, cursor) = delete_forward(&content, &lead(u32::MAX, u32::MAX));
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert_eq!(cursor, lead(u32::MAX, u32::MAX));
    }
    // ------------------------------------------------------- edit_text_multi
    #[test]
    #[should_panic(expected = "same length")]
    fn edit_text_multi_panics_on_a_length_mismatch() {
        // Documented in the function's `# Panics` section.
        let content = vec![text("hi")];
        let sels = [Selection::Cursor(lead(0, 0))];
        let _ = edit_text_multi(&content, &sels, &["a", "b"]);
    }
    #[test]
    fn edit_text_multi_with_no_selections_returns_content_unchanged() {
        let content = vec![text("hi")];
        let (new_content, sels) = edit_text_multi(&content, &[], &[]);
        assert_eq!(dump(&new_content), vec!["hi"]);
        assert!(sels.is_empty());
    }
    #[test]
    fn edit_text_multi_gives_each_cursor_its_own_text() {
        let content = vec![text("ab")];
        let sels = [Selection::Cursor(lead(0, 0)), Selection::Cursor(lead(0, 2))];
        let (new_content, new_sels) = edit_text_multi(&content, &sels, &["X", "Y"]);
        assert_eq!(dump(&new_content), vec!["XabY"]);
        assert_eq!(cursor_of(&new_sels[0]), lead(0, 1));
        assert_eq!(cursor_of(&new_sels[1]), lead(0, 4));
    }
    #[test]
    fn edit_text_multi_with_empty_texts_only_moves_the_carets() {
        let content = vec![text("ab")];
        let sels = [Selection::Cursor(lead(0, 0)), Selection::Cursor(lead(0, 1))];
        let (new_content, new_sels) = edit_text_multi(&content, &sels, &["", ""]);
        assert_eq!(dump(&new_content), vec!["ab"]);
        assert_eq!(new_sels.len(), 2);
    }
    // ---------------------------------------------------------- inspect_delete
    #[test]
    fn inspect_delete_forward_at_the_end_of_the_document_is_none() {
        let content = vec![text("hi")];
        assert!(inspect_delete(&content, &Selection::Cursor(lead(0, 2)), true).is_none());
        assert!(inspect_delete(&[], &Selection::Cursor(lead(0, 0)), true).is_none());
    }
    #[test]
    fn inspect_delete_backward_at_the_start_of_the_document_is_none() {
        let content = vec![text("hi")];
        assert!(inspect_delete(&content, &Selection::Cursor(lead(0, 0)), false).is_none());
        assert!(inspect_delete(&[], &Selection::Cursor(lead(0, 0)), false).is_none());
    }
    #[test]
    fn inspect_delete_forward_reports_exactly_what_delete_forward_removes() {
        let content = vec![text("héllo")]; // é starts at byte 1, 2 bytes long
        let cursor = lead(0, 1);
        let (_, reported) = inspect_delete(&content, &Selection::Cursor(cursor), true).unwrap();
        let (after, _) = delete_forward(&content, &cursor);
        assert_eq!(reported, "é");
        assert_eq!(dump(&after), vec!["hllo"], "inspect and delete agree");
    }
    #[test]
    fn inspect_delete_backward_reports_exactly_what_delete_backward_removes() {
        let content = vec![text(&format!("a{FAMILY}"))];
        let cursor = lead(0, 19);
        let (range, reported) =
            inspect_delete(&content, &Selection::Cursor(cursor), false).unwrap();
        let (after, _) = delete_backward(&content, &cursor);
        assert_eq!(reported, FAMILY, "the whole ZWJ cluster, not one codepoint");
        assert_eq!(range.start, lead(0, 1));
        assert_eq!(dump(&after), vec!["a"]);
    }
    #[test]
    fn inspect_delete_forward_honors_trailing_affinity() {
        // A Trailing cursor sits AFTER its grapheme, so Delete removes the NEXT one.
        let content = vec![text("abc")];
        let (_, reported) =
            inspect_delete(&content, &Selection::Cursor(trail(0, 0)), true).unwrap();
        assert_eq!(reported, "b");
    }
    #[test]
    fn inspect_delete_across_a_run_boundary_reports_the_neighbouring_grapheme() {
        let content = vec![text("ab"), text("cd")];
        let (_, fwd) = inspect_delete(&content, &Selection::Cursor(lead(0, 2)), true).unwrap();
        assert_eq!(fwd, "c");
        let (_, back) = inspect_delete(&content, &Selection::Cursor(lead(1, 0)), false).unwrap();
        assert_eq!(back, "b");
    }
    #[test]
    fn inspect_delete_reports_none_for_a_non_text_neighbour_that_delete_would_remove() {
        // BUG (reported): inspect_delete_forward/backward only match on a TEXT
        // neighbour, so they answer "nothing would be deleted" while
        // delete_forward/delete_backward actually remove the inline item. A callback
        // relying on inspect_delete to veto or log the edit sees nothing coming.
        let content = vec![text("ab"), obj()];
        assert!(inspect_delete(&content, &Selection::Cursor(lead(0, 2)), true).is_none());
        let (after, _) = delete_forward(&content, &lead(0, 2));
        assert_eq!(dump(&after), vec!["ab"], "...but the item IS removed");
        let content = vec![obj(), text("ab")];
        assert!(inspect_delete(&content, &Selection::Cursor(lead(1, 0)), false).is_none());
        let (after, _) = delete_backward(&content, &lead(1, 0));
        assert_eq!(dump(&after), vec!["ab"], "...but the item IS removed");
    }
    #[test]
    fn inspect_delete_on_a_range_returns_the_range_and_its_text() {
        let content = vec![text("hello")];
        let sel = range_sel(lead(0, 1), lead(0, 3));
        let (range, reported) = inspect_delete(&content, &sel, false).unwrap();
        assert_eq!(range.start, lead(0, 1));
        assert_eq!(range.end, lead(0, 3));
        assert_eq!(reported, "el");
        // ...and that is exactly what the delete removes.
        let (after, _) = apply_edit_to_selection(&content, &sel, &TextEdit::DeleteBackward);
        assert_eq!(dump(&after), vec!["hlo"]);
    }
    #[test]
    fn inspect_delete_out_of_range_cursor_is_none_not_a_panic() {
        let content = vec![text("hi")];
        assert!(inspect_delete(&content, &Selection::Cursor(lead(u32::MAX, 0)), true).is_none());
        assert!(inspect_delete(&content, &Selection::Cursor(lead(u32::MAX, 0)), false).is_none());
    }
    // ---------------------------------------------------- extract_text_in_range
    #[test]
    fn extract_text_in_range_single_run() {
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(0, 4),
        };
        assert_eq!(extract_text_in_range(&content, &r), "ell");
    }
    #[test]
    fn extract_text_in_range_multi_run_concatenates_the_span() {
        let content = vec![text("abc"), text("MID"), text("def")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(2, 2),
        };
        assert_eq!(extract_text_in_range(&content, &r), "bcMIDde");
    }
    #[test]
    fn extract_text_in_range_skips_non_text_items_in_the_span() {
        let content = vec![text("abc"), obj(), text("def")];
        let r = SelectionRange {
            start: lead(0, 1),
            end: lead(2, 2),
        };
        assert_eq!(extract_text_in_range(&content, &r), "bcde");
    }
    #[test]
    fn extract_text_in_range_out_of_bounds_yields_empty_string() {
        let content = vec![text("hi")];
        // end_byte past the run length.
        let r = SelectionRange {
            start: lead(0, 0),
            end: lead(0, 99),
        };
        assert_eq!(extract_text_in_range(&content, &r), "");
        // Both runs past the end.
        let r = SelectionRange {
            start: lead(9, 0),
            end: lead(9, 1),
        };
        assert_eq!(extract_text_in_range(&content, &r), "");
        // Empty content.
        let r = SelectionRange {
            start: lead(0, 0),
            end: lead(0, 1),
        };
        assert_eq!(extract_text_in_range(&[], &r), "");
    }
    #[test]
    fn extract_text_in_range_backward_single_run_yields_empty_string() {
        // Unlike delete_range, extract does NOT normalize direction — a
        // right-to-left selection inside one run reports no text at all.
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 3),
            end: lead(0, 1),
        };
        assert_eq!(extract_text_in_range(&content, &r), "");
    }
    #[test]
    fn extract_text_in_range_ignores_affinity_and_drops_the_last_cluster() {
        // BUG (reported): extract_text_in_range reads the RAW `start_byte_in_run`
        // while delete_range goes through cursor_byte_offset_in_run. On a select-all
        // (end cursor Trailing on the last cluster) inspect_delete therefore reports
        // one grapheme LESS than the delete actually removes.
        let content = vec![text("hello")];
        let r = SelectionRange {
            start: lead(0, 0),
            end: trail(0, 4),
        };
        assert_eq!(
            extract_text_in_range(&content, &r),
            "hell",
            "the 'o' is missing"
        );
        let (after, _) = delete_range(&content, &r);
        assert_eq!(
            dump(&after),
            vec![""],
            "...yet delete_range removes all of it"
        );
    }
}
#[cfg(test)]
mod edit_outcome_tests {
    use super::*;
3
    fn cursor0() -> Selection {
3
        Selection::Cursor(TextCursor {
3
            cluster_id: GraphemeClusterId {
3
                source_run: 0,
3
                start_byte_in_run: 0,
3
            },
3
            affinity: CursorAffinity::Leading,
3
        })
3
    }
3
    fn run(text: &str) -> InlineContent {
3
        InlineContent::Text(crate::text3::cache::StyledRun {
3
            text: alloc::sync::Arc::from(text),
3
            style: alloc::sync::Arc::new(Default::default()),
3
            logical_start_byte: 0,
3
            source_node_id: None,
3
        })
3
    }
    #[test]
1
    fn an_insert_with_no_selection_reports_the_reason() {
1
        assert_eq!(
1
            edit_text_outcome(&[run("abc")], &[], &TextEdit::Insert("x".into())),
            EditOutcome::NoOp(EditNoOp::NoSelection),
        );
1
    }
    #[test]
1
    fn an_insert_into_unseeded_empty_content_is_a_named_miss_not_a_success() {
        // The un-seeded empty editable: cursor at run 0 of NOTHING. The old
        // tuple return handed back unchanged content — "success" — and the
        // first character typed into a brand-new document vanished into undo
        // snapshots and cache writes. The reason is now explicit.
1
        assert_eq!(
1
            edit_text_outcome(&[], &[cursor0()], &TextEdit::Insert("H".into())),
            EditOutcome::NoOp(EditNoOp::EverySelectionMissed),
        );
1
    }
    #[test]
1
    fn a_backspace_at_the_document_start_is_a_named_miss() {
1
        assert_eq!(
1
            edit_text_outcome(&[run("abc")], &[cursor0()], &TextEdit::DeleteBackward),
            EditOutcome::NoOp(EditNoOp::EverySelectionMissed),
        );
1
    }
    #[test]
1
    fn an_applied_insert_reports_applied_with_the_new_content() {
        let EditOutcome::Applied {
1
            content,
1
            selections,
1
        } = edit_text_outcome(&[run("bc")], &[cursor0()], &TextEdit::Insert("a".into()))
        else {
            panic!("a real insert must be Applied");
        };
1
        assert_eq!(selections.len(), 1);
1
        let InlineContent::Text(r) = &content[0] else {
            panic!()
        };
1
        assert_eq!(&*r.text, "abc");
1
    }
}