quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! Pure text-processing utilities: fuzzy subsequence matching and
//! word-aware line wrapping.
//!
//! Both functions are framework-shaped — no platform dependencies, no
//! `Backend` coupling — so they're unconditionally compiled and free of
//! feature gates. They exist here so [`fuzzy_score`] backs every fuzzy
//! matcher in the crate ([`crate::compose::folder_picker`]'s directory
//! filter, [`crate::compose::filter_help_actions`]) instead of each one
//! carrying its own ad-hoc scorer, and so [`word_wrap`] gives
//! [`crate::compose::chat_controller`] (and any other consumer that
//! needs to wrap plain text to a column budget) real word-aware
//! wrapping instead of a mid-word hard break.
//!
//! The boundary-snap helpers below ([`snap_to_char_boundary`],
//! [`prev_char_boundary`], [`next_char_boundary`], [`safe_prefix`],
//! [`safe_slice`]) prevent panics when GUI rasterisers (gtk, macos)
//! receive byte-offset cursor/selection positions with no guarantee
//! those offsets land on a UTF-8 char boundary — slicing a `String`
//! directly at such an offset panics the paint pass the moment a
//! multibyte character (é, CJK, emoji) sits left of the cursor. This
//! module unifies them so every caller — in-crate and, eventually,
//! downstream — gets the same panic-free behaviour.
//!
//! [`char_cell_width`] and [`display_width`] measure real terminal
//! display width (CJK/emoji count double, combining marks count zero).
//! These live here instead so core code can use them without depending
//! on `tui`/`gtk`; [`crate::tui::char_cell_width`] re-exports the same
//! function for API stability.
//!
//! [`wrap_spans`] is the one display-width-aware line wrapper in the
//! crate. [`word_wrap`] is now a thin adapter over [`wrap_spans`]
//! (same signature, same behaviour, now display-width-correct).
//!
//! [`char_to_byte_idx`], [`char_col_to_visual`] and
//! [`strip_json_comments`] are unified here so downstream hosts reach
//! `quadraui::text_util::*` instead of copying the logic. Moving
//! [`strip_json_comments`] also fixed a latent bug: earlier
//! byte-indexed implementations corrupted non-ASCII content. The version
//! here walks whole `char`s instead of raw bytes, so multi-byte input
//! round-trips intact; see [`strip_json_comments`]'s tests.

use crate::types::StyledSpan;

