1
//! Text selection helper functions
2
//!
3
//! Provides word and paragraph selection algorithms.
4

            
5
use azul_core::selection::{CursorAffinity, GraphemeClusterId, SelectionRange, TextCursor};
6

            
7
use crate::text3::cache::{is_word_char, BreakType, ShapedCluster, ShapedItem, UnifiedLayout};
8

            
9
/// Select the word at the given cursor position
10
///
11
/// Uses a simple word character heuristic (alphanumeric and underscore)
12
/// to determine word start/end. Returns a `SelectionRange` covering the entire word.
13
#[must_use]
14
218
pub fn select_word_at_cursor(
15
218
    cursor: &TextCursor,
16
218
    layout: &UnifiedLayout,
17
218
) -> Option<SelectionRange> {
18
    // Find the item containing this cursor
19
218
    let (item_idx, _cluster) = find_cluster_at_cursor(cursor, layout)?;
20

            
21
    // Get text and cluster mapping for this line
22
215
    let (line_text, cluster_map) = extract_line_text_and_clusters(item_idx, layout);
23

            
24
    // Compute byte offset within concatenated line text
25
215
    let cursor_byte_offset = cluster_map
26
215
        .iter()
27
5283
        .take_while(|(id, _)| *id != cursor.cluster_id)
28
215
        .map(|(_, len)| len)
29
215
        .sum::<usize>();
30

            
31
    // Find word boundaries in the concatenated text
32
215
    let (word_start, word_end) = find_word_boundaries(&line_text, cursor_byte_offset);
33

            
34
    // Map byte offsets back to cluster IDs
35
215
    let start_cluster_id = byte_offset_to_cluster_id(&cluster_map, word_start)?;
36
215
    let end_cluster_id = byte_offset_to_cluster_id(&cluster_map, word_end.saturating_sub(1))
37
215
        .unwrap_or(start_cluster_id);
38

            
39
215
    Some(SelectionRange {
40
215
        start: TextCursor {
41
215
            cluster_id: start_cluster_id,
42
215
            affinity: CursorAffinity::Leading,
43
215
        },
44
215
        end: TextCursor {
45
215
            cluster_id: end_cluster_id,
46
215
            affinity: CursorAffinity::Trailing,
47
215
        },
48
215
    })
49
218
}
50

            
51
/// Select the paragraph at the given cursor position (triple-click).
52
///
53
/// Returns a `SelectionRange` covering the whole paragraph the cursor is in,
54
/// in LOGICAL order, from its first to its last grapheme cluster.
55
///
56
/// "Paragraph" is the run of inline content between HARD breaks (`<br>`, a
57
/// preserved newline) — soft wraps do not divide it. Two consequences, both of
58
/// which the old `line_index` filter got wrong:
59
///   * a wrapped paragraph selects whole instead of one visual line (no editor selects a
60
///     soft-wrapped fragment on triple-click), and
61
///   * a visually reordered (bidi/RTL) paragraph yields `start <= end`, because the endpoints are
62
///     taken in logical order rather than from the ends of the visual item vector — an inverted
63
///     range mis-highlights, as `get_selection_rects` walks logically.
64
///
65
/// Same gathering discipline as [`extract_line_text_and_clusters`], which fixed
66
/// this class for WORD selection: work on the logical sequence, not on one
67
/// visual line.
68
#[must_use]
69
225
pub fn select_paragraph_at_cursor(
70
225
    cursor: &TextCursor,
71
225
    layout: &UnifiedLayout,
72
225
) -> Option<SelectionRange> {
73
    // Find the item containing this cursor
74
225
    let (_, cursor_cluster) = find_cluster_at_cursor(cursor, layout)?;
75
222
    let cursor_run = cursor_cluster.source_cluster_id.source_run;
76

            
77
    // Hard breaks occupy their OWN slot in the inline-content array, and every
78
    // cluster carries that array index as `source_run` — so a break's run index
79
    // is a boundary in the same coordinate the clusters are ordered by. Take
80
    // the nearest one on each side of the cursor's run; either may be absent
81
    // (the paragraph reaches the start/end of the IFC).
82
222
    let mut before: Option<u32> = None;
83
222
    let mut after: Option<u32> = None;
84
1987
    for item in &layout.items {
85
1765
        let ShapedItem::Break { source, break_info } = &item.item else {
86
1758
            continue;
87
        };
88
7
        if break_info.break_type != BreakType::Hard {
89
1
            continue;
90
6
        }
91
6
        let run = source.run_index;
92
6
        match run.cmp(&cursor_run) {
93
            core::cmp::Ordering::Less => {
94
3
                before = Some(before.map_or(run, |b: u32| b.max(run)));
95
            }
96
            core::cmp::Ordering::Greater => {
97
3
                after = Some(after.map_or(run, |a: u32| a.min(run)));
98
            }
99
            core::cmp::Ordering::Equal => {}
100
        }
101
    }
102

            
103
    // Logical extremes of every cluster inside those bounds. `GraphemeClusterId`
104
    // orders by (source_run, start_byte_in_run), which IS logical order.
105
222
    let mut first: Option<GraphemeClusterId> = None;
106
222
    let mut last: Option<GraphemeClusterId> = None;
107
1756
    for cluster in layout
108
222
        .items
109
222
        .iter()
110
1765
        .filter_map(|item| item.item.as_cluster())
111
    {
112
1756
        let id = cluster.source_cluster_id;
113
1756
        if before.is_some_and(|b| id.source_run <= b) || after.is_some_and(|a| id.source_run >= a) {
114
10
            continue;
115
1746
        }
116
1746
        if first.is_none_or(|f| id < f) {
117
226
            first = Some(id);
118
1520
        }
119
1746
        if last.is_none_or(|l| id > l) {
120
1742
            last = Some(id);
121
1742
        }
122
    }
123

            
124
    Some(SelectionRange {
125
        start: TextCursor {
126
222
            cluster_id: first?,
127
222
            affinity: CursorAffinity::Leading,
128
        },
129
        end: TextCursor {
130
222
            cluster_id: last?,
131
222
            affinity: CursorAffinity::Trailing,
132
        },
133
    })
134
225
}
135

            
136
// Helper Functions
137

            
138
/// Find the cluster containing the given cursor
139
450
fn find_cluster_at_cursor<'a>(
140
450
    cursor: &TextCursor,
141
450
    layout: &'a UnifiedLayout,
