edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
//! Column-width computation and cell text wrapping for GFM tables; the box-drawing paint
//! lives in `renderer::render_table`.  Also parses and emits the per-table
//! `<!-- tui-columns: [...] -->` comment that persists user-set widths.
//!
//! Widths are in *terminal cells*, always through [`char_cells`] / [`str_cells`] — the unit
//! `ui::line_render` paints in, so a CJK glyph costs two.  Wrapping breaks at soft spaces and
//! beside wide glyphs ([`Joint::Glyph`]), never inside a grapheme cluster.  The prose wrap
//! (`document::wrap`) reads the same joints.
//!
//! # Width calculation strategy — min-max proportional
//!
//! The algorithm browsers use for `table-layout: auto`.  Per column, `min = longest word`
//! and `max = longest cell`; then:
//!
//! 1. Every `max` fits the budget → use the `max` widths.
//! 2. Otherwise, if the `min`s fit → distribute the slack across unpinned columns weighted
//!    by `(max - min)`, so prose columns absorb it and `min == max` columns don't move.
//! 3. Otherwise every column drops to its `min` and the table overflows horizontally — a
//!    *prose* word is never broken (a wide glyph is a word to itself).  Cells with code
//!    spans or links report a reduced `min` (`renderer::table::cell_min_width`) and
//!    hard-split instead of forcing the column wide.
//!
//! A `Some(w)` entry in `user_widths` pins that column and excludes it from the
//! distribution, so drag-set widths survive viewport pressure.  Cells wider than their
//! column word-wrap; a row's height is the maximum wrap count across its cells.

use std::num::NonZeroUsize;
use std::ops::Range;

use ratatui::text::Line;
use unicode_segmentation::UnicodeSegmentation;

use super::inline_col_map::{InlineColMap, RefLabels};

/// Minimum column width — narrower leaves no room for a `...` truncation indicator.
pub const MIN_COL_WIDTH: usize = 3;

/// Terminal cells `ch` occupies — the unit every width decision in this module and the table
/// renderer is expressed in.  Control characters contribute none, matching `unicode-width`'s
/// `None`.  Must agree with `document::wrap::char_cells`, the painter's copy.
pub fn char_cells(ch: char) -> usize {
    unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
}

/// Terminal cells `s` occupies when painted: the sum of [`char_cells`].
///
/// Deliberately not `UnicodeWidthStr::width`, which is sequence-aware (`❤️` = 2, a ZWJ family
/// = 2): `line_render::paint_row` draws char by char, a zero-width char taking no cell of its
/// own (it joins its glyph's, or is dropped), so what reaches the screen is the per-char sum
/// (`❤️` = 1, the family = 6).  Measuring any other way sizes a column for a width it is not
/// drawn at.
pub fn str_cells(s: &str) -> usize {
    s.chars().map(char_cells).sum()
}

/// [`str_cells`] over a char slice.
pub fn cells_of(chars: &[char]) -> usize {
    chars.iter().map(|&c| char_cells(c)).sum()
}

/// Whitespace that wrapping may break at or drop: everything `char::is_whitespace` matches
/// except NBSP (U+00A0).  Table cells use NBSP for code-span pad cells, which must travel with
/// the code token across a break rather than being trimmed like an inter-word space.
pub fn is_soft_break_space(ch: char) -> bool {
    ch.is_whitespace() && ch != '\u{00A0}'
}

/// Per-column overhead for `│ content ` — the separator plus one space each side.  The
/// trailing `│` at row end is [`ROW_END_OVERHEAD`].
pub const PER_COL_OVERHEAD: usize = 3;
pub const ROW_END_OVERHEAD: usize = 1;

/// Compute column widths by the min-max proportional strategy described at module level.
///
/// `cell_max_widths[row][col]` is the cell's full width, `cell_min_widths[row][col]` its
/// longest single word.  `viewport_width` is the total budget including borders and
/// padding; `usize::MAX` disables distribution and always returns `max` widths.
/// `user_widths` entries of `Some(w)` pin a column (clamped to `MIN_COL_WIDTH`) and take it
/// out of the distribution; its length must match `col_count`.
///
/// Returns `col_count` widths; when not even the `min`s fit, returns the `min`s and leaves
/// truncation-versus-overflow to the caller.
pub fn compute_widths(
    cell_max_widths: &[Vec<usize>],
    cell_min_widths: &[Vec<usize>],
    col_count: usize,
    viewport_width: usize,
    user_widths: Option<&[Option<usize>]>,
) -> Vec<usize> {
    if col_count == 0 {
        return Vec::new();
    }

    // Clamped to MIN_COL_WIDTH so a column never collapses below ellipsis room.
    let mut col_max = vec![MIN_COL_WIDTH; col_count];
    let mut col_min = vec![MIN_COL_WIDTH; col_count];
    for row in cell_max_widths {
        for (i, w) in row.iter().take(col_count).enumerate() {
            col_max[i] = col_max[i].max(*w);
        }
    }
    for row in cell_min_widths {
        for (i, w) in row.iter().take(col_count).enumerate() {
            col_min[i] = col_min[i].max(*w);
        }
    }
    for i in 0..col_count {
        if col_min[i] > col_max[i] {
            col_max[i] = col_min[i];
        }
    }

    let mut widths = col_max.clone();
    let mut pinned = vec![false; col_count];
    if let Some(uw) = user_widths {
        for (i, w) in uw.iter().take(col_count).enumerate() {
            if let Some(val) = w {
                widths[i] = (*val).max(MIN_COL_WIDTH);
                pinned[i] = true;
            }
        }
    }

    let border_budget = PER_COL_OVERHEAD * col_count + ROW_END_OVERHEAD;
    let pinned_total: usize = widths
        .iter()
        .enumerate()
        .filter(|(i, _)| pinned[*i])
        .map(|(_, w)| *w)
        .sum();

    // With `viewport_width == usize::MAX` this stays `usize::MAX`, so the natural-fit
    // branch always wins.
    let available = viewport_width
        .saturating_sub(border_budget)
        .saturating_sub(pinned_total);

    let unpinned: Vec<usize> = (0..col_count).filter(|i| !pinned[*i]).collect();
    let unpinned_max_total: usize = unpinned.iter().map(|i| col_max[*i]).sum();
    let unpinned_min_total: usize = unpinned.iter().map(|i| col_min[*i]).sum();

    if unpinned_max_total <= available {
        for &i in &unpinned {
            widths[i] = col_max[i];
        }
    } else if unpinned_min_total <= available {
        let slack = available - unpinned_min_total;
        let total_weight: usize = unpinned.iter().map(|i| col_max[*i] - col_min[*i]).sum();
        if let Some(total_weight) = NonZeroUsize::new(total_weight) {
            // Weighted integer division; the leftover cells go to the largest residuals
            // below, so every available cell is used.
            let mut residuals: Vec<(usize, usize)> = Vec::with_capacity(unpinned.len());
            let mut assigned = 0usize;
            for &i in &unpinned {
                let weight = col_max[i] - col_min[i];
                let numer = slack * weight;
                let extra = numer / total_weight;
                let remainder = numer % total_weight;
                widths[i] = col_min[i] + extra;
                assigned += extra;
                residuals.push((i, remainder));
            }
            // Descending residual, ties broken on index so the result is deterministic.
            residuals.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
            let mut leftover = slack.saturating_sub(assigned);
            for (i, _) in residuals {
                if leftover == 0 {
                    break;
                }
                if widths[i] < col_max[i] {
                    widths[i] += 1;
                    leftover -= 1;
                }
            }
        } else {
            // Defensive only: zero total weight means every `min == max`, which the
            // natural-fit branch above would already have claimed.  Kept so a change to
            // either total can't turn a divide-by-zero into a panic.
            for &i in &unpinned {
                widths[i] = col_min[i];
            }
        }
    } else {
        // Even the mins don't fit; the caller truncates or accepts overflow.
        for &i in &unpinned {
            widths[i] = col_min[i];
        }
    }

    widths
}