/// Snap `byte_idx` to the nearest UTF-8 char boundary in `s` at or
/// before `byte_idx`, clamping `byte_idx` to `s.len()` first.
///
/// Use this to make an arbitrary (possibly host-supplied, possibly
/// stale) byte offset safe to slice with: `&s[..snap_to_char_boundary(s,
/// byte_idx)]` never panics, regardless of where `byte_idx` originally
/// pointed.
pub fn snap_to_char_boundary(s: &str, byte_idx: usize) -> usize {
    let byte_idx = byte_idx.min(s.len());
    let mut i = byte_idx;
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

/// Return the byte offset of the char boundary immediately before
/// `byte_idx` (i.e. the start of the previous character). Returns `0`
/// if `byte_idx == 0`.
///
/// Intended for "move cursor left one char" style operations, where the
/// caller then slices or indexes at the returned offset.
pub fn prev_char_boundary(s: &str, byte_idx: usize) -> usize {
    let byte_idx = byte_idx.min(s.len());
    if byte_idx == 0 {
        return 0;
    }
    let mut i = byte_idx - 1;
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

/// Return the byte offset of the char boundary immediately after
/// `byte_idx` (i.e. the start of the next character), clamped to
/// `s.len()`.
///
/// Intended for "move cursor right one char" style operations.
pub fn next_char_boundary(s: &str, byte_idx: usize) -> usize {
    let byte_idx = byte_idx.min(s.len());
    if byte_idx >= s.len() {
        return s.len();
    }
    let mut i = byte_idx + 1;
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// Return `&s[..byte_idx]`, with `byte_idx` snapped to the nearest char
/// boundary at or before it — a panic-free replacement for `&s[..byte_idx]`
/// when `byte_idx` isn't known to be char-boundary-aligned (e.g. a
/// host-supplied cursor position).
pub fn safe_prefix(s: &str, byte_idx: usize) -> &str {
    &s[..snap_to_char_boundary(s, byte_idx)]
}

/// Return `&s[lo..hi]`, with both bounds snapped to char boundaries and
/// swapped if `lo > hi` — a panic-free replacement for `&s[lo..hi]` when
/// the bounds aren't known to be char-boundary-aligned or correctly
/// ordered.
pub fn safe_slice(s: &str, lo: usize, hi: usize) -> &str {
    let (lo, hi) = if lo <= hi { (lo, hi) } else { (hi, lo) };
    let lo = snap_to_char_boundary(s, lo);
    let hi = snap_to_char_boundary(s, hi);
    &s[lo..hi]
}

/// Convert a **char** offset into `text` to a byte offset safe to slice
/// at. Out-of-range offsets clamp to `text.len()` — always a valid slice
/// point — rather than panicking.
///
/// Use this when a caller stores a cursor/selection boundary as a
/// character count (the natural unit for column arithmetic) but needs a
/// byte offset to slice or index the underlying `&str`. Formerly
/// duplicated as private `char_to_byte` closures/functions in
/// `primitives/find_replace.rs` and the `gtk`/`win` `rich_text_popup`
/// rasterisers; this is the shared implementation.
pub fn char_to_byte_idx(text: &str, char_idx: usize) -> usize {
    text.char_indices()
        .nth(char_idx)
        .map(|(i, _)| i)
        .unwrap_or(text.len())
}

/// Convert a character-index column into a visual column, expanding tabs
/// to the next tab stop (`tabstop`, floored to 1). Stops at the first
/// `\n`/`\r` in `raw_text` or at `char_col`, whichever comes first — a
/// column past the end of the line's content simply measures the whole
/// line.
///
/// Every non-tab character advances the visual column by exactly one
/// cell (this does *not* account for double-width CJK/emoji glyphs —
/// callers that need display-width-aware measurement should use
/// [`display_width`] instead).
pub fn char_col_to_visual(raw_text: &str, char_col: usize, tabstop: usize) -> usize {
    let tabstop = tabstop.max(1);
    let mut vis = 0usize;
    for (i, ch) in raw_text.chars().enumerate() {
        if ch == '\n' || ch == '\r' {
            break;
        }
        if i >= char_col {
            break;
        }
        if ch == '\t' {
            vis = ((vis / tabstop) + 1) * tabstop;
        } else {
            vis += 1;
        }
    }
    vis
}

/// Strip `//` and `/* */` comments from JSON-with-comments (JSONC), as
/// used by VS Code theme files. Preserves newlines inside block comments
/// so that any later parse-error line/column reporting on the stripped
/// string still lines up with the original file.
///
/// Walks whole `char`s (not raw bytes), so multi-byte UTF-8 content —
/// inside a string literal or in bare JSON text — round-trips intact.
/// Lifted from vimcode's `render::strip_json_comments` — a pure
/// text transform with nothing editor-specific about it — and moved here
/// from a private `theme.rs` helper.
pub fn strip_json_comments(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    // Byte length of the UTF-8 char starting at byte offset `at` (`at`
    // must be on a char boundary, which every branch below maintains).
    let char_len_at =
        |at: usize| -> usize { input[at..].chars().next().map_or(1, |c| c.len_utf8()) };
    while i < len {
        if bytes[i] == b'"' {
            // String literal — copy verbatim until the closing quote, so a
            // `//` or `/*` inside a JSON string value is never mistaken
            // for a comment.
            out.push('"');
            i += 1;
            while i < len {
                if bytes[i] == b'\\' && i + 1 < len {
                    // JSON escape sequences (`\n`, `\"`, `\uXXXX`, ...) are
                    // always a backslash followed by one ASCII char, but
                    // copy by char width regardless for symmetry.
                    let esc_len = char_len_at(i + 1);
                    out.push_str(&input[i..i + 1 + esc_len]);
                    i += 1 + esc_len;
                } else if bytes[i] == b'"' {
                    out.push('"');
                    i += 1;
                    break;
                } else {
                    let n = char_len_at(i);
                    out.push_str(&input[i..i + n]);
                    i += n;
                }
            }
        } else if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'/' {
            // Line comment — skip until newline.
            i += 2;
            while i < len && bytes[i] != b'\n' {
                i += 1;
            }
        } else if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
            // Block comment — skip until `*/`, preserving newlines.
            i += 2;
            while i + 1 < len && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                if bytes[i] == b'\n' {
                    out.push('\n');
                }
                i += 1;
            }
            i += 2; // skip `*/`
        } else {
            let n = char_len_at(i);
            out.push_str(&input[i..i + n]);
            i += n;
        }
    }
    out
}

/// Terminal cell width of a single character (0, 1, or 2).
///
/// Uses the `unicode-width` crate's UAX#11 tables directly, with no
/// codepoint-range overrides. Private-Use-Area codepoints — including
/// both Nerd Font PUA blocks (BMP `U+E000`–`U+F8FF` and Supplementary-A
/// `U+F0000`–`U+FFFFD`) — measure as width 1, matching `unicode-width`
/// and `Nerd Font Mono` (the terminal-recommended, single-cell variant).
/// Non-Mono Nerd Font variants are genuinely double-width, but that is a
/// font/theme property, not something derivable from the codepoint
/// alone; if double-width PUA glyphs ever need supporting, it must come
/// in as an explicit input (theme/config/probe), not a range guess here.
///
/// Lives here so core types like [`crate::types::StyledText`] can measure
/// real display width without depending on the `tui` or `gtk` features.
/// [`crate::tui::char_cell_width`] re-exports this same function; it
/// is not a separate implementation.
pub fn char_cell_width(c: char) -> u16 {
    unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as u16
}

/// Terminal display width of `s` in cells: the sum of each character's
/// [`char_cell_width`].
///
/// Not the same as `s.chars().count()` (CJK/emoji count double) or
/// `s.len()` (UTF-8 byte length).
pub fn display_width(s: &str) -> usize {
    s.chars().map(|c| char_cell_width(c) as usize).sum()
}

/// Whether `c` is a double-width glyph (CJK, emoji, ...) per
/// [`char_cell_width`] — i.e. `char_cell_width(c) == 2`.
///
/// Named for callers that only need the wide/narrow classification, not
/// the numeric width: pixel-based terminal rasterisers (`gtk`, `macos`)
/// use this to decide whether a cell claims one grid column or two — see
/// [`crate::terminal_style::wide_cell_advance`].
pub fn is_wide_char(c: char) -> bool {
    char_cell_width(c) == 2
}

/// Case-sensitive subsequence fuzzy match with a relevance score and
/// per-match byte positions.
///
/// Returns `None` if `query`'s characters do not all appear in
/// `haystack`, in order (not necessarily contiguously); otherwise
/// returns `Some((score, positions))`:
///
/// - `score` starts at a neutral baseline and is adjusted per matched
///   character: consecutive matches (no gap between them) earn a
///   "run" bonus, non-consecutive matches are penalised by the size of
///   the gap, and matches that land right after a word-boundary byte
///   (`/`, `\`, `_`, `-`, `.`, whitespace, or the start of the string)
///   earn a boundary bonus. Higher is a better match.
/// - `positions` are the **byte offsets** into `haystack` of each
///   matched character, in order — feed these straight into
///   [`crate::primitives::palette::PaletteItem::match_positions`] (or
///   an equivalent highlight field) so backends can highlight *why* a
///   row matched.
///
/// Matching is case-sensitive by design (mirroring the pre-existing
/// `dir_fuzzy_score` this replaces) — callers that want
/// case-insensitive matching should lowercase both `haystack` and
/// `query` before calling, same as
/// [`crate::compose::folder_picker`]'s filter already does.
///
/// An empty `query` is a trivial match against anything: `Some((0,
/// vec![]))`. Callers that want an "empty query shows everything,
/// unranked, in original order" fast path (as opposed to a
/// zero-scored, unsorted match) should special-case `query.is_empty()`
/// before calling — see [`crate::compose::filter_help_actions`] for
/// that convention.
pub fn fuzzy_score(haystack: &str, query: &str) -> Option<(i32, Vec<usize>)> {
    if query.is_empty() {
        return Some((0, Vec::new()));
    }

    let query_chars: Vec<char> = query.chars().collect();
    let mut qi = 0usize;
    let mut score = 100i32;
    let mut positions = Vec::with_capacity(query_chars.len());
    let mut prev_matched_char_idx: Option<usize> = None;
    let mut prev_char: Option<char> = None;

    for (char_idx, (byte_idx, ch)) in haystack.char_indices().enumerate() {
        if qi < query_chars.len() && ch == query_chars[qi] {
            if let Some(prev_idx) = prev_matched_char_idx {
                let gap = char_idx - prev_idx - 1;
                if gap == 0 {
                    score += 15; // consecutive-run bonus
                } else {
                    score -= gap as i32;
                }
            }
            let at_boundary = prev_char.is_none_or(|c| c.is_whitespace())
                || matches!(prev_char, Some('/' | '\\' | '_' | '-' | '.'));
            if at_boundary {
                score += 10;
            }
            positions.push(byte_idx);
            prev_matched_char_idx = Some(char_idx);
            qi += 1;
        }
        prev_char = Some(ch);
    }

    if qi == query_chars.len() {
        Some((score, positions))
    } else {
        None
    }
}

/// Word-aware soft-wrap: break `text` into rows no wider than
/// `col_budget` **display cells** (see [`display_width`] — CJK and emoji
/// count as 2), breaking at whitespace where possible.
///
/// A single word longer than `col_budget` doesn't fit on any row no
/// matter where lines break, so it falls back to a hard display-width
/// break (chunked to `col_budget` cells) — this is the only case where a
/// word is split mid-word.
///
/// Runs of whitespace between words collapse to a single space when
/// they land inside a wrapped row (standard word-wrap behaviour); a
/// line that fits within `col_budget` unmodified is returned verbatim,
/// so single-space text with no wrapping needed round-trips exactly.
///
/// `text` is assumed to be a single logical line (no `\n`) — callers
/// that need to wrap multi-line text should split on `\n` first and
/// call this per line, same as
/// [`crate::compose::chat_controller`] does.
///
/// Zero budget or empty input is handled gracefully: `col_budget == 0`
/// returns `text` unmodified as a single row (there's no sane way to
/// wrap to zero columns), and empty `text` returns one empty row.
///
/// A thin adapter over [`wrap_spans`] with [`WrapPolicy::Word`]. The
/// signature and behaviour are unchanged; only the row-budget accounting
/// changed from `chars().count()` to [`display_width`], so CJK/emoji
/// text now wraps at the correct column instead of overflowing.
pub fn word_wrap(text: &str, col_budget: usize) -> Vec<String> {
    let spans = [StyledSpan::plain(text)];
    wrap_spans(&spans, col_budget, WrapPolicy::Word)
        .into_iter()
        .map(|group| group.iter().map(|s| s.text.as_str()).collect())
        .collect()
}

/// How [`wrap_spans`] should treat word boundaries when a row must break.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WrapPolicy {
    /// Break at whitespace where possible; a single word wider than the
    /// row budget hard-breaks at the display-width budget. This is
    /// [`word_wrap`]'s policy, generalised to styled spans.
    Word,
    /// Ignore word boundaries entirely: break exactly at the
    /// display-width budget, mid-word or mid-span if necessary. As an
    /// explicit policy option, switching a call site's wrap behaviour is
    /// a one-word decision, not a silent side effect of unifying multiple
    /// independent wrappers.
    Char,
}