142
450
) -> Option<(usize, &'a ShapedCluster)> {
143
6304
    layout.items.iter().enumerate().find_map(|(idx, item)| {
144
6304
        if let ShapedItem::Cluster(cluster) = &item.item {
145
6299
            if cluster.source_cluster_id == cursor.cluster_id {
146
439
                return Some((idx, cluster));
147
5860
            }
148
5
        }
149
5865
        None
150
6304
    })
151
450
}
152

            
153
/// Extract text and cluster ID mapping for the cursor's logical run.
154
///
155
/// Returns concatenated text and a vec of (`cluster_id`, `byte_length`) pairs
156
/// so byte offsets can be mapped back to cluster IDs.
157
///
158
/// Clusters are gathered by their logical run (`source_run`) and concatenated in
159
/// LOGICAL byte order — NOT visual (`layout.items`) order, and NOT restricted to a
160
/// single visual line. This makes word segmentation correct in two cases the old
161
/// per-visual-line code broke:
162
///   * bidi text, where visual order differs from logical order, so word boundaries computed on the
163
///     visual concatenation mapped back to the wrong clusters, and
164
///   * a word split across a soft wrap, where filtering to one `line_index` only selected the
165
///     fragment on the clicked line.
166
222
fn extract_line_text_and_clusters(
167
222
    item_idx: usize,
168
222
    layout: &UnifiedLayout,
169
222
) -> (String, Vec<(GraphemeClusterId, usize)>) {
170
222
    let Some(source_run) = layout.items[item_idx]
171
222
        .item
172
222
        .as_cluster()
173
222
        .map(|c| c.source_cluster_id.source_run)
174
    else {
175
1
        return (String::new(), Vec::new());
176
    };
177

            
178
    // Gather every cluster of this logical run across all visual lines, then sort
179
    // into logical order so segmentation runs on the real character sequence.
180
221
    let mut clusters: Vec<&ShapedCluster> = layout
181
221
        .items
182
221
        .iter()
183
10548
        .filter_map(|item| item.item.as_cluster())
184
10548
        .filter(|c| c.source_cluster_id.source_run == source_run)
185
221
        .collect();
186
221
    clusters.sort_by_key(|c| c.source_cluster_id.start_byte_in_run);
187

            
188
221
    let mut text = String::new();
189
221
    let mut cluster_map = Vec::new();
190
10766
    for c in clusters {
191
10545
        let s = c.text();
192
10545
        cluster_map.push((c.source_cluster_id, s.len()));
193
10545
        text.push_str(s);
194
10545
    }
195

            
196
221
    (text, cluster_map)
197
222
}
198

            
199
/// Map a byte offset in concatenated line text back to a cluster ID.
200
472
fn byte_offset_to_cluster_id(
201
472
    cluster_map: &[(GraphemeClusterId, usize)],
202
472
    byte_offset: usize,
203
472
) -> Option<GraphemeClusterId> {
204
472
    let mut cumulative = 0;
205
10838
    for (id, len) in cluster_map {
206
10813
        if byte_offset < cumulative + len {
207
447
            return Some(*id);
208
10366
        }
209
10366
        cumulative += len;
210
    }
211
25
    cluster_map.last().map(|(id, _)| *id)
212
472
}
213

            
214
/// Find word boundaries around the given byte offset
215
///
216
/// Uses a simple algorithm: word characters are alphanumeric or underscore,
217
/// everything else is a boundary.
218
524
fn find_word_boundaries(text: &str, cursor_offset: usize) -> (usize, usize) {
219
    // Clamp cursor offset to text length
220
524
    let cursor_offset = cursor_offset.min(text.len());
221

            
222
    // Find word start (scan backwards)
223
524
    let mut word_start = 0;
224
524
    let char_indices: Vec<(usize, char)> = text.char_indices().collect();
225

            
226
72937
    for (i, (byte_idx, ch)) in char_indices.iter().enumerate().rev() {
227
72937
        if *byte_idx >= cursor_offset {
228
6155
            continue;
229
66782
        }
230

            
231
66782
        if !is_word_char(*ch) {
232
            // Found boundary, word starts after this char
233
276
            word_start = if i + 1 < char_indices.len() {
234
215
                char_indices[i + 1].0
235
            } else {
236
61
                text.len()
237
            };
238
276
            break;
239
66506
        }
240
    }
241

            
242
    // Find word end (scan forwards)
243
524
    let mut word_end = text.len();
244
139076
    for (byte_idx, ch) in &char_indices {
245
138741
        if *byte_idx <= cursor_offset {
246
137791
            continue;
247
950
        }
248

            
249
950
        if !is_word_char(*ch) {
250
            // Found boundary, word ends before this char
251
189
            word_end = *byte_idx;
252
189
            break;
253
761
        }
254
    }
255

            
256
    // If cursor is on whitespace, select just that whitespace
257
137942
    if let Some((_, ch)) = char_indices.iter().find(|(idx, _)| *idx == cursor_offset) {
258
328
        if !is_word_char(*ch) {
259
            // Find span of consecutive whitespace/punctuation
260
84
            let start = char_indices
261
84
                .iter()
262
84
                .rev()
263
2467
                .find(|(idx, c)| *idx < cursor_offset && is_word_char(*c))
264
84
                .map_or(0, |(idx, c)| idx + c.len_utf8());
265

            
266
84
            let end = char_indices
267
84
                .iter()
268
2492
                .find(|(idx, c)| *idx > cursor_offset && is_word_char(*c))
269
84
                .map_or(text.len(), |(idx, _)| *idx);
270

            
271
84
            return (start, end);
272
244
        }
273
196
    }
274

            
275
440
    (word_start, word_end)
276
524
}
277

            
278
// Word-character classification is shared with cursor word-motion via
279
// `cache::is_word_char` (imported above) so selection and Ctrl/Alt+Arrow agree
280
// on punctuation. Kept distinct from `cache::is_word_separator`, which is for
281
// word-spacing justification, not segmentation.
282

            
283
#[cfg(test)]
284
mod tests {
285
    use super::*;
286

            
287
    #[test]
288
1
    fn test_word_boundaries_simple() {
289
1
        let text = "Hello World";
290
1
        let (start, end) = find_word_boundaries(text, 2);
291
1
        assert_eq!(&text[start..end], "Hello");
292

            
293
1
        let (start, end) = find_word_boundaries(text, 7);
294
1
        assert_eq!(&text[start..end], "World");
295

            
296
1
        let (start, end) = find_word_boundaries(text, 5);
297
1
        assert_eq!(&text[start..end], " ");
298
1
    }
299

            
300
    #[test]
301
1
    fn test_word_boundaries_start_end() {
302
1
        let text = "Hello";
303
1
        let (start, end) = find_word_boundaries(text, 0);
304
1
        assert_eq!(&text[start..end], "Hello");
305

            
306
1
        let (start, end) = find_word_boundaries(text, 5);
307
1
        assert_eq!(&text[start..end], "Hello");
308
1
    }
309

            
310
    #[test]
311
1
    fn test_word_boundaries_punctuation() {
312
1
        let text = "Hello, World!";
313
1
        let (start, end) = find_word_boundaries(text, 2);
314
1
        assert_eq!(&text[start..end], "Hello");
315

            
316
1
        let (start, end) = find_word_boundaries(text, 5);
317
1
        assert_eq!(&text[start..end], ", ");
318

            
319
1
        let (start, end) = find_word_boundaries(text, 8);
320
1
        assert_eq!(&text[start..end], "World");
321
1
    }
322

            
323
    #[test]
324
1
    fn test_word_boundaries_underscore() {
325
1
        let text = "hello_world";
326
1
        let (start, end) = find_word_boundaries(text, 5);
327
1
        assert_eq!(&text[start..end], "hello_world");
328
1
    }
329

            
330
    #[test]
331
1
    fn test_is_word_char() {
332
1
        assert!(is_word_char('a'));
333
1
        assert!(is_word_char('Z'));
334
1
        assert!(is_word_char('0'));
335
1
        assert!(is_word_char('_'));
336
1
        assert!(!is_word_char(' '));
337
1
        assert!(!is_word_char(','));
338
1
        assert!(!is_word_char('!'));
339
1
    }
340

            
341
    #[test]
342
1
    fn test_word_boundaries_empty() {
343
1
        let (start, end) = find_word_boundaries("", 0);
344
1
        assert_eq!(start, 0);
345
1
        assert_eq!(end, 0);
346
1
    }
347

            
348
    #[test]
349
1
    fn test_byte_offset_to_cluster_id_basic() {
350
1
        let id0 = GraphemeClusterId {
351
1
            source_run: 0,
352
1
            start_byte_in_run: 0,
353
1
        };
354
1
        let id1 = GraphemeClusterId {
355
1
            source_run: 0,
356
1
            start_byte_in_run: 5,
357
1
        };
358
1
        let id2 = GraphemeClusterId {
359
1
            source_run: 0,
360
1
            start_byte_in_run: 6,
361
1
        };
362
1
        let map = vec![(id0, 5), (id1, 1), (id2, 5)];
363

            
364
1
        assert_eq!(byte_offset_to_cluster_id(&map, 0), Some(id0));
365
1
        assert_eq!(byte_offset_to_cluster_id(&map, 4), Some(id0));
366
1
        assert_eq!(byte_offset_to_cluster_id(&map, 5), Some(id1));
367
1
        assert_eq!(byte_offset_to_cluster_id(&map, 6), Some(id2));
368
1
        assert_eq!(byte_offset_to_cluster_id(&map, 100), Some(id2));
369
1
    }
370
}
371

            
372
/// Adversarial unit tests generated for `layout/src/text3/selection.rs`.
373
///
374
/// These push the selection helpers at the boundaries the production callers never
375
/// reach: `usize::MAX` byte offsets, offsets that land *inside* a multi-byte char,
376
/// zero-length clusters, empty layouts, cluster ids that do not exist, visually
377
/// reordered (bidi) item vectors, words split across a soft wrap, and cluster
378
/// metadata that contradicts the cluster text. Where the current behaviour is
379
/// surprising but real (an empty range for a trailing boundary char; a combining
380
/// mark splitting a word) the test PINS that behaviour and says so rather than
381
/// pretending it is correct.
382
#[cfg(test)]
383
#[allow(
384
    clippy::cast_possible_truncation,