// ── Wrapping ────────────────────────────────────────────────────────────────

/// What lies between two adjacent chars, as far as wrapping is concerned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Joint {
    /// Inside a grapheme cluster: never a break, not even a hard split.
    Inside,
    /// Between clusters: a hard split may cut here.
    Cluster,
    /// Beside a wide glyph with no whitespace on either side: a break as good as a space.
    /// CJK carries no inter-word spaces, so its text breaks between any two glyphs, except
    /// before closing punctuation ([`no_break_before`]), after opening punctuation
    /// ([`no_break_after`]), or beside a no-break char ([`is_no_break_char`]) or a quote
    /// ([`is_ambiguous_quote`]).
    Glyph,
}

/// The [`Joint`] before each index of `chars`, over `0..=chars.len()` (both ends are
/// [`Joint::Cluster`]).  A cluster is wide when it paints more than one cell.  The all-ASCII
/// fast path skips segmentation: every joint is `Cluster`.
pub fn joints(chars: &[char]) -> Vec<Joint> {
    if chars.iter().all(char::is_ascii) {
        return vec![Joint::Cluster; chars.len() + 1];
    }
    joints_in_str(&chars.iter().collect::<String>(), chars.len())
}

/// [`joints`] over `text`, which holds `n_chars` chars, for a caller that already has the text
/// as a string (the prose wrap, on its per-keystroke path).  No ASCII fast path: that is the
/// caller's.
pub fn joints_in_str(text: &str, n_chars: usize) -> Vec<Joint> {
    let mut out = vec![Joint::Cluster; n_chars + 1];
    let mut idx = 0usize;
    // The previous cluster's last char, and whether that cluster was wide.
    let mut prev: Option<(char, bool)> = None;
    for cluster in text.graphemes(true) {
        let len = cluster.chars().count();
        let wide = str_cells(cluster) > 1;
        for joint in &mut out[idx + 1..idx + len] {
            *joint = Joint::Inside;
        }
        if let (Some((before, prev_wide)), Some(after)) = (prev, cluster.chars().next()) {
            let spaced = before.is_whitespace() || after.is_whitespace();
            let bound = no_break_after(before)
                || no_break_before(after)
                || [before, after]
                    .into_iter()
                    .any(|c| is_no_break_char(c) || is_ambiguous_quote(c));
            if (wide || prev_wide) && !spaced && !bound {
                out[idx] = Joint::Glyph;
            }
        }
        prev = cluster.chars().last().map(|c| (c, wide));
        idx += len;
    }
    out
}

/// Chars that carry no break on either side (UAX #14 GL / WJ).  A no-break space is *defined*
/// that way, and code blocks pad blank lines with U+00A0 — breaking there would split padding
/// emitted precisely to keep a row intact.  Shared with the prose wrap (`document::wrap`).
pub fn is_no_break_char(ch: char) -> bool {
    matches!(ch, '\u{a0}' | '\u{202f}' | '\u{2060}' | '\u{feff}')
}

/// Quotes whose direction the char alone doesn't give (UAX #14 QU): `"`, `'`, and `’`, which is
/// also an apostrophe (`’90s`).  No glyph break forms beside one, so a quote stays with the
/// glyph it wraps.  The prose wrap (`document::wrap`) also reads their direction from the
/// neighboring words.
pub fn is_ambiguous_quote(ch: char) -> bool {
    matches!(ch, '"' | '\'' | '\u{2019}')
}

/// Chars a row may not start with: closing brackets and quotes, sentence punctuation, and the
/// CJK marks that lean on the glyph before them (the prolonged-sound mark, iteration marks).  An
/// abridged UAX #14 CL / CP / EX / IS / NS, Japanese *kinsoku*: a break before one strands it at
/// the head of the next row.  Shared with the prose wrap (`document::wrap`).
pub fn no_break_before(ch: char) -> bool {
    matches!(
        ch,
        ')' | ']'
            | '}'
            | '.'
            | ','
            | ':'
            | ';'
            | '!'
            | '?'
            | '\u{201d}' // ”
            | '\u{bb}' // »
            | '\u{2026}' // …
            | '\u{2025}' // ‥
            | '\u{3001}' // 、
            | '\u{3002}' // 。
            | '\u{3005}' // 々
            | '\u{3009}' // 〉
            | '\u{300b}' // 》
            | '\u{300d}' // 」
            | '\u{300f}' // 』
            | '\u{3011}' // 】
            | '\u{3015}' // 〕
            | '\u{3017}' // 〗
            | '\u{3019}' // 〙
            | '\u{301f}' // 〟
            | '\u{309d}' // ゝ
            | '\u{309e}' // ゞ
            | '\u{30fb}' // ・
            | '\u{30fc}' // ー
            | '\u{30fd}' // ヽ
            | '\u{30fe}' // ヾ
            | '\u{ff01}' // !
            | '\u{ff09}' // )
            | '\u{ff0c}' // ,
            | '\u{ff0e}' // .
            | '\u{ff1a}' // :
            | '\u{ff1b}' // ;
            | '\u{ff1f}' // ?
            | '\u{ff3d}' // ]
            | '\u{ff5d}' // }
            | '\u{ff63}' // 」
    )
}

/// Chars a row may not end with: opening brackets and quotes (UAX #14 OP, abridged), which
/// belong with the text they open.  Shared with the prose wrap (`document::wrap`).
pub fn no_break_after(ch: char) -> bool {
    matches!(
        ch,
        '(' | '['
            | '{'
            | '\u{2018}' // ‘
            | '\u{201c}' // “
            | '\u{ab}' // «
            | '\u{bf}' // ¿
            | '\u{a1}' // ¡
            | '\u{3008}' // 〈
            | '\u{300a}' // 《
            | '\u{300c}' // 「
            | '\u{300e}' // 『
            | '\u{3010}' // 【
            | '\u{3014}' // 〔
            | '\u{3016}' // 〖
            | '\u{3018}' // 〘
            | '\u{301d}' // 〝
            | '\u{ff08}' // (
            | '\u{ff3b}' // [
            | '\u{ff5b}' // {
            | '\u{ff62}' // 「
    )
}

/// Char index where the last grapheme cluster of `chars` begins; 0 when empty.  Where a cursor
/// clamped onto "the last char" must land: the last *char* may be a zero-width mark (VS16, a
/// combining accent) that has no cell of its own to draw the cursor on.
pub fn last_cluster_start(chars: &[char]) -> usize {
    let joints = joints(chars);
    (0..chars.len())
        .rev()
        .find(|&i| joints[i] != Joint::Inside)
        .unwrap_or(0)
}

/// Char ranges of the words in `chars`: maximal runs free of [soft
/// spaces](is_soft_break_space), further split at every [`Joint::Glyph`].  A word is the unit
/// a wrap never breaks unless it alone overflows a row — so the longest one is a cell's width
/// floor.
pub fn word_ranges(chars: &[char]) -> Vec<Range<usize>> {
    let joints = joints(chars);
    word_ranges_with(chars, &joints)
}

fn word_ranges_with(chars: &[char], joints: &[Joint]) -> Vec<Range<usize>> {
    let mut words = Vec::new();
    let mut i = 0usize;
    while i < chars.len() {
        if is_soft_break_space(chars[i]) {
            i += 1;
            continue;
        }
        let start = i;
        i += 1;
        while i < chars.len() && !is_soft_break_space(chars[i]) && joints[i] != Joint::Glyph {
            i += 1;
        }
        words.push(start..i);
    }
    words
}