/// Wrap a styled-span line to `col_budget` **display cells** per row (see
/// [`display_width`]), honouring `policy`.
///
/// Returns one `Vec<StyledSpan>` per visual row; a span that crosses a
/// wrap boundary is split, with the original style (fg/bg/bold/italic/
/// underline) cloned onto every resulting chunk. The concatenation of
/// each row's span texts, in order, reconstructs the corresponding slice
/// of the original line's plain text (`WrapPolicy::Word` drops the single
/// whitespace character consumed at each wrap point, same as
/// [`word_wrap`]).
///
/// `spans` empty, or every span's `text` empty, returns `vec![vec![]]`
/// (one empty row) — same convention as `col_budget == 0` or the whole
/// line already fitting, both of which return `vec![spans.to_vec()]`
/// (the input unmodified, as a single row).
///
/// This is the crate's one line wrapper — see the module doc and issue
pub fn wrap_spans(
    spans: &[StyledSpan],
    col_budget: usize,
    policy: WrapPolicy,
) -> Vec<Vec<StyledSpan>> {
    // Flatten to (char, index into `spans` of the span that owns it) so
    // wrapping can work at cell-width granularity while still knowing
    // which style to reapply when it re-groups a row into spans.
    let chars: Vec<(char, usize)> = spans
        .iter()
        .enumerate()
        .flat_map(|(idx, span)| span.text.chars().map(move |c| (c, idx)))
        .collect();

    if spans.is_empty() || chars.is_empty() {
        return vec![vec![]];
    }

    let total_width: usize = chars
        .iter()
        .map(|&(c, _)| char_cell_width(c) as usize)
        .sum();
    if col_budget == 0 || total_width <= col_budget {
        return vec![spans.to_vec()];
    }

    let rows: Vec<Vec<(char, usize)>> = match policy {
        WrapPolicy::Char => wrap_chars_by_width(&chars, col_budget),
        WrapPolicy::Word => wrap_chars_by_word(&chars, col_budget),
    };

    rows.iter()
        .map(|row| group_into_spans(row, spans))
        .collect()
}