385
    clippy::similar_names,
386
    clippy::too_many_lines
387
)]
388
mod autotest_generated {
389
    use std::sync::Arc;
390

            
391
    use azul_core::selection::ContentIndex;
392

            
393
    use super::*;
394
    use crate::text3::cache::{
395
        BidiDirection, ClearType, InlineBreak, OverflowInfo, Point, PositionedItem, Rect,
396
        ShapedGlyphVec, StyleProperties,
397
    };
398

            
399
    // ------------------------------------------------------------------
400
    // Fixtures
401
    // ------------------------------------------------------------------
402

            
403
    const fn gid(run: u32, byte: u32) -> GraphemeClusterId {
404
        GraphemeClusterId {
405
            source_run: run,
406
            start_byte_in_run: byte,
407
        }
408
    }
409

            
410
    const fn ci(run: u32, item: u32) -> ContentIndex {
411
        ContentIndex {
412
            run_index: run,
413
            item_index: item,
414
        }
415
    }
416

            
417
    fn cluster(text: &str, id: GraphemeClusterId) -> ShapedCluster {
418
        ShapedCluster {
419
            flags: crate::text3::cache::ClusterFlags::classify(text),
420
            source_text: {
421
                // Test helper: pad so the slice at the given id's offset
422
                // yields exactly `text` (production stamps a shared Arc
423
                // whose offsets are real; tests mint ids freely).
424
                let mut s = String::new();
425
                for _ in 0..id.start_byte_in_run {
426
                    s.push(' ');
427
                }
428
                s.push_str(text);
429
                Arc::from(s.as_str())
430
            },
431
            source_byte_len: text.len() as u16,
432
            source_cluster_id: id,
433
            source_content_index: ci(id.source_run, id.start_byte_in_run),
434
            source_node_id: None,
435
            glyphs: ShapedGlyphVec::new(),
436
            advance: 10.0,
437
            direction: BidiDirection::Ltr,
438
            style: Arc::new(StyleProperties::default()),
439
            marker_position_outside: None,
440
            is_first_fragment: true,
441
            is_last_fragment: true,
442
        }
443
    }
444

            
445
    /// A cluster item on `line`.
446
    fn cl(text: &str, id: GraphemeClusterId, line: usize) -> PositionedItem {
447
        PositionedItem {
448
            item: ShapedItem::Cluster(cluster(text, id)),
449
            position: Point::default(),
450
            line_index: line,
451
        }
452
    }
453

            
454
    /// A forced break occupying inline-content slot `run` (its own slot, like
455
    /// production: `<br>` / a preserved newline is an `InlineContent::LineBreak`
456
    /// between the text runs it separates).
457
    fn hard_break(run: u32, line: usize) -> PositionedItem {
458
        break_item(run, line, BreakType::Hard)
459
    }
460

            
461
    /// A soft wrap opportunity — NOT a paragraph boundary.
462
    fn soft_break(run: u32, line: usize) -> PositionedItem {
463
        break_item(run, line, BreakType::Soft)
464
    }
465

            
466
    fn break_item(run: u32, line: usize, break_type: BreakType) -> PositionedItem {
467
        PositionedItem {
468
            item: ShapedItem::Break {
469
                source: ci(run, 0),
470
                break_info: InlineBreak {
471
                    break_type,
472
                    clear: ClearType::None,
473
                    content_index: 0,
474
                },
475
            },
476
            position: Point::default(),
477
            line_index: line,
478
        }
479
    }
480

            
481
    /// A non-cluster item (`as_cluster()` returns `None`) on `line`.
482
    fn tab(line: usize) -> PositionedItem {
483
        PositionedItem {
484
            item: ShapedItem::Tab {
485
                source: ci(0, 0),
486
                bounds: Rect::default(),
487
            },
488
            position: Point::default(),
489
            line_index: line,
490
        }
491
    }
492

            
493
    fn layout_of(items: Vec<PositionedItem>) -> UnifiedLayout {
494
        UnifiedLayout {
495
            items,
496
            overflow: OverflowInfo::default(),
497
        }
498
    }
499

            
500
    /// One cluster per `char` of `text`, all in `run`, all on line 0, with
501
    /// `start_byte_in_run` equal to the real logical byte offset of the char.
502
    fn layout_from_str(text: &str, run: u32) -> UnifiedLayout {
503
        layout_of(
504
            text.char_indices()
505
                .map(|(byte_idx, ch)| {
506
                    let mut buf = [0u8; 4];
507
                    cl(ch.encode_utf8(&mut buf), gid(run, byte_idx as u32), 0)
508
                })
509
                .collect(),
510
        )
511
    }
512

            
513
    const fn cursor_at(id: GraphemeClusterId) -> TextCursor {
514
        TextCursor {
515
            cluster_id: id,
516
            affinity: CursorAffinity::Leading,
517
        }
518
    }
519

            
520
    /// Strings chosen to break byte/char assumptions: ASCII, CJK (alphanumeric,
521
    /// 3 bytes), emoji (NOT alphanumeric, 4 bytes), Arabic (RTL), NBSP (a 2-byte
522
    /// *non*-word char), a combining mark, and pathological all-boundary input.
523
    const NASTY: &[&str] = &[
524
        "",
525
        " ",
526
        "_",
527
        "a",
528
        "!",
529
        "Hello World",
530
        "Hello, World!",
531
        "  ",
532
        "ab ",
533
        " ab",
534
        "héllo wörld",
535
        "日本語のテキスト",
536
        "👍👍",
537
        "a👍b",
538
        "مرحبا بالعالم",
539
        "a\u{00A0}b",
540
        "a\u{0301}b",
541
        "!!!???",
542
        "foo_bar42",
543
        "\n\t\r ",
544
    ];
545

            
546
    // ------------------------------------------------------------------
547
    // find_word_boundaries — numeric: zero / min_max / overflow / unicode
548
    // ------------------------------------------------------------------
549

            
550
    #[test]
551
    fn word_boundaries_empty_text_at_any_offset_is_zero_zero() {
552
        for off in [0, 1, 7, usize::MAX / 2, usize::MAX] {
553
            assert_eq!(
554
                find_word_boundaries("", off),
555
                (0, 0),
556
                "empty text must collapse to (0, 0) for offset {off}"
557
            );
558
        }
559
    }
560

            
561
    #[test]
562
    fn word_boundaries_usize_max_offset_is_clamped_to_text_len() {
563
        let text = "Hello World";
564
        let at_max = find_word_boundaries(text, usize::MAX);
565
        let at_len = find_word_boundaries(text, text.len());
566

            
567
        assert_eq!(at_max, at_len, "usize::MAX must clamp to text.len()");
568
        assert_eq!(&text[at_max.0..at_max.1], "World");
569
    }
570

            
571
    /// The load-bearing safety invariant: whatever offset it is handed — including
572
    /// offsets *inside* a multi-byte char and offsets past the end — the returned
573
    /// pair must be sliceable, ordered, and on char boundaries. Callers slice
574
    /// `&text[start..end]`, so a violation here is an immediate panic in the caller.
575
    #[test]
576
    fn word_boundaries_invariants_hold_for_every_offset_of_nasty_unicode() {
577
        for &text in NASTY {
578
            let probes = (0..=text.len() + 4)
579
                .chain([usize::MAX - 1, usize::MAX])
580
                .collect::<Vec<_>>();
581

            
582
            for off in probes {
583
                let (start, end) = find_word_boundaries(text, off);
584

            
585
                assert!(
586
                    start <= end,
587
                    "{text:?} @ {off}: start {start} > end {end} (inverted range)"
588
                );
589
                assert!(
590
                    end <= text.len(),
591
                    "{text:?} @ {off}: end {end} past len {}",
592
                    text.len()
593
                );
594
                assert!(
595
                    text.is_char_boundary(start),
596
                    "{text:?} @ {off}: start {start} splits a char"
597
                );
598
                assert!(
599
                    text.is_char_boundary(end),
600
                    "{text:?} @ {off}: end {end} splits a char"
601
                );
602
                // Must not panic — this is what every caller does with the result.
603
                let _slice = &text[start..end];
604
            }
605
        }
606
    }
607

            
608
    #[test]
609
    fn word_boundaries_offset_inside_multibyte_char_does_not_split_it() {
610
        // 'é' occupies bytes 1..3; offset 2 is *inside* it.
611
        let text = "héllo";
612
        let (start, end) = find_word_boundaries(text, 2);
613
        assert_eq!(&text[start..end], "héllo");
614

            
615
        // NBSP occupies bytes 1..3 and is NOT a word char; offset 2 is inside it.
616
        let text = "a\u{00A0}b";
617
        let (start, end) = find_word_boundaries(text, 2);
618
        assert!(text.is_char_boundary(start) && text.is_char_boundary(end));
619
        assert_eq!(&text[start..end], "b");
620
    }
621

            
622
    /// PINNED QUIRK: an offset that sits *after* a trailing boundary char (only
623
    /// reachable by a direct call, not through a cluster id) yields the empty
624
    /// range `(len, len)` rather than selecting the trailing whitespace.
625
    #[test]
626
    fn word_boundaries_offset_past_trailing_boundary_char_yields_empty_range() {
627
        let text = "ab ";
628
        assert_eq!(find_word_boundaries(text, 3), (3, 3));
629
        assert_eq!(&text[3..3], "");
630
    }
631

            
632
    /// PINNED QUIRK: `is_word_char` is `is_alphanumeric() || '_'`, and a combining
633
    /// mark (category Mn) is neither — so decomposed "á" is segmented as TWO words.
634
    /// NFC "á" (a single precomposed alphanumeric char) is not. Real Unicode
635
    /// weakness of the heuristic; recorded, not worked around.
636
    #[test]
637
    fn word_boundaries_combining_mark_splits_a_word() {
638
        let decomposed = "a\u{0301}b"; // a + COMBINING ACUTE + b
639
        let (start, end) = find_word_boundaries(decomposed, 0);
640
        assert_eq!(
641
            &decomposed[start..end],
642
            "a",
643
            "combining mark is treated as a word boundary"
644
        );
645

            
646
        let precomposed = "áb";
647
        let (start, end) = find_word_boundaries(precomposed, 0);
648
        assert_eq!(&precomposed[start..end], "áb");
649
    }
650

            
651
    #[test]
652
    fn word_boundaries_emoji_is_a_boundary_char_cjk_is_a_word_char() {
653
        // Emoji are not alphanumeric → boundary run selected whole.
654
        let emoji = "👍👍";
655
        assert_eq!(find_word_boundaries(emoji, 0), (0, emoji.len()));
656

            
657
        // Ideographs ARE alphanumeric → one word.
658
        let cjk = "日本語";
659
        let (start, end) = find_word_boundaries(cjk, 3);
660
        assert_eq!(&cjk[start..end], "日本語");
661

            
662
        // Emoji between words acts as a separator.
663
        let mixed = "a👍b";
664
        let (start, end) = find_word_boundaries(mixed, 0);
665
        assert_eq!(&mixed[start..end], "a");
666
    }
667

            
668
    #[test]
669
    fn word_boundaries_all_boundary_chars_selects_the_whole_run() {
670
        let text = "!!!???";
671
        assert_eq!(find_word_boundaries(text, 0), (0, 6));
672
        assert_eq!(find_word_boundaries(text, 3), (0, 6));
673
        assert_eq!(find_word_boundaries(text, 5), (0, 6));
674
    }
675

            
676
    #[test]
677
    fn word_boundaries_huge_text_with_max_offset_does_not_overflow() {
678
        let text = "a".repeat(64 * 1024);
679
        let (start, end) = find_word_boundaries(&text, usize::MAX);
680
        assert_eq!((start, end), (0, text.len()));
681

            
682
        // …and the same for a huge all-boundary text.
683
        let sep = " ".repeat(64 * 1024);
684
        let (start, end) = find_word_boundaries(&sep, usize::MAX);
685
        assert!(start <= end && end <= sep.len());
686
    }
687

            
688
    // ------------------------------------------------------------------
689
    // byte_offset_to_cluster_id — numeric: zero / min_max / overflow
690
    // ------------------------------------------------------------------
691

            
692
    #[test]
693
    fn byte_offset_to_cluster_id_empty_map_is_none_for_every_offset() {
694
        for off in [0, 1, usize::MAX / 2, usize::MAX] {
695
            assert_eq!(byte_offset_to_cluster_id(&[], off), None);
696
        }
697
    }
698

            
699
    /// Non-empty map ⇒ ALWAYS `Some` (offsets past the end fall back to the last
700
    /// cluster). Exhaustive over every offset in and beyond the mapped range.
701
    #[test]
702
    fn byte_offset_to_cluster_id_non_empty_map_is_always_some() {
703
        let map = [(gid(0, 0), 3), (gid(0, 3), 1), (gid(0, 4), 2)];
704
        let total: usize = map.iter().map(|(_, l)| l).sum();
705

            
706
        for off in (0..=total + 8).chain([usize::MAX - 1, usize::MAX]) {
707
            assert!(
708
                byte_offset_to_cluster_id(&map, off).is_some(),
709
                "offset {off} returned None for a non-empty map"
710
            );
711
        }
712
        assert_eq!(byte_offset_to_cluster_id(&map, 0), Some(gid(0, 0)));
713
        assert_eq!(byte_offset_to_cluster_id(&map, total - 1), Some(gid(0, 4)));
714
        assert_eq!(byte_offset_to_cluster_id(&map, usize::MAX), Some(gid(0, 4)));
715
    }
716

            
717
    /// PINNED QUIRK: a zero-length cluster is *unaddressable* — `offset < cum + 0`
718
    /// is never true — so it is silently skipped and the next cluster wins.
719
    #[test]
720
    fn byte_offset_to_cluster_id_zero_length_clusters_are_skipped() {
721
        let map = [(gid(0, 0), 0), (gid(0, 1), 2), (gid(0, 3), 0)];
722

            
723
        assert_eq!(
724
            byte_offset_to_cluster_id(&map, 0),
725
            Some(gid(0, 1)),
726
            "leading zero-length cluster must be skipped, not returned"
727
        );
728
        assert_eq!(byte_offset_to_cluster_id(&map, 1), Some(gid(0, 1)));
729
        // Past the end → last entry, even though the last entry is zero-length.
730
        assert_eq!(byte_offset_to_cluster_id(&map, 2), Some(gid(0, 3)));
731
    }
732

            
733
    #[test]
734
    fn byte_offset_to_cluster_id_all_zero_length_map_returns_last_never_none() {
735
        let map = [(gid(0, 0), 0), (gid(0, 1), 0), (gid(0, 2), 0)];
736
        for off in [0, 1, usize::MAX] {
737
            assert_eq!(byte_offset_to_cluster_id(&map, off), Some(gid(0, 2)));
738
        }
739
    }
740

            
741
    /// Cluster lengths at the top of the `usize` range: a single `usize::MAX`-long
742
    /// cluster, and two `usize::MAX / 2`-long ones whose running sum stays just
743
    /// below the overflow point. The internal `cumulative + len` must not wrap.
744
    #[test]
745
    fn byte_offset_to_cluster_id_huge_lengths_do_not_overflow() {
746
        let single = [(gid(0, 0), usize::MAX)];
747
        assert_eq!(byte_offset_to_cluster_id(&single, 0), Some(gid(0, 0)));
748
        assert_eq!(
749
            byte_offset_to_cluster_id(&single, usize::MAX - 1),
750
            Some(gid(0, 0))
751
        );
752
        // offset == len → falls through the loop, then to the `last()` fallback.
753
        assert_eq!(
754
            byte_offset_to_cluster_id(&single, usize::MAX),
755
            Some(gid(0, 0))
756
        );
757

            
758
        let half = usize::MAX / 2; // 2*half == usize::MAX - 1, no wrap.
759
        let pair = [(gid(0, 0), half), (gid(0, 1), half)];
760
        assert_eq!(byte_offset_to_cluster_id(&pair, 0), Some(gid(0, 0)));
761
        assert_eq!(byte_offset_to_cluster_id(&pair, half - 1), Some(gid(0, 0)));
762
        assert_eq!(byte_offset_to_cluster_id(&pair, half), Some(gid(0, 1)));
763
        assert_eq!(
764
            byte_offset_to_cluster_id(&pair, usize::MAX),
765
            Some(gid(0, 1))
766
        );
767
    }
768

            
769
    // ------------------------------------------------------------------
770
    // find_cluster_at_cursor — getters / predicates: invariants
771
    // ------------------------------------------------------------------
772

            
773
    #[test]
774
    fn find_cluster_at_cursor_empty_layout_is_none() {
775
        let layout = layout_of(vec![]);
776
        assert!(find_cluster_at_cursor(&cursor_at(gid(0, 0)), &layout).is_none());
777
        assert!(find_cluster_at_cursor(&cursor_at(gid(u32::MAX, u32::MAX)), &layout).is_none());
778
    }
779

            
780
    #[test]
781
    fn find_cluster_at_cursor_unknown_id_is_none() {
782
        let layout = layout_from_str("abc", 0);
783
        // Right run, byte offset past the end.
784
        assert!(find_cluster_at_cursor(&cursor_at(gid(0, 99)), &layout).is_none());
785
        // Right byte offset, wrong run.
786
        assert!(find_cluster_at_cursor(&cursor_at(gid(7, 0)), &layout).is_none());
787
        // Saturated id.
788
        assert!(find_cluster_at_cursor(&cursor_at(gid(u32::MAX, u32::MAX)), &layout).is_none());
789
    }
790

            
791
    #[test]
792
    fn find_cluster_at_cursor_skips_non_cluster_items_and_reports_visual_index() {
793
        let layout = layout_of(vec![tab(0), cl("a", gid(0, 0), 0), tab(0)]);
794
        let (idx, found) = find_cluster_at_cursor(&cursor_at(gid(0, 0)), &layout).unwrap();
795
        assert_eq!(idx, 1, "index must be into layout.items, skipping the tab");
796
        assert_eq!(found.text(), "a");
797
    }
798

            
799
    /// Duplicate cluster ids are not supposed to happen; if they do, the FIRST
800
    /// visual match wins. Pinned so a change of iteration order is caught.
801
    #[test]
802
    fn find_cluster_at_cursor_duplicate_ids_return_the_first_match() {
803
        let layout = layout_of(vec![cl("x", gid(0, 0), 0), cl("y", gid(0, 0), 1)]);
804
        let (idx, found) = find_cluster_at_cursor(&cursor_at(gid(0, 0)), &layout).unwrap();
805
        assert_eq!(idx, 0);
806
        assert_eq!(found.text(), "x");
807
    }
808

            
809
    // ------------------------------------------------------------------
810
    // extract_line_text_and_clusters — numeric: index bounds / ordering
811
    // ------------------------------------------------------------------
812

            
813
    /// `layout.items[item_idx]` is an unchecked index: the function's contract is
814
    /// that `item_idx` comes from `find_cluster_at_cursor`. Pin the panic so that
815
    /// contract is not silently broadened.
816
    #[test]
817
    #[should_panic(expected = "index out of bounds")]
818
    fn extract_line_text_out_of_bounds_index_panics_on_empty_layout() {
819
        let layout = layout_of(vec![]);
820
        let _ = extract_line_text_and_clusters(0, &layout);
821
    }
822

            
823
    #[test]
824
    #[should_panic(expected = "index out of bounds")]
825
    fn extract_line_text_usize_max_index_panics() {
826
        let layout = layout_from_str("abc", 0);
827
        let _ = extract_line_text_and_clusters(usize::MAX, &layout);
828
    }
829

            
830
    #[test]
831
    fn extract_line_text_non_cluster_item_yields_empty_text_and_map() {
832
        let layout = layout_of(vec![tab(0), cl("a", gid(0, 0), 0)]);
833
        let (text, map) = extract_line_text_and_clusters(0, &layout);
834
        assert!(text.is_empty());
835
        assert!(map.is_empty());
836
    }
837

            
838
    #[test]
839
    fn extract_line_text_zero_index_on_a_cluster_gathers_the_whole_run() {
840
        let layout = layout_from_str("hi there", 0);
841
        let (text, map) = extract_line_text_and_clusters(0, &layout);
842
        assert_eq!(text, "hi there");
843
        assert_eq!(map.len(), 8);
844
        assert_eq!(map[0], (gid(0, 0), 1));
845
    }
846

            
847
    /// Documented behaviour: clusters are gathered by LOGICAL run and sorted by
848
    /// `start_byte_in_run`, so a visually reordered (bidi) item vector must still
849
    /// concatenate in logical order.
850
    #[test]
851
    fn extract_line_text_restores_logical_order_from_reversed_visual_items() {
852
        let layout = layout_of(vec![
853
            cl("o", gid(0, 4), 0),
854
            cl("l", gid(0, 3), 0),
855
            cl("l", gid(0, 2), 0),
856
            cl("e", gid(0, 1), 0),
857
            cl("H", gid(0, 0), 0),
858
        ]);
859
        let (text, map) = extract_line_text_and_clusters(0, &layout);
860
        assert_eq!(text, "Hello", "visual order must not leak into the text");
861
        assert_eq!(
862
            map.iter()
863
                .map(|(id, _)| id.start_byte_in_run)
864
                .collect::<Vec<_>>(),
865
            vec![0, 1, 2, 3, 4]
866
        );
867
    }
868

            
869
    /// Documented behaviour: gathering is NOT restricted to one visual line, so a
870
    /// word split by a soft wrap is still reassembled.
871
    #[test]
872
    fn extract_line_text_crosses_visual_lines_and_excludes_other_runs() {
873
        let layout = layout_of(vec![
874
            cl("H", gid(0, 0), 0),
875
            cl("e", gid(0, 1), 0),
876
            cl("l", gid(0, 2), 1), // soft-wrapped onto line 1
877
            cl("X", gid(1, 0), 1), // a different logical run — must be excluded
878
            cl("o", gid(0, 3), 2), // and onto line 2
879
        ]);
880
        let (text, map) = extract_line_text_and_clusters(0, &layout);
881
        assert_eq!(text, "Helo");
882
        assert_eq!(map.len(), 4);
883
        assert!(map.iter().all(|(id, _)| id.source_run == 0));
884
    }
885

            
886
    #[test]
887
    fn extract_line_text_byte_lengths_are_utf8_lengths_not_char_counts() {
888
        let layout = layout_from_str("é日👍", 0);
889
        let (text, map) = extract_line_text_and_clusters(0, &layout);
890
        assert_eq!(text, "é日👍");
891
        assert_eq!(
892
            map.iter().map(|(_, len)| *len).collect::<Vec<_>>(),
893
            vec![2, 3, 4]
894
        );
895
        assert_eq!(map.iter().map(|(_, l)| l).sum::<usize>(), text.len());
896
    }
897

            
898
    // ------------------------------------------------------------------
899
    // select_word_at_cursor — round-trip + invariants
900
    // ------------------------------------------------------------------
901

            
902
    #[test]
903
    fn select_word_empty_layout_is_none() {
904
        let layout = layout_of(vec![]);
905
        assert!(select_word_at_cursor(&cursor_at(gid(0, 0)), &layout).is_none());
906
    }
907

            
908
    #[test]
909
    fn select_word_unknown_cursor_is_none() {
910
        let layout = layout_from_str("Hello", 0);
911
        assert!(select_word_at_cursor(&cursor_at(gid(3, 0)), &layout).is_none());
912
        assert!(select_word_at_cursor(&cursor_at(gid(0, u32::MAX)), &layout).is_none());
913
    }
914

            
915
    #[test]
916
    fn select_word_selects_the_word_under_the_cursor_with_correct_affinities() {
917
        let layout = layout_from_str("Hello World", 0);
918
        let range = select_word_at_cursor(&cursor_at(gid(0, 1)), &layout).unwrap();
919

            
920
        assert_eq!(range.start.cluster_id, gid(0, 0), "start of \"Hello\"");
921
        assert_eq!(range.end.cluster_id, gid(0, 4), "last cluster of \"Hello\"");
922
        assert_eq!(range.start.affinity, CursorAffinity::Leading);
923
        assert_eq!(range.end.affinity, CursorAffinity::Trailing);
924

            
925
        let range = select_word_at_cursor(&cursor_at(gid(0, 8)), &layout).unwrap();
926
        assert_eq!(range.start.cluster_id, gid(0, 6));
927
        assert_eq!(range.end.cluster_id, gid(0, 10));
928
    }
929

            
930
    /// A word broken by a soft wrap must select whole, not just the clicked fragment.
931
    #[test]
932
    fn select_word_spans_a_soft_wrap() {
933
        let layout = layout_of(vec![
934
            cl("H", gid(0, 0), 0),
935
            cl("e", gid(0, 1), 0),
936
            cl("l", gid(0, 2), 0),
937
            cl("l", gid(0, 3), 1), // wrapped
938
            cl("o", gid(0, 4), 1),
939
        ]);
940
        let range = select_word_at_cursor(&cursor_at(gid(0, 1)), &layout).unwrap();
941
        assert_eq!(range.start.cluster_id, gid(0, 0));
942
        assert_eq!(range.end.cluster_id, gid(0, 4), "must cross the line break");
943
    }
944

            
945
    /// Bidi: items in visual (reversed) order must still yield the logical word.
946
    #[test]
947
    fn select_word_uses_logical_not_visual_order() {
948
        let layout = layout_of(vec![
949
            cl("o", gid(0, 4), 0),
950
            cl("l", gid(0, 3), 0),
951
            cl("l", gid(0, 2), 0),
952
            cl("e", gid(0, 1), 0),
953
            cl("H", gid(0, 0), 0),
954
        ]);
955
        let range = select_word_at_cursor(&cursor_at(gid(0, 3)), &layout).unwrap();
956
        assert_eq!(range.start.cluster_id, gid(0, 0));
957
        assert_eq!(range.end.cluster_id, gid(0, 4));
958
    }
959

            
960
    /// Round-trip / idempotence: re-selecting from the START of a returned range
961
    /// must reproduce the identical range. A fixpoint failure here would make
962
    /// double-click-then-drag jitter.
963
    #[test]
964
    fn select_word_is_idempotent_from_its_own_start_cursor() {
965
        for text in ["Hello, World! foo_bar 42", "a  b", "héllo wörld", "!!!a"] {
966
            let layout = layout_from_str(text, 0);
967

            
968
            for (byte_idx, _) in text.char_indices() {
969
                let cur = cursor_at(gid(0, byte_idx as u32));
970
                let first = select_word_at_cursor(&cur, &layout)
971
                    .unwrap_or_else(|| panic!("{text:?} @ {byte_idx}: no selection"));
972
                let again = select_word_at_cursor(&first.start, &layout)
973
                    .unwrap_or_else(|| panic!("{text:?} @ {byte_idx}: re-select failed"));
974

            
975
                assert_eq!(
976
                    first, again,
977
                    "{text:?} @ {byte_idx}: selection is not a fixpoint"
978
                );
979
            }
980
        }
981
    }
982

            
983
    /// Invariants over every reachable cursor of every nasty string: always `Some`,
984
    /// never inverted, both endpoints are real clusters of the layout, affinities fixed.
985
    #[test]
986
    fn select_word_invariants_hold_for_every_cursor_of_nasty_unicode() {
987
        for &text in NASTY {
988
            let layout = layout_from_str(text, 0);
989
            let ids: Vec<GraphemeClusterId> =
990
                text.char_indices().map(|(b, _)| gid(0, b as u32)).collect();
991

            
992
            for id in &ids {
993
                let range = select_word_at_cursor(&cursor_at(*id), &layout)
994
                    .unwrap_or_else(|| panic!("{text:?} @ {id:?}: expected a selection"));
995

            
996
                assert!(
997
                    range.start.cluster_id <= range.end.cluster_id,
998
                    "{text:?} @ {id:?}: inverted range {range:?}"
999
                );
                assert!(
                    ids.contains(&range.start.cluster_id),
                    "{text:?} @ {id:?}: start is not a cluster of the layout"
                );
                assert!(
                    ids.contains(&range.end.cluster_id),
                    "{text:?} @ {id:?}: end is not a cluster of the layout"
                );
                assert_eq!(range.start.affinity, CursorAffinity::Leading);
                assert_eq!(range.end.affinity, CursorAffinity::Trailing);
            }
        }
    }
    /// A zero-length cluster (empty `text`) cannot be addressed by a byte offset,
    /// so selecting *on* it resolves to the neighbouring cluster instead of panicking.
    #[test]
    fn select_word_on_zero_length_cluster_resolves_to_a_neighbour() {
        let layout = layout_of(vec![cl("", gid(0, 0), 0), cl("x", gid(0, 1), 0)]);
        let range = select_word_at_cursor(&cursor_at(gid(0, 0)), &layout).unwrap();
        assert_eq!(range.start.cluster_id, gid(0, 1));
        assert_eq!(range.end.cluster_id, gid(0, 1));
    }
    #[test]
    fn select_word_all_clusters_empty_does_not_panic() {
        let layout = layout_of(vec![cl("", gid(0, 0), 0), cl("", gid(0, 1), 0)]);
        let range = select_word_at_cursor(&cursor_at(gid(0, 0)), &layout).unwrap();
        // Empty concatenated text ⇒ boundaries (0, 0) ⇒ both ends fall back to last().
        assert_eq!(range.start.cluster_id, gid(0, 1));
        assert_eq!(range.end.cluster_id, gid(0, 1));
    }
    /// Cluster metadata that contradicts the cluster text (`start_byte_in_run`
    /// values that do not match the utf-8 lengths) must not panic or slice mid-char.
    #[test]
    fn select_word_with_inconsistent_cluster_metadata_does_not_panic() {
        let layout = layout_of(vec![
            cl("abc", gid(0, 0), 0), // claims 1 byte, is 3
            cl("def", gid(0, 1), 0),
            cl("👍", gid(0, 2), 0), // multi-byte at a bogus offset
        ]);
        for id in [gid(0, 0), gid(0, 1), gid(0, 2)] {
            let range = select_word_at_cursor(&cursor_at(id), &layout);
            assert!(range.is_some(), "{id:?} must still resolve");
        }
    }
    #[test]
    fn select_word_large_layout_stays_correct_and_does_not_panic() {
        // 4000 clusters: 500 × "word " (word chars + a separator).
        let text = "word ".repeat(800);
        let layout = layout_from_str(&text, 0);
        // Cursor in the middle of the 400th word.
        let word_start = 400 * 5;
        let range = select_word_at_cursor(&cursor_at(gid(0, word_start as u32 + 2)), &layout)
            .expect("mid-word cursor must select");
        assert_eq!(range.start.cluster_id, gid(0, word_start as u32));
        assert_eq!(range.end.cluster_id, gid(0, word_start as u32 + 3));
        // Cursor on the separator selects just the separator.
        let sep = word_start + 4;
        let range = select_word_at_cursor(&cursor_at(gid(0, sep as u32)), &layout)
            .expect("separator cursor must select");
        assert_eq!(range.start.cluster_id, gid(0, sep as u32));
        assert_eq!(range.end.cluster_id, gid(0, sep as u32));
    }
    // ------------------------------------------------------------------
    // select_paragraph_at_cursor — invariants
    // ------------------------------------------------------------------
    #[test]
    fn select_paragraph_empty_layout_is_none() {
        let layout = layout_of(vec![]);
        assert!(select_paragraph_at_cursor(&cursor_at(gid(0, 0)), &layout).is_none());
    }
    #[test]
    fn select_paragraph_unknown_cursor_is_none() {
        let layout = layout_from_str("abc", 0);
        assert!(select_paragraph_at_cursor(&cursor_at(gid(9, 9)), &layout).is_none());
        assert!(select_paragraph_at_cursor(&cursor_at(gid(u32::MAX, u32::MAX)), &layout).is_none());
    }
    #[test]
    fn select_paragraph_covers_the_whole_soft_wrapped_paragraph() {
        // One paragraph wrapped over two visual lines. Triple-click selects the
        // paragraph — filtering by `line_index` used to select the clicked
        // visual line only, which no editor does.
        let layout = layout_of(vec![
            cl("a", gid(0, 0), 0),
            cl("b", gid(0, 1), 0),
            cl("c", gid(0, 2), 1),
            cl("d", gid(0, 3), 1),
        ]);
        for probe in [gid(0, 0), gid(0, 1), gid(0, 2), gid(0, 3)] {
            let range = select_paragraph_at_cursor(&cursor_at(probe), &layout).unwrap();
            assert_eq!(range.start.cluster_id, gid(0, 0), "from {probe:?}");
            assert_eq!(range.end.cluster_id, gid(0, 3), "from {probe:?}");
            assert_eq!(range.start.affinity, CursorAffinity::Leading);
            assert_eq!(range.end.affinity, CursorAffinity::Trailing);
        }
    }
    /// A paragraph made of several logical runs (`<p>plain <b>bold</b></p>`)
    /// selects whole — the runs are one paragraph, no break separates them.
    #[test]
    fn select_paragraph_spans_every_run_between_breaks() {
        let layout = layout_of(vec![
            cl("a", gid(0, 0), 0),
            cl("b", gid(1, 0), 0),
            cl("c", gid(2, 0), 1),
        ]);
        for probe in [gid(0, 0), gid(1, 0), gid(2, 0)] {
            let range = select_paragraph_at_cursor(&cursor_at(probe), &layout).unwrap();
            assert_eq!(range.start.cluster_id, gid(0, 0), "from {probe:?}");
            assert_eq!(range.end.cluster_id, gid(2, 0), "from {probe:?}");
        }
    }
    /// A HARD break (`<br>`, a preserved newline) IS a paragraph boundary: it
    /// occupies its own slot in the inline-content array, so its `run_index`
    /// splits the clusters into two paragraphs.
    #[test]
    fn select_paragraph_stops_at_hard_breaks() {
        let layout = layout_of(vec![
            cl("a", gid(0, 0), 0),
            cl("b", gid(0, 1), 0),
            hard_break(1, 0),
            cl("c", gid(2, 0), 1),
            cl("d", gid(2, 1), 2), // wrapped: still the second paragraph
            hard_break(3, 2),
            cl("e", gid(4, 0), 3),
        ]);
        let first = select_paragraph_at_cursor(&cursor_at(gid(0, 1)), &layout).unwrap();
        assert_eq!(first.start.cluster_id, gid(0, 0));
        assert_eq!(first.end.cluster_id, gid(0, 1), "must not cross the break");
        let middle = select_paragraph_at_cursor(&cursor_at(gid(2, 1)), &layout).unwrap();
        assert_eq!(middle.start.cluster_id, gid(2, 0), "bounded on both sides");
        assert_eq!(middle.end.cluster_id, gid(2, 1));
        let last = select_paragraph_at_cursor(&cursor_at(gid(4, 0)), &layout).unwrap();
        assert_eq!(last.start.cluster_id, gid(4, 0));
        assert_eq!(last.end.cluster_id, gid(4, 0));
    }
    /// A SOFT break is a wrap opportunity, not a paragraph boundary.
    #[test]
    fn select_paragraph_ignores_soft_breaks() {
        let layout = layout_of(vec![
            cl("a", gid(0, 0), 0),
            soft_break(1, 0),
            cl("b", gid(2, 0), 1),
        ]);
        let range = select_paragraph_at_cursor(&cursor_at(gid(0, 0)), &layout).unwrap();
        assert_eq!(range.start.cluster_id, gid(0, 0));
        assert_eq!(range.end.cluster_id, gid(2, 0));
    }
    #[test]
    fn select_paragraph_ignores_non_cluster_items_at_the_paragraph_edges() {
        let layout = layout_of(vec![
            tab(0),
            cl("a", gid(0, 0), 0),
            cl("b", gid(0, 1), 0),
            tab(0),
        ]);
        let range = select_paragraph_at_cursor(&cursor_at(gid(0, 1)), &layout).unwrap();
        assert_eq!(range.start.cluster_id, gid(0, 0));
        assert_eq!(range.end.cluster_id, gid(0, 1));
    }
    /// A saturated `line_index` is no longer load-bearing (the paragraph is
    /// delimited by breaks, not by lines), and must not change the answer or
    /// overflow anything.
    #[test]
    fn select_paragraph_is_unaffected_by_a_saturated_line_index() {
        let layout = layout_of(vec![
            cl("a", gid(0, 0), 0),
            cl("b", gid(0, 1), usize::MAX),
            cl("c", gid(0, 2), usize::MAX),
        ]);
        for probe in [gid(0, 0), gid(0, 1), gid(0, 2)] {
            let range = select_paragraph_at_cursor(&cursor_at(probe), &layout).unwrap();
            assert_eq!(range.start.cluster_id, gid(0, 0), "from {probe:?}");
            assert_eq!(range.end.cluster_id, gid(0, 2), "from {probe:?}");
        }
    }
    /// Bidi: the items arrive in VISUAL (reversed) order, but the endpoints are
    /// taken in LOGICAL order, so the range is never inverted. It used to read
    /// the ends of the visual vector and return `start > end`, which
    /// `get_selection_rects` (a logical walk) cannot highlight — an inverted
    /// range is a bug, not a quirk.
    #[test]
    fn select_paragraph_returns_a_logical_range_for_reordered_runs() {
        let layout = layout_of(vec![
            cl("o", gid(0, 4), 0),
            cl("l", gid(0, 3), 0),
            cl("l", gid(0, 2), 0),
            cl("e", gid(0, 1), 0),
            cl("H", gid(0, 0), 0),
        ]);
        let range = select_paragraph_at_cursor(&cursor_at(gid(0, 2)), &layout).unwrap();
        assert_eq!(range.start.cluster_id, gid(0, 0), "logically-first cluster");
        assert_eq!(range.end.cluster_id, gid(0, 4), "logically-last cluster");
        assert!(
            range.start.cluster_id <= range.end.cluster_id,
            "a selection range must never be logically inverted"
        );
    }
    /// The same invariant `select_word_at_cursor` is held to, over every
    /// reachable cursor of every nasty string.
    #[test]
    fn select_paragraph_is_never_inverted_for_nasty_unicode() {
        for &text in NASTY {
            let layout = layout_from_str(text, 0);
            for (byte_idx, _) in text.char_indices() {
                let cur = cursor_at(gid(0, byte_idx as u32));
                let range = select_paragraph_at_cursor(&cur, &layout)
                    .unwrap_or_else(|| panic!("{text:?} @ {byte_idx}: expected a selection"));
                assert!(
                    range.start.cluster_id <= range.end.cluster_id,
                    "{text:?} @ {byte_idx}: inverted range {range:?}"
                );
            }
        }
    }
    /// Whenever the cursor resolves to a cluster, paragraph selection must resolve
    /// too (its line always contains at least that cluster) — never `None`.
    #[test]
    fn select_paragraph_is_some_for_every_reachable_cursor() {
        for &text in NASTY {
            let layout = layout_from_str(text, 0);
            for (byte_idx, _) in text.char_indices() {
                let cur = cursor_at(gid(0, byte_idx as u32));
                assert!(
                    select_paragraph_at_cursor(&cur, &layout).is_some(),
                    "{text:?} @ {byte_idx}: cursor found a cluster but no paragraph"
                );
            }
        }
    }
}