/// Wrap `chars` into rows of at most `width` cells, as char ranges into `chars`.
///
/// Greedy over [`word_ranges`], each word carrying the soft spaces before it.  A row other than
/// the first drops those leading spaces (they are drawn on neither row), so a range's `start`
/// is where its first visible char sits; trailing spaces after the last word are dropped too.
/// A word wider than `width` is hard-split at cluster boundaries, preferring a cut just after
/// punctuation ([`split_at_clusters`]), and closes its last row.  Never empty; `width == 0`
/// returns everything as one row.
///
/// The one wrap every table consumer shares — the renderer's styled cells, the click mapper
/// and the raw-reveal overlay — so their rows agree by construction.
pub fn wrap_ranges(chars: &[char], width: usize) -> Vec<Range<usize>> {
    if width == 0 || chars.is_empty() {
        return vec![Range {
            start: 0,
            end: chars.len(),
        }];
    }
    let joints = joints(chars);
    let mut rows: Vec<Range<usize>> = Vec::new();
    // The open row and its width in cells.
    let mut current: Option<(Range<usize>, usize)> = None;
    let mut token_start = 0usize;
    for word in word_ranges_with(chars, &joints) {
        let token = token_start..word.end;
        token_start = word.end;
        let w = cells_of(&chars[token.clone()]);
        if let Some((row, row_w)) = current.as_mut() {
            if *row_w + w <= width {
                row.end = token.end;
                *row_w += w;
                continue;
            }
        }
        if let Some((row, _)) = current.take() {
            rows.push(row);
        }
        // Leading spaces survive only at the very start of the text.
        let start = if rows.is_empty() {
            token.start
        } else {
            word.start
        };
        let w = cells_of(&chars[start..token.end]);
        if w <= width {
            current = Some((start..token.end, w));
        } else {
            split_at_clusters(chars, &joints, start..token.end, width, true, &mut rows);
        }
    }
    if let Some((row, _)) = current {
        rows.push(row);
    }
    if rows.is_empty() {
        rows.push(0..0);
    }
    rows
}

/// Wrap a cell's plain text to `width` terminal cells, one `String` per visual row.  See
/// [`wrap_ranges`].
pub fn wrap_cell(text: &str, width: usize) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    wrap_ranges(&chars, width)
        .into_iter()
        .map(|r| chars[r].iter().collect())
        .collect()
}

/// [`wrap_cell`] plus the char index in `text` where each row begins — `RenderedView` maps
/// a cursor offset inside a wrapped cell back to a (sub-line, column) with it.
///
/// Whitespace at a break point is drawn on neither row, so continuation rows start at the
/// first non-whitespace char after the previous row, and a cursor on a dropped space maps
/// to the next row's start.
pub fn wrap_cell_with_indices(text: &str, width: usize) -> Vec<(usize, String)> {
    let chars: Vec<char> = text.chars().collect();
    wrap_ranges(&chars, width)
        .into_iter()
        .map(|r| (r.start, chars[r].iter().collect()))
        .collect()
}

/// Hard-wrap `chars` into rows of at most `width` cells, as char ranges into `chars`: cuts fall
/// between grapheme clusters only, with no preference for words or punctuation, and every
/// space is kept.  So a row's boundaries depend only on glyph widths — what the raw-reveal
/// chunk overlay scrolls through.  A single cluster wider than `width` gets a row of its own.
/// Never empty; `width == 0` returns everything as one row.
pub fn hard_wrap_ranges(chars: &[char], width: usize) -> Vec<Range<usize>> {
    if width == 0 || chars.is_empty() {
        return vec![Range {
            start: 0,
            end: chars.len(),
        }];
    }
    let joints = joints(chars);
    let mut rows = Vec::new();
    split_at_clusters(chars, &joints, 0..chars.len(), width, false, &mut rows);
    rows
}

/// Push rows of at most `width` cells covering `range`, cutting only at cluster boundaries.
/// With `prefer_punctuation` a cut moves to just after punctuation ([`preferred_cut`]) when
/// the remainder still fits beside the next cluster, so identifiers, paths, and URLs don't
/// split mid-token.  A single cluster wider than `width` still gets a row of its own, so the
/// split makes progress; the caller truncates it.
fn split_at_clusters(
    chars: &[char],
    joints: &[Joint],
    range: Range<usize>,
    width: usize,
    prefer_punctuation: bool,
    rows: &mut Vec<Range<usize>>,
) {
    let mut start = range.start;
    let mut w = 0usize;
    let mut i = range.start;
    while i < range.end {
        let mut next = i + 1;
        while next < range.end && joints[next] == Joint::Inside {
            next += 1;
        }
        let cw = cells_of(&chars[i..next]);
        if w + cw > width && i > start {
            let mut cut = i;
            if prefer_punctuation {
                let p = start + preferred_cut(i - start, |k| chars[start + k]);
                if joints[p] != Joint::Inside && cells_of(&chars[p..i]) + cw <= width {
                    cut = p;
                }
            }
            rows.push(start..cut);
            start = cut;
            w = cells_of(&chars[start..i]);
        }
        w += cw;
        i = next;
    }
    rows.push(start..range.end);
}

/// Characters a hard-split prefers to break *after* — tuned for identifiers, paths, URLs.
pub fn is_break_after(ch: char) -> bool {
    matches!(
        ch,
        '_' | '-'
            | '.'
            | ','
            | ';'
            | ':'
            | '/'
            | '\\'
            | '('
            | ')'
            | '['
            | ']'
            | '{'
            | '}'
            | '='
            | '&'
            | '?'
            | '#'
            | '@'
    )
}

/// Cut index for a hard-split chunk of `len` chars (exposed via `char_at`): just after the
/// last [`is_break_after`] character in the *trailing half*, else `len`.  Limiting the scan
/// to the trailing half keeps every row at least half-width, so a punctuation-dense token
/// can't degenerate into confetti rows.
pub fn preferred_cut(len: usize, char_at: impl Fn(usize) -> char) -> usize {
    let lookback = len / 2;
    for back in 0..lookback {
        let i = len - 1 - back;
        if is_break_after(char_at(i)) {
            return i + 1;
        }
    }
    len
}

// ── Column-width comment parsing ────────────────────────────────────────────

/// Parse a `<!-- tui-columns: [20, _, 30] -->` comment: `Some(w)` per pinned column,
/// `None` per `_` placeholder.  `None` overall when absent, malformed, or all-`_` (which
/// carries no information).
pub fn parse_column_widths_comment(text: &str) -> Option<Vec<Option<usize>>> {
    let start = text.find("<!-- tui-columns:")?;
    let after = &text[start + "<!-- tui-columns:".len()..];
    let end_rel = after.find("-->")?;
    let body = after[..end_rel].trim();
    let inner = body.strip_prefix('[')?.strip_suffix(']')?;
    let mut widths = Vec::new();
    for part in inner.split(',') {
        let s = part.trim();
        if s.is_empty() {
            continue;
        }
        if s == "_" {
            widths.push(None);
        } else {
            widths.push(Some(s.parse::<usize>().ok()?));
        }
    }
    if widths.is_empty() || widths.iter().all(Option::is_none) {
        None
    } else {
        Some(widths)
    }
}

/// Emit a `<!-- tui-columns: [20, _, 30] -->` comment; `None` becomes `_` (auto-sized).
pub fn format_column_widths_comment(widths: &[Option<usize>]) -> String {
    let body: Vec<String> = widths
        .iter()
        .map(|w| match w {
            Some(v) => v.to_string(),
            None => "_".to_owned(),
        })
        .collect();
    format!("<!-- tui-columns: [{}] -->", body.join(", "))
}

// ── Pipe position / cell-range helpers ──────────────────────────────────────
//
// Shared by `TableView`'s mouse hit-testing and `RenderedView`'s cell-scoped raw reveal.
// Pure functions of the raw row text and the rendered `Line` — no editor-state coupling.