/// `WrapPolicy::Char`: break strictly at `budget` display cells, ignoring
/// word boundaries. Always makes progress — a single character wider
/// than `budget` (a lone CJK/emoji glyph in a narrow budget) still lands
/// alone on its own row rather than looping forever.
fn wrap_chars_by_width(chars: &[(char, usize)], budget: usize) -> Vec<Vec<(char, usize)>> {
    let mut rows = Vec::new();
    let mut row: Vec<(char, usize)> = Vec::new();
    let mut row_w = 0usize;
    for &(c, idx) in chars {
        let w = char_cell_width(c) as usize;
        if !row.is_empty() && row_w + w > budget {
            rows.push(std::mem::take(&mut row));
            row_w = 0;
        }
        row.push((c, idx));
        row_w += w;
    }
    if !row.is_empty() {
        rows.push(row);
    }
    rows
}

/// `WrapPolicy::Word`: pack whitespace-delimited words onto rows greedily,
/// joining consecutive words with a single space (collapsing any wider
/// run of literal `' '` characters at that boundary — same collapsing
/// [`word_wrap`] has always done). A word wider than `budget` hard-breaks
/// via [`wrap_chars_by_width`], the same as a plain [`WrapPolicy::Char`]
/// chunk, and any leftover chunk becomes the start of the next row so
/// later words can still pack onto it.
fn wrap_chars_by_word(chars: &[(char, usize)], budget: usize) -> Vec<Vec<(char, usize)>> {
    // Tokenize into alternating whitespace / non-whitespace runs. Only
    // the literal space character `' '` is treated as a separator,
    // matching `word_wrap`'s standard word-wrap tokenization.
    enum TokenKind {
        Word,
        Space,
    }
    let mut tokens: Vec<(TokenKind, Vec<(char, usize)>)> = Vec::new();
    for &(c, idx) in chars {
        let kind_is_space = c == ' ';
        match tokens.last_mut() {
            Some((TokenKind::Space, run)) if kind_is_space => run.push((c, idx)),
            Some((TokenKind::Word, run)) if !kind_is_space => run.push((c, idx)),
            _ => tokens.push((
                if kind_is_space {
                    TokenKind::Space
                } else {
                    TokenKind::Word
                },
                vec![(c, idx)],
            )),
        }
    }

    let mut rows: Vec<Vec<(char, usize)>> = Vec::new();
    let mut row: Vec<(char, usize)> = Vec::new();
    let mut row_w = 0usize;
    // The single space (collapsed from however many literal spaces were
    // in the source run) pending insertion before the next word, if any
    // word actually follows it on the same row.
    let mut pending_space: Option<(char, usize)> = None;

    for (kind, content) in tokens {
        match kind {
            TokenKind::Space => {
                pending_space = content.first().copied();
            }
            TokenKind::Word => {
                let word_w: usize = content
                    .iter()
                    .map(|&(c, _)| char_cell_width(c) as usize)
                    .sum();
                if word_w > budget {
                    // Doesn't fit on any row by itself — flush the
                    // current row (dropping any pending space, since a
                    // fresh row follows regardless) and hard-break the
                    // word by display width.
                    if !row.is_empty() {
                        rows.push(std::mem::take(&mut row));
                    }
                    pending_space = None;
                    let mut chunks = wrap_chars_by_width(&content, budget);
                    // Leave the last chunk as the new current row so a
                    // following short word may still pack onto it.
                    row = chunks.pop().unwrap_or_default();
                    row_w = row.iter().map(|&(c, _)| char_cell_width(c) as usize).sum();
                    rows.extend(chunks);
                } else {
                    let extra = if row.is_empty() || pending_space.is_none() {
                        0
                    } else {
                        1
                    };
                    if row_w + extra + word_w <= budget {
                        if extra == 1 {
                            row.push(pending_space.expect("extra == 1 implies Some"));
                            row_w += 1;
                        }
                        row.extend_from_slice(&content);
                        row_w += word_w;
                    } else {
                        if !row.is_empty() {
                            rows.push(std::mem::take(&mut row));
                        }
                        row = content;
                        row_w = word_w;
                    }
                    pending_space = None;
                }
            }
        }
    }
    if !row.is_empty() {
        rows.push(row);
    }
    if rows.is_empty() {
        rows.push(Vec::new());
    }
    rows
}

/// Re-group a flattened `(char, owning-span-index)` row into
/// [`StyledSpan`]s, merging consecutive characters that share the same
/// owning span into one chunk and cloning that span's style onto it.
fn group_into_spans(row: &[(char, usize)], spans: &[StyledSpan]) -> Vec<StyledSpan> {
    let mut result = Vec::new();
    let mut i = 0usize;
    while i < row.len() {
        let idx = row[i].1;
        let mut text = String::new();
        while i < row.len() && row[i].1 == idx {
            text.push(row[i].0);
            i += 1;
        }
        result.push(StyledSpan {
            text,
            ..spans[idx].clone()
        });
    }
    result
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── snap_to_char_boundary / prev_char_boundary / next_char_boundary ──

    #[test]
    fn snap_to_char_boundary_already_on_boundary_is_noop() {
        let s = "héllo";
        assert_eq!(snap_to_char_boundary(s, 0), 0);
        assert_eq!(snap_to_char_boundary(s, 1), 1);
        // 'é' is 2 bytes starting at byte 1, boundary after it is byte 3.
        assert_eq!(snap_to_char_boundary(s, 3), 3);
    }

    #[test]
    fn snap_to_char_boundary_mid_char_walks_back() {
        let s = "héllo";
        // byte 2 is inside 'é' (bytes 1..3) — must walk back to 1.
        assert_eq!(snap_to_char_boundary(s, 2), 1);
    }

    #[test]
    fn snap_to_char_boundary_clamps_past_end() {
        let s = "abc";
        assert_eq!(snap_to_char_boundary(s, 100), 3);
    }

    #[test]
    fn snap_to_char_boundary_cjk_and_emoji() {
        let s = "中文🎉end";
        // Every offset, however it lands mid-char, should snap to a valid
        // boundary and never panic when used to slice.
        for i in 0..=s.len() {
            let snapped = snap_to_char_boundary(s, i);
            assert!(s.is_char_boundary(snapped));
            let _ = &s[..snapped]; // must not panic
        }
    }

    #[test]
    fn prev_char_boundary_at_zero_stays_zero() {
        assert_eq!(prev_char_boundary("abc", 0), 0);
    }

    #[test]
    fn prev_char_boundary_steps_back_one_multibyte_char() {
        let s = "héllo";
        // Cursor right after 'é' (byte 3) should move to right before it (byte 1).
        assert_eq!(prev_char_boundary(s, 3), 1);
    }

    #[test]
    fn prev_char_boundary_from_mid_char_lands_before_that_char() {
        let s = "héllo";
        // byte 2 is mid-'é'; prev boundary is the start of 'é' at byte 1.
        assert_eq!(prev_char_boundary(s, 2), 1);
    }

    #[test]
    fn prev_char_boundary_clamps_past_end() {
        let s = "héllo";
        // Same clamp-then-walk-back behaviour as snap_to_char_boundary /
        // next_char_boundary for an out-of-range byte_idx.
        assert_eq!(prev_char_boundary(s, 999), prev_char_boundary(s, s.len()));
    }

    #[test]
    fn next_char_boundary_at_end_stays_at_end() {
        let s = "abc";
        assert_eq!(next_char_boundary(s, 3), 3);
        assert_eq!(next_char_boundary(s, 100), 3);
    }

    #[test]
    fn next_char_boundary_steps_forward_one_multibyte_char() {
        let s = "héllo";
        // Cursor right before 'é' (byte 1) should move past it to byte 3.
        assert_eq!(next_char_boundary(s, 1), 3);
    }

    #[test]
    fn next_char_boundary_from_mid_char_lands_after_that_char() {
        let s = "héllo";
        assert_eq!(next_char_boundary(s, 2), 3);
    }

    // ── safe_prefix / safe_slice ───────────────────────────────────────

    #[test]
    fn safe_prefix_on_boundary_matches_manual_slice() {
        let s = "héllo";
        assert_eq!(safe_prefix(s, 3), &s[..3]);
    }

    #[test]
    fn safe_prefix_mid_char_does_not_panic() {
        let s = "héllo";
        assert_eq!(safe_prefix(s, 2), "h");
    }

    #[test]
    fn safe_prefix_past_end_returns_whole_string() {
        let s = "héllo";
        assert_eq!(safe_prefix(s, 999), s);
    }

    #[test]
    fn safe_slice_mid_char_bounds_do_not_panic() {
        let s = "中文🎉end";
        // Arbitrary byte offsets landing inside multibyte chars must still
        // produce a valid (possibly empty) slice, never panic.
        for lo in 0..=s.len() {
            for hi in 0..=s.len() {
                let slice = safe_slice(s, lo, hi);
                let _ = slice; // must not panic; content already validated by &str type
            }
        }
    }

    #[test]
    fn safe_slice_swaps_reversed_bounds() {
        let s = "abcdef";
        assert_eq!(safe_slice(s, 4, 1), &s[1..4]);
    }

    #[test]
    fn safe_slice_on_boundaries_matches_manual_slice() {
        let s = "héllo world";
        assert_eq!(safe_slice(s, 0, 3), &s[0..3]);
    }

    // ── char_to_byte_idx ───────────────────────────────────────────────

    #[test]
    fn char_to_byte_idx_ascii_matches_index() {
        assert_eq!(char_to_byte_idx("abcde", 0), 0);
        assert_eq!(char_to_byte_idx("abcde", 3), 3);
    }

    #[test]
    fn char_to_byte_idx_multibyte_input() {
        let s = "héllo"; // 'é' is 2 bytes at char index 1, byte offset 1.
        assert_eq!(char_to_byte_idx(s, 0), 0);
        assert_eq!(char_to_byte_idx(s, 1), 1);
        // char index 2 ('l') starts at byte 3, after the 2-byte 'é'.
        assert_eq!(char_to_byte_idx(s, 2), 3);
    }

    #[test]
    fn char_to_byte_idx_cjk_and_emoji() {
        let s = "中文🎉end";
        let byte_offsets: Vec<usize> = s.char_indices().map(|(b, _)| b).collect();
        for (char_idx, &expected_byte) in byte_offsets.iter().enumerate() {
            assert_eq!(char_to_byte_idx(s, char_idx), expected_byte);
        }
    }

    #[test]
    fn char_to_byte_idx_past_end_clamps_to_len() {
        let s = "héllo";
        assert_eq!(char_to_byte_idx(s, 999), s.len());
    }

    // ── char_col_to_visual ────────────────────────────────────────────

    #[test]
    fn char_col_to_visual_no_tabs_is_identity() {
        assert_eq!(char_col_to_visual("hello", 3, 4), 3);
        assert_eq!(char_col_to_visual("hello", 0, 4), 0);
    }

    #[test]
    fn char_col_to_visual_expands_tabs_to_tabstop() {
        // "\t" at col 0 expands to the next tab stop (4); a second char
        // after it lands at column 5.
        assert_eq!(char_col_to_visual("\tx", 1, 4), 4);
        assert_eq!(char_col_to_visual("\tx", 2, 4), 5);
    }

    #[test]
    fn char_col_to_visual_stops_at_newline() {
        // Content after a newline doesn't count toward the visual column,
        // even if char_col points past it.
        assert_eq!(char_col_to_visual("ab\ncd", 5, 4), 2);
    }

    #[test]
    fn char_col_to_visual_multibyte_chars_count_as_one_cell_each() {
        // char_col_to_visual counts *characters*, not display width — a
        // CJK char still advances the visual column by 1 here (unlike
        // display_width, which would count 2).
        let s = "中x";
        assert_eq!(char_col_to_visual(s, 1, 4), 1);
        assert_eq!(char_col_to_visual(s, 2, 4), 2);
    }

    #[test]
    fn char_col_to_visual_zero_tabstop_treated_as_one() {
        assert_eq!(char_col_to_visual("\tx", 1, 0), 1);
    }

    // ── strip_json_comments ─────────────────────────────────────────────

    #[test]
    fn strip_json_comments_removes_line_and_block_comments() {
        let input = "{\n  // a line comment\n  \"a\": 1, /* inline block */\n  \"b\": \"has // not a comment\"\n}";
        let stripped = strip_json_comments(input);
        let val: serde_json::Value = serde_json::from_str(&stripped).unwrap();
        assert_eq!(val["a"], 1);
        assert_eq!(val["b"], "has // not a comment");
    }

    #[test]
    fn strip_json_comments_preserves_newlines_in_block_comments() {
        let input = "{\n/* line1\nline2\nline3 */\n\"a\": 1\n}";
        let stripped = strip_json_comments(input);
        // Same number of lines, so a parse error's line number on the
        // stripped string still maps to the original file.
        assert_eq!(stripped.lines().count(), input.lines().count());
        let val: serde_json::Value = serde_json::from_str(&stripped).unwrap();
        assert_eq!(val["a"], 1);
    }

    #[test]
    fn strip_json_comments_multibyte_content_round_trips() {
        // RED against the original byte-indexed implementation, which
        // pushed `bytes[i] as char` per byte and corrupted any multi-byte
        // UTF-8 sequence, in or out of a string literal.
        let input = r#"{"a": "日本語 🎉", "b": "héllo"}"#;
        let stripped = strip_json_comments(input);
        assert_eq!(
            stripped, input,
            "no comments present, must round-trip exactly"
        );
        let val: serde_json::Value = serde_json::from_str(&stripped).unwrap();
        assert_eq!(val["a"], "日本語 🎉");
        assert_eq!(val["b"], "héllo");
    }

    #[test]
    fn strip_json_comments_multibyte_around_comments() {
        let input = "{\n  // 日本語 comment\n  \"a\": \"héllo 🎉\" /* 中文 block */\n}";
        let stripped = strip_json_comments(input);
        let val: serde_json::Value = serde_json::from_str(&stripped).unwrap();
        assert_eq!(val["a"], "héllo 🎉");
    }

    // ── char_cell_width / display_width ────────────────────────────────

    #[test]
    fn char_cell_width_ascii_is_one() {
        assert_eq!(char_cell_width('a'), 1);
        assert_eq!(char_cell_width(' '), 1);
    }

    #[test]
    fn char_cell_width_cjk_is_two() {
        assert_eq!(char_cell_width('日'), 2);
        assert_eq!(char_cell_width('中'), 2);
    }

    #[test]
    fn char_cell_width_combining_mark_is_zero() {
        // U+0301 COMBINING ACUTE ACCENT.
        assert_eq!(char_cell_width('\u{0301}'), 0);
    }

    #[test]
    fn display_width_sums_mixed_ascii_and_cjk() {
        assert_eq!(display_width("ab日本"), 2 + 2 + 2);
        assert_eq!(display_width(""), 0);
        assert_eq!(display_width("hello"), 5);
    }

    #[test]
    fn is_wide_char_classifies_cjk_and_ascii() {
        assert!(is_wide_char('日'));
        assert!(is_wide_char('中'));
        assert!(!is_wide_char('a'));
        assert!(!is_wide_char(' '));
        assert!(!is_wide_char('\u{0301}'));
    }

    // ── fuzzy_score ─────────────────────────────────────────────────────

    #[test]
    fn fuzzy_score_exact_match_scores_high() {
        let s = fuzzy_score("src/main.rs", "src/main.rs");
        assert!(s.is_some());
        assert!(s.unwrap().0 > 0);
    }

    #[test]
    fn fuzzy_score_subsequence_matches() {
        // "sm" is a subsequence of "src/main"
        let s = fuzzy_score("src/main", "sm");
        assert!(s.is_some());
    }

    #[test]
    fn fuzzy_score_non_subsequence_is_none() {
        assert!(fuzzy_score("src/main", "xyz").is_none());
    }

    #[test]
    fn fuzzy_score_boundary_bonus() {
        // "m" starting right after a "/" boundary should score higher than
        // a "m" buried mid-word.
        let at_boundary = fuzzy_score("src/main", "m").unwrap().0;
        let mid_word = fuzzy_score("abcmain", "m").unwrap().0;
        assert!(at_boundary > mid_word);
    }

    #[test]
    fn fuzzy_score_consecutive_run_beats_scattered() {
        // "ab" contiguous in "xxabxx" should outscore "ab" scattered
        // across "axbxxx" (a...b with a gap).
        let contiguous = fuzzy_score("xxabxx", "ab").unwrap().0;
        let scattered = fuzzy_score("axbxxx", "ab").unwrap().0;
        assert!(contiguous > scattered);
    }

    #[test]
    fn fuzzy_score_returns_match_positions() {
        let (_, positions) = fuzzy_score("abcdef", "ace").unwrap();
        assert_eq!(positions, vec![0, 2, 4]);
    }

    #[test]
    fn fuzzy_score_empty_query_matches_trivially() {
        let s = fuzzy_score("anything", "");
        assert_eq!(s, Some((0, Vec::new())));
    }

    #[test]
    fn fuzzy_score_empty_haystack_non_empty_query_is_none() {
        assert!(fuzzy_score("", "x").is_none());
    }

    #[test]
    fn fuzzy_score_treats_backslash_as_boundary() {
        let posix = fuzzy_score("src/main", "m").unwrap().0;
        let windows = fuzzy_score("src\\main", "m").unwrap().0;
        let mid = fuzzy_score("abcmain", "m").unwrap().0;
        assert_eq!(posix, windows);
        assert!(posix > mid);
    }

    // ── word_wrap ───────────────────────────────────────────────────────

    #[test]
    fn word_wrap_short_line_is_not_split() {
        assert_eq!(word_wrap("hello", 80), vec!["hello".to_string()]);
    }

    #[test]
    fn word_wrap_empty_returns_one_empty_row() {
        assert_eq!(word_wrap("", 80), vec![String::new()]);
    }

    #[test]
    fn word_wrap_zero_budget_returns_text_unmodified() {
        assert_eq!(word_wrap("hello world", 0), vec!["hello world".to_string()]);
    }

    #[test]
    fn word_wrap_breaks_at_word_boundary() {
        let wrapped = word_wrap("hello world", 7);
        assert_eq!(wrapped, vec!["hello".to_string(), "world".to_string()]);
    }

    #[test]
    fn word_wrap_packs_multiple_words_per_row() {
        let wrapped = word_wrap("the quick brown fox", 10);
        // "the quick" = 9 chars fits in 10; "brown" (5) doesn't fit after
        // "the quick" (9 + 1 + 5 = 15 > 10); "brown fox" = 9 fits.
        assert_eq!(
            wrapped,
            vec!["the quick".to_string(), "brown fox".to_string()]
        );
    }

    #[test]
    fn word_wrap_hard_breaks_a_word_longer_than_budget() {
        // No spaces at all — must degrade to the old char-chunk behaviour.
        let wrapped = word_wrap("abcde", 3);
        assert_eq!(wrapped, vec!["abc".to_string(), "de".to_string()]);
    }

    #[test]
    fn word_wrap_hard_breaks_overlong_word_within_wrapped_text() {
        // "implementation" (14 chars) alone exceeds a 10-col budget and must
        // hard-break, but short neighbouring words still wrap on spaces.
        let wrapped = word_wrap("a implementation b", 10);
        assert_eq!(
            wrapped,
            vec![
                "a".to_string(),
                "implementa".to_string(),
                "tion b".to_string(),
            ]
        );
    }

    #[test]
    fn word_wrap_never_exceeds_budget() {
        let text = "the quick brown fox jumps over the lazy dog and then some more words follow";
        for budget in 1..12 {
            for row in word_wrap(text, budget) {
                assert!(
                    row.chars().count() <= budget,
                    "row {row:?} exceeds budget {budget}"
                );
            }
        }
    }

    #[test]
    fn word_wrap_no_budget_loses_no_non_space_characters() {
        let text = "the quick brown fox jumps over the lazy dog";
        let wrapped = word_wrap(text, 6);
        let rejoined: String = wrapped.join(" ");
        let original_non_space: String = text.chars().filter(|c| !c.is_whitespace()).collect();
        let rejoined_non_space: String = rejoined.chars().filter(|c| !c.is_whitespace()).collect();
        assert_eq!(original_non_space, rejoined_non_space);
    }

    // ── word_wrap / wrap_spans: CJK + emoji display-width correctness ────
    //
    // RED against a `chars().count()`-based wrapper: five CJK
    // characters are 5 *characters* but 10 *display cells*. A
    // `chars().count()` budget of 6 would let all 5 through as "6 chars or
    // fewer" and never wrap at all; a display-width budget of 6 must wrap
    // after 3 (6 cells), not 5.

    #[test]
    fn word_wrap_cjk_wraps_at_display_width_not_char_count() {
        let text = "中文中文中文"; // 6 chars, 12 display cells
        let wrapped = word_wrap(text, 6);
        // `chars().count() <= 6` would wrongly treat this as a single
        // short row (it's 6 *characters*) instead of wrapping at 6 *cells*
        // (3 CJK characters).
        assert_eq!(
            wrapped,
            vec!["中文中".to_string(), "文中文".to_string()],
            "must wrap by display width (2 cells/char), not char count"
        );
        for row in &wrapped {
            assert!(
                display_width(row) <= 6,
                "row {row:?} exceeds the 6-cell budget"
            );
        }
    }

    #[test]
    fn word_wrap_emoji_wraps_at_display_width() {
        // Each emoji below is a single `char` but a 2-cell glyph.
        let text = "🎉🎉🎉🎉🎉";
        let wrapped = word_wrap(text, 4);
        for row in &wrapped {
            assert!(
                display_width(row) <= 4,
                "row {row:?} exceeds the 4-cell budget"
            );
        }
        // 5 emoji * 2 cells = 10 cells; budget 4 must produce at least 3 rows.
        assert!(wrapped.len() >= 3, "expected wrapping, got {wrapped:?}");
    }

    // ── wrap_spans ─────────────────────────────────────────────────────

    #[test]
    fn wrap_spans_char_policy_short_line_not_split() {
        let spans = vec![StyledSpan::plain("hello")];
        let groups = wrap_spans(&spans, 80, WrapPolicy::Char);
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].len(), 1);
        assert_eq!(groups[0][0].text, "hello");
    }

    #[test]
    fn wrap_spans_char_policy_splits_single_span_at_budget() {
        let spans = vec![StyledSpan::plain("abcde")];
        let groups = wrap_spans(&spans, 3, WrapPolicy::Char);
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0][0].text, "abc");
        assert_eq!(groups[1][0].text, "de");
    }

    #[test]
    fn wrap_spans_char_policy_preserves_style_on_split_chunks() {
        use crate::types::Color;
        let bold_span = StyledSpan {
            text: "abcdef".to_string(),
            fg: Some(Color::rgb(255, 0, 0)),
            bg: None,
            bold: true,
            italic: false,
            underline: false,
        };
        let groups = wrap_spans(&[bold_span], 4, WrapPolicy::Char);
        assert_eq!(groups.len(), 2);
        assert!(groups[0][0].bold, "first chunk must retain bold");
        assert!(groups[1][0].bold, "second chunk must retain bold");
        assert_eq!(groups[0][0].fg, Some(Color::rgb(255, 0, 0)));
        assert_eq!(groups[0][0].text, "abcd");
        assert_eq!(groups[1][0].text, "ef");
    }

    #[test]
    fn wrap_spans_char_policy_multi_span_boundary() {
        // Two 3-char spans at budget=4 → first row gets span-A (3) + one
        // char of span-B; second row gets remaining 2 chars of span-B.
        let a = StyledSpan::plain("abc");
        let b = StyledSpan::plain("def");
        let groups = wrap_spans(&[a, b], 4, WrapPolicy::Char);
        assert_eq!(groups.len(), 2);
        let row0_text: String = groups[0].iter().map(|s| s.text.as_str()).collect();
        let row1_text: String = groups[1].iter().map(|s| s.text.as_str()).collect();
        assert_eq!(row0_text, "abcd");
        assert_eq!(row1_text, "ef");
    }

    #[test]
    fn wrap_spans_empty_returns_one_empty_group() {
        let groups = wrap_spans(&[], 80, WrapPolicy::Char);
        assert_eq!(groups.len(), 1);
        assert!(groups[0].is_empty());
        let groups = wrap_spans(&[], 80, WrapPolicy::Word);
        assert_eq!(groups.len(), 1);
        assert!(groups[0].is_empty());
    }

    #[test]
    fn wrap_spans_char_policy_is_display_width_aware() {
        // Old `chars().count()`-based per-span wrapping would let a
        // 6-cell-wide (3-char) CJK span through under a 6-char budget
        // without ever consulting cell width. It must wrap at 3 chars (6
        // cells), matching `WrapPolicy::Char`'s "break exactly at the
        // display-width budget" contract.
        let spans = vec![StyledSpan::plain("中文中文")]; // 4 chars, 8 cells
        let groups = wrap_spans(&spans, 6, WrapPolicy::Char);
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0][0].text, "中文中");
        assert_eq!(groups[1][0].text, "文");
    }

    #[test]
    fn wrap_spans_word_policy_preserves_style_across_word_boundary() {
        // "aaa " (plain) + "bold text" (bold) + " bbb" (plain), wrapped at
        // a budget that must split inside the bold span.
        let a = StyledSpan::plain("aaa ");
        let bold = StyledSpan {
            text: "bold text".to_string(),
            fg: None,
            bg: None,
            bold: true,
            italic: false,
            underline: false,
        };
        let c = StyledSpan::plain(" bbb");
        let groups = wrap_spans(&[a, bold, c], 8, WrapPolicy::Word);
        // Row texts must reconstruct to the original words, and the bold
        // style must survive the split between "bold" and "text".
        let row_texts: Vec<String> = groups
            .iter()
            .map(|g| g.iter().map(|s| s.text.as_str()).collect())
            .collect();
        assert_eq!(
            row_texts,
            vec!["aaa bold".to_string(), "text bbb".to_string()]
        );
        assert!(
            groups[0].iter().any(|s| s.bold && s.text == "bold"),
            "bold must survive onto row 0: {:?}",
            groups[0]
        );
        assert!(
            groups[1].iter().any(|s| s.bold && s.text == "text"),
            "bold must survive onto row 1: {:?}",
            groups[1]
        );
        assert!(
            groups[1].iter().any(|s| !s.bold && s.text.trim() == "bbb"),
            "trailing plain text must stay non-bold: {:?}",
            groups[1]
        );
    }
}