/// Char positions of unescaped `|` in a raw table row (GFM: `\|` escapes, `\\|` does not).
pub fn raw_pipe_positions(row: &str) -> Vec<usize> {
    let mut positions = Vec::new();
    let mut escaped = false;
    for (i, ch) in row.chars().enumerate() {
        if ch == '|' && !escaped {
            positions.push(i);
            escaped = false;
        } else if ch == '\\' {
            escaped = !escaped;
        } else {
            escaped = false;
        }
    }
    positions
}

/// The cells of raw table row `row` as GFM splits them: the char ranges between its unescaped
/// pipes, pipes excluded.  Counting starts at `content_col`, the row's content column (its
/// origin's `raw_col`), so a container prefix never contributes a pipe: a quote's `> `, an
/// item's indent, a footnote's `[^a|b]: `.  Edge pipes are optional, as in GFM: without a
/// leading one the first cell starts at the content, without a trailing one the last runs to
/// the line's end.  Empty for a blank row.
pub fn raw_cells(row: &str, content_col: usize) -> Vec<Range<usize>> {
    let chars: Vec<char> = row.chars().collect();
    let mut end = chars.len();
    while end > content_col && chars[end - 1].is_whitespace() {
        end -= 1;
    }
    let mut start = content_col.min(end);
    while start < end && chars[start].is_whitespace() {
        start += 1;
    }
    if start >= end {
        return Vec::new();
    }
    let mut pipes: Vec<usize> = raw_pipe_positions(row)
        .into_iter()
        .filter(|p| (start..end).contains(p))
        .collect();
    let open = if pipes.first() == Some(&start) {
        pipes.remove(0);
        start + 1
    } else {
        start
    };
    let close = if end > open && pipes.last() == Some(&(end - 1)) {
        pipes.pop();
        end - 1
    } else {
        end
    };
    let mut cells = Vec::with_capacity(pipes.len() + 1);
    let mut from = open;
    for p in pipes {
        cells.push(from..p);
        from = p + 1;
    }
    cells.push(from..close.max(from));
    cells
}

/// The raw cells to pair with the `drawn` cells a rendered row of cells shows: the first `drawn`
/// of [`raw_cells`].  GFM drops a row's cells past the header's count, and the renderer draws
/// none for them; a row with fewer cells keeps them all, and the empty cells the renderer pads
/// it with have no raw cell.  `None` off a row of cells (nothing drawn, or a blank raw row).
pub fn paired_raw_cells(row: &str, content_col: usize, drawn: usize) -> Option<Vec<Range<usize>>> {
    let mut cells = raw_cells(row, content_col);
    cells.truncate(drawn);
    (!cells.is_empty()).then_some(cells)
}

/// The index of the cell in non-empty `cells` holding raw column `col`.  A column on a pipe
/// belongs to the cell before it, and one in the prefix to the first.
fn raw_cell_at(cells: &[Range<usize>], col: usize) -> usize {
    cells
        .iter()
        .take_while(|c| c.start <= col)
        .count()
        .saturating_sub(1)
}

/// The drawn cell that raw column `col` of `row` shows in, and that cell's raw range, the cells
/// paired as [`paired_raw_cells`] pairs them.  Usually [`raw_cell_at`]'s.  On a row with fewer
/// cells than the `drawn` ones, a column past its closing pipe (the row's end, where typing adds
/// a cell, and where a click in a missing cell lands) shows in the first cell it lacks, as an
/// empty range at `col`; without a closing pipe, typing there extends the last cell, which keeps
/// it.  `None` off a row of cells, and for a column in a cell GFM drops (past the header's
/// count): no drawn cell shows it, so the caller reveals the whole line instead.
pub fn drawn_cell_at(
    row: &str,
    content_col: usize,
    drawn: usize,
    col: usize,
) -> Option<(usize, Range<usize>)> {
    let mut cells = raw_cells(row, content_col);
    let dropped = cells.len() > drawn;
    cells.truncate(drawn);
    let last = cells.last()?;
    if col > last.end {
        if dropped {
            return None;
        }
        // `raw_cells` ends the last cell on the closing pipe when there is one.
        if cells.len() < drawn && row.chars().nth(last.end) == Some('|') {
            return Some((cells.len(), col..col));
        }
    }
    let i = raw_cell_at(&cells, col);
    Some((i, cells[i].clone()))
}

/// Char positions of `│` box-drawing pipe characters in a rendered line.
pub fn rendered_pipe_positions(line: &Line<'_>) -> Vec<usize> {
    let mut positions = Vec::new();
    let mut col = 0usize;
    for span in &line.spans {
        for ch in span.content.chars() {
            if ch == '│' {
                positions.push(col);
            }
            col += 1;
        }
    }
    positions
}

/// Cell columns of the `│` pipes in a rendered line — [`rendered_pipe_positions`] in screen
/// geometry, which differs from it once a wide glyph sits to the left.  What a painter
/// addressing buffer cells needs; a `cursor_col_override` wants the char positions.
pub fn rendered_pipe_cells(line: &Line<'_>) -> Vec<usize> {
    let mut positions = Vec::new();
    let mut col = 0usize;
    for span in &line.spans {
        for ch in span.content.chars() {
            if ch == '│' {
                positions.push(col);
            }
            col += char_cells(ch);
        }
    }
    positions
}