/// Property tests for [`strip_json_comments`]: it runs on
/// foreign input (a VS Code theme file someone downloaded), so "never
/// panics" and "never mangles comment-free JSON" need to hold for more
/// than the hand-picked fixtures in `mod tests` above.
#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// No input, however malformed (an unterminated string, an
        /// unterminated block comment, a lone `/`), may panic.
        #[test]
        fn strip_json_comments_never_panics(s in ".{0,2000}") {
            let _ = strip_json_comments(&s);
        }

        /// Same, but from raw bytes reinterpreted lossily, so invalid
        /// UTF-8 byte sequences are covered too — `strip_json_comments`
        /// walks `char`s, and its char-boundary bookkeeping is exactly
        /// the kind of logic that panics ("byte index not a char
        /// boundary") when it's wrong, rather than misbehaving quietly.
        #[test]
        fn strip_json_comments_never_panics_on_lossy_bytes(bytes in prop::collection::vec(any::<u8>(), 0..2000)) {
            let s = String::from_utf8_lossy(&bytes);
            let _ = strip_json_comments(&s);
        }

        /// A string with no `//`, `/*`, or `"` in it at all has nothing
        /// for the stripper to act on — round-trips byte-for-byte.
        #[test]
        fn strip_json_comments_is_identity_when_nothing_to_strip(
            s in "[^/\"]{0,200}"
        ) {
            prop_assert_eq!(strip_json_comments(&s), s);
        }

        /// A `//`-style line comment appended after a JSON value must
        /// disappear entirely, leaving only the value plus the space
        /// that preceded `//` and the trailing newline — an exact
        /// expected output, not just "the comment text is gone" (which
        /// a comment body that happens to overlap `value` could satisfy
        /// vacuously).
        #[test]
        fn strip_json_comments_removes_line_comments(
            value in "[a-zA-Z0-9_]{1,20}",
            comment in "[^\\n\"/]{0,40}",
        ) {
            let input = format!("{value} // {comment}\n");
            let stripped = strip_json_comments(&input);
            prop_assert_eq!(stripped, format!("{value} \n"));
        }
    }
}