/// Where the char at raw column `raw_col` of a table row shows on the rendered row: the wrap
/// sub-line holding its glyph and its char column there (a `cursor_col_override`).  `row_lines`
/// are the row's rendered sub-lines.  Columns go through the cell's [`CellContent`], so a char
/// after hidden markers (`**b** x`) lands on its glyph, as a click there lands on the char.  A
/// column in a cell's leading whitespace lands on the pad space; one past the content, past its
/// last glyph, never beyond the cell's trailing pad.  The cell is found as the cell reveal finds
/// it, by [`drawn_cell_at`] from `content_col`.  `None` off a row of cells (alignment row,
/// border) and in a cell GFM drops, which no drawn cell shows.
pub fn table_raw_col_to_rendered(
    raw_row: &str,
    content_col: usize,
    row_lines: &[Line<'_>],
    raw_col: usize,
    labels: &RefLabels,
) -> Option<(usize, usize)> {
    let first = row_lines.first()?;
    let pipe_cells = rendered_pipe_cells(first);
    let drawn = pipe_cells.len().saturating_sub(1);
    let raw_chars: Vec<char> = raw_row.chars().collect();
    let (cell_idx, raw_cell) =
        drawn_cell_at(raw_row, content_col, drawn, raw_col.min(raw_chars.len()))?;
    let raw_cell_start = raw_cell.start;
    let width = pipe_cells[cell_idx + 1].saturating_sub(pipe_cells[cell_idx] + 3);
    let cell = CellContent::new(&raw_chars[raw_cell], width, labels);

    let offset = raw_col.saturating_sub(raw_cell_start);
    // `None` for the pad space, else the char index into the sub-line's chunk.
    let (sub, in_chunk) = match offset.checked_sub(cell.leading) {
        None => (0, None),
        Some(k) => {
            let rendered = match k.checked_sub(cell.raw_len) {
                None => cell.map.raw_to_rendered(k),
                Some(past) => cell.map.rendered_len() + past,
            };
            // Whitespace a wrap drops at a break stays at the end of the chunk before it.
            let sub = cell
                .chunks
                .iter()
                .rposition(|(start, _)| *start <= rendered)
                .unwrap_or(0);
            let (start, text) = &cell.chunks[sub];
            let pos = rendered - start;
            let pos = if sub + 1 < cell.chunks.len() {
                pos.min(text.chars().count())
            } else {
                pos
            };
            (sub.min(row_lines.len() - 1), Some(pos))
        }
    };
    // Char positions differ per sub-line once a wide glyph sits left of the cell.
    let pipes = rendered_pipe_positions(&row_lines[sub]);
    let (open, close) = (*pipes.get(cell_idx)?, *pipes.get(cell_idx + 1)?);
    let col = in_chunk.map_or(open + 1, |pos| open + 2 + pos);
    Some((sub, col.min(close.saturating_sub(1))))
}

/// Cells to paint a revealed raw cell right of its cell's left edge: 1 for a cell with no
/// whitespace after its opening pipe (`a | b`'s first cell, an empty one a short row lacks), so
/// its text lands on the rendered text it replaces rather than on the pad cell, where a click
/// maps it; 0 for a cell whose leading space fills the pad.
pub fn unpadded_cell_shift(raw_cell: &str) -> usize {
    usize::from(!raw_cell.starts_with(char::is_whitespace))
}

/// One table cell's content as `render_table_row` lays it out: the raw cell (the chars between
/// its pipes) trimmed, an [`InlineColMap`] from that to the marker-collapsed text the renderer
/// shows, and that text's wrap chunks at the cell's width.  The click and the overlay both read
/// cells through it, so they agree with the renderer on which chunk holds which char even where
/// inline markers (`**`, backticks, a link's URL) are hidden.
pub struct CellContent {
    /// Raw chars of whitespace before the content, within the cell.
    pub leading: usize,
    /// Raw chars of content, after `leading`.
    pub raw_len: usize,
    /// Raw content (past `leading`) ⇄ rendered content.
    pub map: InlineColMap,
    /// `(rendered char start, text)` of each wrap chunk; at least one.
    pub chunks: Vec<(usize, String)>,
}

impl CellContent {
    /// `raw_cell` is the cell's raw chars between its pipes, `width` its content width in
    /// terminal cells, and `labels` the document's, so a reference link collapses as it renders.
    pub fn new(raw_cell: &[char], width: usize, labels: &RefLabels) -> Self {
        let leading = raw_cell.iter().take_while(|c| c.is_whitespace()).count();
        let trailing = raw_cell[leading..]
            .iter()
            .rev()
            .take_while(|c| c.is_whitespace())
            .count();
        let content = &raw_cell[leading..raw_cell.len() - trailing];
        let map = InlineColMap::build_inline(&content.iter().collect::<String>(), labels);
        // The rendered text, as raw chars at the positions the map keeps: what the renderer wraps
        // (a smart-punctuation glyph stands in as its run's first char, the same width).
        let rendered: String = map.rendered_to_raw_vec()[..map.rendered_len()]
            .iter()
            .map(|&raw| content.get(raw).copied().unwrap_or(' '))
            .collect();
        Self {
            leading,
            raw_len: content.len(),
            map,
            chunks: wrap_cell_with_indices(&rendered, width.max(1)),
        }
    }
}

/// Map a raw char-column range to the rendered segments visible on wrap-chunk `sub`, in char
/// columns of `rendered_line`.  Cells wrap independently, so each contributes at most one
/// segment, mapped through the cell's [`CellContent`].  Used by the selection / search overlay
/// painter.  Cells are [`paired_raw_cells`] from `content_col`; empty off a row of cells.
pub fn table_raw_col_range_to_rendered_segments(
    raw_row: &str,
    content_col: usize,
    rendered_line: &Line<'_>,
    raw_start: usize,
    raw_end: usize,
    sub: usize,
    labels: &RefLabels,
) -> Vec<(usize, usize)> {
    let rendered_pipes = rendered_pipe_positions(rendered_line);
    let rendered_cells = rendered_pipe_cells(rendered_line);
    let Some(cells) =
        paired_raw_cells(raw_row, content_col, rendered_pipes.len().saturating_sub(1))
    else {
        return Vec::new();
    };
    let raw_chars: Vec<char> = raw_row.chars().collect();
    let mut out = Vec::new();
    for (i, raw_cell) in cells.into_iter().enumerate() {
        let raw_cell_start = raw_cell.start;
        // Wrap at the cell's width in cells, as the renderer did; the segment is char columns.
        let width = rendered_cells[i + 1].saturating_sub(rendered_cells[i] + 3);
        let cell = CellContent::new(&raw_chars[raw_cell], width, labels);
        let Some((chunk_start, chunk_text)) = cell.chunks.get(sub) else {
            continue;
        };
        let content_start = raw_cell_start + cell.leading;
        let to_rendered = |raw: usize| {
            cell.map
                .raw_to_rendered(raw.saturating_sub(content_start).min(cell.raw_len))
        };
        let s = to_rendered(raw_start).max(*chunk_start);
        let e = to_rendered(raw_end).min(chunk_start + chunk_text.chars().count());
        if s >= e {
            continue;
        }
        let rend_chunk_start = rendered_pipes[i] + 2;
        out.push((
            rend_chunk_start + (s - chunk_start),
            rend_chunk_start + (e - chunk_start),
        ));
    }
    out
}

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

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

    /// mins == maxes (single-word cells), exercising the "no-wrap" path.
    fn maxes_eq_mins(cells: Vec<Vec<usize>>) -> (Vec<Vec<usize>>, Vec<Vec<usize>>) {
        let mins = cells.clone();
        (cells, mins)
    }

    #[test]
    fn compute_widths_uses_natural_when_room_available() {
        let (maxes, mins) = maxes_eq_mins(vec![vec![2, 4, 3], vec![3, 5, 2]]);
        let widths = compute_widths(&maxes, &mins, 3, 80, None);
        assert_eq!(widths, vec![3, 5, 3]); // clamped to MIN where natural was 2
    }

    #[test]
    fn compute_widths_returns_mins_when_max_exceeds_budget_and_no_slack() {
        // Single-word cells: min == max, so no slack — the table overflows rather than
        // truncating.
        let (maxes, mins) = maxes_eq_mins(vec![vec![10, 10, 10]]);
        let widths = compute_widths(&maxes, &mins, 3, 20, None);
        assert_eq!(widths, vec![10, 10, 10]);
        assert!(widths.iter().all(|w| *w >= MIN_COL_WIDTH));
    }

    #[test]
    fn compute_widths_distributes_slack_proportionally_to_max_minus_min() {
        // Col 0 is prose (max 20, min 4); col 1 has no flexibility (min == max == 5), so
        // col 0 absorbs all the slack.
        let maxes = vec![vec![20, 5]];
        let mins = vec![vec![4, 5]];
        // border 7, viewport 22 → slack 6, all of it weighted onto col 0.
        let widths = compute_widths(&maxes, &mins, 2, 22, None);
        assert_eq!(widths, vec![10, 5]);
    }

    #[test]
    fn compute_widths_caps_each_column_at_max_during_distribution() {
        // Wide enough that the proportional formula would overshoot col 0's max.
        let maxes = vec![vec![8, 8]];
        let mins = vec![vec![3, 3]];
        let widths = compute_widths(&maxes, &mins, 2, 23, None);
        assert_eq!(widths, vec![8, 8]);
    }

    #[test]
    fn compute_widths_respects_user_override() {
        let (maxes, mins) = maxes_eq_mins(vec![vec![1, 1, 1]]);
        let widths = compute_widths(&maxes, &mins, 3, 80, Some(&[Some(15), Some(7), Some(20)]));
        assert_eq!(widths, vec![15, 7, 20]);
    }

    #[test]
    fn compute_widths_clamps_user_override_to_min() {
        let (maxes, mins) = maxes_eq_mins(vec![vec![1, 1]]);
        let widths = compute_widths(&maxes, &mins, 2, 80, Some(&[Some(1), Some(0)])); // both below MIN
        assert_eq!(widths, vec![MIN_COL_WIDTH, MIN_COL_WIDTH]);
    }

    #[test]
    fn compute_widths_mixes_pinned_and_auto_columns() {
        let (maxes, mins) = maxes_eq_mins(vec![vec![3, 6]]);
        let widths = compute_widths(&maxes, &mins, 2, 80, Some(&[Some(5), None]));
        assert_eq!(widths, vec![5, 6]);
    }

    #[test]
    fn compute_widths_shrink_leaves_pinned_columns_alone() {
        // Pinned col 0 keeps its width; col 1 distributes from what's left, landing in
        // [4, 10].
        let maxes = vec![vec![10, 10]];
        let mins = vec![vec![10, 4]];
        let widths = compute_widths(&maxes, &mins, 2, 17, Some(&[Some(8), None]));
        assert_eq!(widths[0], 8); // pinned
        assert!(widths[1] >= MIN_COL_WIDTH);
        assert!(widths[1] <= 10);
    }

    #[test]
    fn compute_widths_narrow_prose_column_stays_at_min_with_no_slack() {
        // A viewport with no slack at all: the column gets exactly its min.
        let maxes = vec![vec![12]];
        let mins = vec![vec![3]];
        let widths = compute_widths(&maxes, &mins, 1, 7, None);
        assert_eq!(widths, vec![3]);
    }

    #[test]
    fn wrap_cell_breaks_on_spaces() {
        let rows = wrap_cell("hello world foo bar", 11);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].trim(), "hello world");
        assert_eq!(rows[1].trim(), "foo bar");
    }

    #[test]
    fn wrap_cell_empty_returns_one_empty_row() {
        let rows = wrap_cell("", 10);
        assert_eq!(rows, vec!["".to_owned()]);
    }

    #[test]
    fn wrap_cell_hard_splits_long_word() {
        let rows = wrap_cell("supercalifragilistic", 6);
        assert!(rows.len() >= 2);
        for r in &rows {
            assert!(str_cells(r) <= 6);
        }
        let joined: String = rows.join("");
        assert_eq!(joined, "supercalifragilistic");
    }

    #[test]
    fn wrap_cell_hard_split_prefers_punctuation_break() {
        // A naive cut lands at char 10; the `_` at index 6 is in the trailing half, so
        // the cut moves just after it.
        let rows = wrap_cell("really_long_name", 10);
        assert_eq!(rows, vec!["really_", "long_name"]);
    }

    #[test]
    fn wrap_cell_hard_split_falls_back_to_full_width_without_punctuation() {
        let rows = wrap_cell("abcdefghijklmnop", 10);
        assert_eq!(rows, vec!["abcdefghij", "klmnop"]);
    }

    // ── Width unit and break opportunities ─────────────────────────────────

    const FAMILY: &str = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";

    fn chars(s: &str) -> Vec<char> {
        s.chars().collect()
    }

    fn words(s: &str) -> Vec<String> {
        let cs = chars(s);
        word_ranges(&cs)
            .into_iter()
            .map(|r| cs[r].iter().collect())
            .collect()
    }

    /// The painter's unit, not `UnicodeWidthStr`'s: `line_render::paint_row` gives zero-width
    /// chars no cell of their own, so VS16 widens nothing and a ZWJ family paints as its three
    /// members.
    #[test]
    fn str_cells_is_the_per_char_sum_the_painter_draws() {
        assert_eq!(str_cells("日本"), 4);
        assert_eq!(str_cells("\u{2764}\u{FE0F}"), 1);
        assert_eq!(str_cells(FAMILY), 6);
        assert_eq!(str_cells("e\u{301}"), 1);
        assert_eq!(str_cells("ab\u{7}"), 2, "control chars take no cell");
    }

    #[test]
    fn joints_on_ascii_are_all_cluster_boundaries() {
        assert!(joints(&chars("ab cd")).iter().all(|j| *j == Joint::Cluster));
    }

    #[test]
    fn joints_break_on_both_sides_of_a_wide_glyph() {
        use Joint::*;
        assert_eq!(
            joints(&chars("a日本b")),
            vec![Cluster, Glyph, Glyph, Glyph, Cluster]
        );
    }

    #[test]
    fn joints_never_break_inside_a_cluster() {
        use Joint::*;
        let js = joints(&chars(FAMILY));
        assert_eq!(js, vec![Cluster, Inside, Inside, Inside, Inside, Cluster]);
        assert_eq!(
            joints(&chars("e\u{301}x")),
            vec![Cluster, Inside, Cluster, Cluster]
        );
    }

    /// No glyph break forms before closing punctuation or after opening punctuation, so a cell's
    /// `。` or `」` stays with the glyph before it and a `「` with the one after.
    #[test]
    fn joints_do_not_break_where_punctuation_binds() {
        use Joint::*;
        assert_eq!(
            joints(&chars("日。本")),
            vec![Cluster, Cluster, Glyph, Cluster]
        );
        assert_eq!(
            joints(&chars("「日」x")),
            vec![Cluster, Cluster, Cluster, Glyph, Cluster]
        );
    }

    /// A word joiner forbids a break on either side, and a quote stays with the glyph it wraps.
    #[test]
    fn joints_do_not_break_beside_a_word_joiner_or_a_quote() {
        use Joint::*;
        assert_eq!(
            joints(&chars("日\u{2060}本")),
            vec![Cluster, Cluster, Cluster, Cluster]
        );
        assert_eq!(
            joints(&chars("'日本'")),
            vec![Cluster, Cluster, Glyph, Cluster, Cluster]
        );
        assert_eq!(
            joints(&chars("日’本")),
            vec![Cluster, Cluster, Cluster, Cluster]
        );
    }

    /// The string entry point agrees with the char-slice one, wide glyphs, clusters and all.
    #[test]
    fn joints_in_str_matches_joints() {
        for text in ["日本 語", "「日」x", "e\u{301}日👨\u{200d}👩", "a日\u{a0}b"] {
            assert_eq!(
                joints_in_str(text, text.chars().count()),
                joints(&chars(text)),
                "{text:?}"
            );
        }
    }

    /// NBSP pads a code span and must travel with it, so no glyph break forms beside one.
    #[test]
    fn joints_do_not_break_beside_whitespace() {
        let js = joints(&chars("\u{A0}日 本"));
        assert_eq!(js[1], Joint::Cluster);
        assert_eq!(js[3], Joint::Cluster);
    }

    #[test]
    fn word_ranges_make_each_wide_glyph_a_word() {
        assert_eq!(words("ab 日本語c"), vec!["ab", "日", "本", "語", "c"]);
        assert_eq!(words(&format!("x{FAMILY}y")), vec!["x", FAMILY, "y"]);
        assert_eq!(words("  "), Vec::<String>::new());
    }

    /// CJK breaks between glyphs, so a run fills the rest of a row rather than moving whole.
    #[test]
    fn wrap_cell_fills_a_row_with_cjk_glyphs() {
        assert_eq!(wrap_cell("abc 日本語日本", 10), vec!["abc 日本語", "日本"]);
    }

    #[test]
    fn wrap_cell_breaks_cjk_between_glyphs_at_the_floor() {
        assert_eq!(wrap_cell("日本語", 3), vec!["日", "本", "語"]);
    }

    #[test]
    fn wrap_cell_keeps_a_cluster_whole_even_when_it_overflows() {
        let rows = wrap_cell(&format!("a{FAMILY}b"), 3);
        assert_eq!(
            rows,
            vec!["a".to_owned(), FAMILY.to_owned(), "b".to_owned()]
        );
    }

    #[test]
    fn wrap_cell_hard_split_cuts_between_clusters() {
        let e = "e\u{301}";
        let rows = wrap_cell(&e.repeat(3), 2);
        assert_eq!(rows, vec![e.repeat(2), e.to_owned()]);
    }

    /// A row opened after a hard split drops its leading space like any other continuation row,
    /// so `wrap_cell_with_indices` starts line up with the text.
    #[test]
    fn wrap_cell_drops_the_leading_space_after_a_hard_split() {
        assert_eq!(wrap_cell("aaaaaaaa bb", 5), vec!["aaaaa", "aaa", "bb"]);
        let rows = wrap_cell_with_indices("aaaaaaaa bb", 5);
        assert_eq!(rows[2], (9, "bb".to_owned()));
    }

    #[test]
    fn wrap_cell_with_indices_reports_char_starts_for_wide_text() {
        assert_eq!(
            wrap_cell_with_indices("日本語 x", 4),
            vec![(0, "日本".to_owned()), (2, "語 x".to_owned())]
        );
    }

    /// A punctuation cut is taken only when what it leaves still fits beside the next cluster;
    /// otherwise the row breaks at the cluster instead of overflowing.
    #[test]
    fn wrap_cell_drops_a_punctuation_cut_that_would_overflow() {
        let text = format!("abc.\u{A0}{FAMILY}");
        assert_eq!(
            wrap_cell(&text, 6),
            vec!["abc.\u{A0}".to_owned(), FAMILY.to_owned()]
        );
    }

    #[test]
    fn hard_wrap_ranges_cuts_by_cells_keeping_spaces_and_clusters() {
        let text = chars(&format!("a b{FAMILY}日c"));
        let rows: Vec<String> = hard_wrap_ranges(&text, 4)
            .into_iter()
            .map(|r| text[r].iter().collect())
            .collect();
        assert_eq!(
            rows,
            vec!["a b".to_owned(), FAMILY.to_owned(), "日c".to_owned()]
        );
    }

    #[test]
    fn wrap_ranges_rows_never_exceed_the_width() {
        let text = chars("表格 wide 日本語テキスト and `code_span_here` 한국어 x.y\u{A0}日");
        for width in 2..20 {
            for r in wrap_ranges(&text, width) {
                assert!(cells_of(&text[r.clone()]) <= width, "{r:?} at {width}");
            }
            for r in hard_wrap_ranges(&text, width) {
                assert!(cells_of(&text[r.clone()]) <= width, "{r:?} at {width}");
            }
        }
    }

    #[test]
    fn preferred_cut_ignores_punctuation_in_leading_half() {
        // Index 1 is outside the trailing-half scan window — full-width cut.
        let chunk: Vec<char> = "a_bcdefghi".chars().collect();
        assert_eq!(preferred_cut(chunk.len(), |i| chunk[i]), chunk.len());
    }

    #[test]
    fn parse_column_widths_comment_roundtrip() {
        let widths = vec![Some(20), Some(15), Some(30)];
        let s = format_column_widths_comment(&widths);
        assert_eq!(s, "<!-- tui-columns: [20, 15, 30] -->");
        let parsed = parse_column_widths_comment(&s).unwrap();
        assert_eq!(parsed, widths);
    }

    #[test]
    fn parse_column_widths_comment_handles_embedded_text() {
        let src = "some doc text\n<!-- tui-columns: [5, 7] -->\nrest of doc";
        let parsed = parse_column_widths_comment(src).unwrap();
        assert_eq!(parsed, vec![Some(5), Some(7)]);
    }

    #[test]
    fn parse_column_widths_comment_returns_none_when_absent() {
        assert!(parse_column_widths_comment("no widths here").is_none());
        assert!(parse_column_widths_comment("<!-- tui-columns: [a, b] -->").is_none());
    }

    #[test]
    fn parse_column_widths_comment_supports_auto_placeholders() {
        let parsed = parse_column_widths_comment("<!-- tui-columns: [10, _, 30] -->").unwrap();
        assert_eq!(parsed, vec![Some(10), None, Some(30)]);
    }

    #[test]
    fn parse_column_widths_comment_all_auto_returns_none() {
        assert!(parse_column_widths_comment("<!-- tui-columns: [_, _] -->").is_none());
    }

    #[test]
    fn format_column_widths_comment_emits_underscore_for_auto() {
        let widths = vec![Some(5), None, Some(12)];
        assert_eq!(
            format_column_widths_comment(&widths),
            "<!-- tui-columns: [5, _, 12] -->"
        );
    }

    // ── Pipe / cell helpers ────────────────────────────────────────────────

    use ratatui::text::{Line, Span};

    fn line_with(s: &str) -> Line<'static> {
        Line::from(vec![Span::raw(s.to_owned())])
    }

    #[test]
    fn raw_pipe_positions_basic() {
        assert_eq!(raw_pipe_positions("| a | b |"), vec![0, 4, 8]);
    }

    #[test]
    fn raw_pipe_positions_skips_escaped_pipes() {
        let row = r"| a \| x | b |";
        let pipes = raw_pipe_positions(row);
        assert_eq!(pipes, vec![0, 9, 13]);
    }

    /// Raw cells as GFM splits a row: edge pipes optional, the content column skipping a prefix
    /// (even one holding a pipe), escaped pipes inside a cell, trailing whitespace ignored.
    #[test]
    fn raw_cells_split_as_gfm_does() {
        let text = |row: &str, col: usize| -> Vec<String> {
            let chars: Vec<char> = row.chars().collect();
            raw_cells(row, col)
                .into_iter()
                .map(|r| chars[r].iter().collect())
                .collect()
        };
        assert_eq!(text("| a | b |", 0), [" a ", " b "]);
        assert_eq!(text("a | b", 0), ["a ", " b"]);
        assert_eq!(text("| a | b", 0), [" a ", " b"]);
        assert_eq!(text("a | b |  \n", 0), ["a ", " b "]);
        assert_eq!(text("> | a | b |", 2), [" a ", " b "]);
        assert_eq!(text("[^a|b]: | x | y |", 8), [" x ", " y "]);
        assert_eq!(text(r"| a \| x | b |", 0), [r" a \| x ", " b "]);
        assert_eq!(text("| |", 0), [" "]);
        assert!(raw_cells("   ", 0).is_empty());
        assert!(raw_cells("> ", 2).is_empty());
    }

    /// Pairing keeps the first `drawn` raw cells, and a prefix or pipe column belongs to the cell
    /// before it.
    #[test]
    fn paired_raw_cells_drop_the_excess_and_find_a_columns_cell() {
        let row = "| 1 | 2 | 3 | 4 |";
        let cells = paired_raw_cells(row, 0, 2).unwrap();
        assert_eq!(cells, vec![1..4, 5..8]);
        assert_eq!(raw_cell_at(&cells, 0), 0, "the leading pipe");
        assert_eq!(
            raw_cell_at(&cells, 4),
            0,
            "a pipe belongs to the cell before it"
        );
        assert_eq!(raw_cell_at(&cells, 5), 1);
        assert_eq!(raw_cell_at(&cells, 16), 1, "past the drawn cells");
        assert!(
            paired_raw_cells(row, 0, 0).is_none(),
            "a border draws no cell"
        );
    }

    /// The drawn cell a raw column shows in: a short row's missing cell past its closing pipe,
    /// the last cell without one (typing there extends it), and nothing in a dropped cell.
    #[test]
    fn drawn_cell_at_pairs_short_and_long_rows() {
        // Three drawn cells over a row with one.
        let short = "| 1 |";
        assert_eq!(drawn_cell_at(short, 0, 3, 2), Some((0, 1..4)));
        assert_eq!(
            drawn_cell_at(short, 0, 3, 4),
            Some((0, 1..4)),
            "the closing pipe belongs to the cell before it"
        );
        assert_eq!(
            drawn_cell_at(short, 0, 3, 5),
            Some((1, 5..5)),
            "the row's end, past the closing pipe, is the first missing cell"
        );
        assert_eq!(drawn_cell_at("| 1 |  ", 0, 3, 5), Some((1, 5..5)));
        assert_eq!(
            drawn_cell_at("| 1", 0, 3, 3),
            Some((0, 1..3)),
            "without a closing pipe the row's end stays in the last cell"
        );
        assert_eq!(drawn_cell_at("| 1  ", 0, 3, 5), Some((0, 1..3)));
        assert_eq!(
            drawn_cell_at("> | 1 |", 2, 3, 7),
            Some((1, 7..7)),
            "behind a prefix"
        );

        // Two drawn cells over a row with four.
        let long = "| 1 | 2 | 3 | 4 |";
        assert_eq!(drawn_cell_at(long, 0, 2, 6), Some((1, 5..8)));
        assert_eq!(
            drawn_cell_at(long, 0, 2, 8),
            Some((1, 5..8)),
            "the pipe closing the last drawn cell"
        );
        assert_eq!(drawn_cell_at(long, 0, 2, 10), None, "in a dropped cell");
        assert_eq!(drawn_cell_at(long, 0, 2, 17), None, "the row's end");

        assert_eq!(drawn_cell_at(long, 0, 0, 2), None, "a border draws no cell");
        assert_eq!(drawn_cell_at("  ", 0, 2, 0), None, "a blank row");
    }

    #[test]
    fn unpadded_cell_shift_skips_the_pad_only_without_leading_whitespace() {
        assert_eq!(unpadded_cell_shift(" a "), 0);
        assert_eq!(unpadded_cell_shift("\ta"), 0);
        assert_eq!(unpadded_cell_shift("a "), 1);
        assert_eq!(unpadded_cell_shift(""), 1, "a short row's missing cell");
    }

    #[test]
    fn rendered_pipe_cells_count_wide_glyphs_as_two() {
        let line = line_with("│ 日 │ b │");
        assert_eq!(rendered_pipe_positions(&line), vec![0, 4, 8]);
        assert_eq!(rendered_pipe_cells(&line), vec![0, 5, 9]);
    }

    #[test]
    fn last_cluster_start_skips_back_over_zero_width_marks() {
        assert_eq!(last_cluster_start(&chars("abc")), 2);
        assert_eq!(last_cluster_start(&chars("a\u{2764}\u{FE0F}")), 1);
        assert_eq!(last_cluster_start(&chars(&format!("x{FAMILY}"))), 1);
        assert_eq!(last_cluster_start(&[]), 0);
    }

    #[test]
    fn rendered_pipe_positions_counts_box_drawing_pipes() {
        let line = line_with("│ a │ bb │");
        let pipes = rendered_pipe_positions(&line);
        assert_eq!(pipes, vec![0, 4, 9]);
    }

    #[test]
    fn table_raw_col_to_rendered_maps_plain_cells() {
        // Both sides share a leading space, so raw col 2 ('a') maps to rendered col 2, and the
        // space before it (raw col 1) to the pad space.
        let raw = "| a | b |";
        let rendered = [line_with("│ a │ b │")];
        let labels = RefLabels::default();
        let at = |col| table_raw_col_to_rendered(raw, 0, &rendered, col, &labels);
        assert_eq!(at(2), Some((0, 2)));
        assert_eq!(at(1), Some((0, 1)));
        assert_eq!(at(6), Some((0, 6)));
        // Past `a`, and on the pipe after it: both still the first cell, past its glyph.
        assert_eq!(at(3), Some((0, 3)));
        assert_eq!(at(4), Some((0, 3)));
    }

    #[test]
    fn table_raw_col_to_rendered_lands_on_the_glyph_past_hidden_markers() {
        let raw = "| a | **b** x |";
        let rendered = [line_with("│ a │ b x │")];
        let labels = RefLabels::default();
        let at =
            |c: &str| table_raw_col_to_rendered(raw, 0, &rendered, raw.find(c).unwrap(), &labels);
        assert_eq!(at("x"), Some((0, 8)));
        assert_eq!(at("b*"), Some((0, 6)));
        // On an opening marker: the glyph it opens.
        assert_eq!(at("**b"), Some((0, 6)));
    }

    #[test]
    fn table_raw_col_to_rendered_finds_the_wrap_sub_line() {
        // `**alpha** bravo` renders `alpha` / `bravo` at width 5.
        let raw = "| x | **alpha** bravo |";
        let rendered = [line_with("│ x │ alpha │"), line_with("│   │ bravo │")];
        let labels = RefLabels::default();
        let at =
            |c: &str| table_raw_col_to_rendered(raw, 0, &rendered, raw.find(c).unwrap(), &labels);
        assert_eq!(at("bravo"), Some((1, 6)));
        assert_eq!(at("avo"), Some((1, 8)));
        assert_eq!(at("alpha"), Some((0, 6)));
    }

    /// The column is a char index into its own sub-line: a wide glyph in the column to the left
    /// puts the cell fewer chars than cells in.
    #[test]
    fn table_raw_col_to_rendered_counts_chars_past_wide_glyphs() {
        let raw = "| 日本 | ab |";
        let rendered = [line_with("│ 日本 │ ab │")];
        let col = raw.find('b').map(|b| raw[..b].chars().count()).unwrap();
        let (sub, at) =
            table_raw_col_to_rendered(raw, 0, &rendered, col, &RefLabels::default()).unwrap();
        assert_eq!(sub, 0);
        assert_eq!(rendered[0].spans[0].content.chars().nth(at), Some('b'));
    }

    #[test]
    fn rendered_segments_map_continuation_chunk() {
        // Cell 1 wraps into ["alpha", "bravo"]; sub-line 1 shows "bravo" at raw 12..17.
        let raw = "| x | alpha bravo |";
        let rendered = line_with("│   │ bravo │");
        let labels = RefLabels::default();
        let segs = table_raw_col_range_to_rendered_segments(raw, 0, &rendered, 13, 16, 1, &labels);
        assert_eq!(segs, vec![(7, 10)]);
        assert!(
            table_raw_col_range_to_rendered_segments(raw, 0, &rendered, 2, 3, 1, &labels)
                .is_empty()
        );
        assert!(
            table_raw_col_range_to_rendered_segments(raw, 0, &rendered, 13, 16, 2, &labels)
                .is_empty()
        );
    }

    #[test]
    fn rendered_segments_skip_hidden_markers() {
        // `*b* x` renders `b x`: one chunk, `x` at rendered col 8, where the raw `x` is 4 into
        // the cell's content.
        let raw = "| a | *b* x |";
        let rendered = line_with("│ a │ b x │");
        let labels = RefLabels::default();
        let x = raw.find('x').unwrap();
        assert_eq!(
            table_raw_col_range_to_rendered_segments(raw, 0, &rendered, x, x + 1, 0, &labels),
            vec![(8, 9)]
        );
        // A range over the whole of `*b*` covers just the `b`.
        let b = raw.find('*').unwrap();
        assert_eq!(
            table_raw_col_range_to_rendered_segments(raw, 0, &rendered, b, b + 3, 0, &labels),
            vec![(6, 7)]
        );
        // A cell reading `2. a` is inline text, not a list item.
        let raw = "| 2. a |";
        let rendered = line_with("│ 2. a │");
        let a = raw.find('a').unwrap();
        assert_eq!(
            table_raw_col_range_to_rendered_segments(raw, 0, &rendered, a, a + 1, 0, &labels),
            vec![(5, 6)]
        );
    }

    #[test]
    fn rendered_segments_empty_on_pipe_mismatch() {
        let raw = "| a | b |";
        let rendered = line_with("├───┼───┤");
        assert!(table_raw_col_range_to_rendered_segments(
            raw,
            0,
            &rendered,
            2,
            3,
            0,
            &RefLabels::default()
        )
        .is_empty());
    }

    #[test]
    fn table_raw_col_to_rendered_returns_none_on_pipe_mismatch() {
        let raw = "| a | b |";
        let rendered = [line_with("├───┼───┤")];
        assert!(table_raw_col_to_rendered(raw, 0, &rendered, 2, &RefLabels::default()).is_none());
    }
}