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
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
//! Rendered row ↔ source line, and a row's rendered chars ↔ source columns, answered from the
//! [`RowOrigin`]s the renderer recorded.
//!
//! Works in **logical rows** — entries of `ParsedDoc::lines`, before wrap — in rendered chars
//! within such a row, and in source lines relative to a block's first line (the line holding its
//! original range's start).  Columns are read against the parse's own text, so they agree with
//! the origins they were recorded beside.  Wrapping and the reflow reveal stay with
//! `line_render` and `EffectiveRows`.  `block` is always an index in the source map's space
//! (blank-line virtual blocks included), and a row is an offset from the block's first rendered
//! row.  The rules are in `docs/dev/editing-model.md`.

use std::cell::OnceCell;
use std::ops::Range;

use crate::document::wrap::Indent;
use crate::document::ParsedDoc;
use crate::markdown::ast::{to_u32, ListItem};
use crate::markdown::segment_break;
use crate::markdown::table_layout::char_cells;
use crate::markdown::{
    strip_atx_closing, Block, ColOrigin, ContentKind, InlineColMap, RowOrigin, SrcLines,
};

/// `block`'s own rows' origins, and how many rows a `$$…$$` reveal's math-preview band holds
/// above them.  The band is editor state (the cursor's reveal), not the renderer's, so the
/// origins don't know it: a band row shows no source line, and the rows below it are the
/// origins' rows shifted down.
fn own_origins(parsed: &ParsedDoc, block: usize) -> (&[RowOrigin], usize) {
    let own = parsed.block_own_line_count(block);
    let first = parsed.source_map.rendered_lines_for_block(block).start;
    let origins = parsed
        .row_origins()
        .get(first..first.saturating_add(own))
        .unwrap_or(&[]);
    (origins, parsed.latex_source_offset(block))
}

/// The row of `block` that shows block-relative source `line`: the first row whose lines reach
/// it.  A line that renders no row of its own (a link reference definition inside a container,
/// a setext underline below a one-row heading, a bare `-`) shares the next line's row; a line
/// past every row clamps to the last row that shows a line, so never onto trailing chrome no
/// line owns (a table's bottom
/// border, an unclosed fence's placeholder).  A block with no rows answers 0.
pub fn row_for_line(parsed: &ParsedDoc, block: usize, line: usize) -> usize {
    let (origins, band) = own_origins(parsed, block);
    if origins.is_empty() {
        return 0;
    }
    let line = to_u32(line);
    let last = origins.len() - 1;
    let row = origins
        .iter()
        .position(|o| o.lines.as_ref().is_some_and(|l| l.end > line))
        .or_else(|| origins.iter().rposition(|o| o.lines.is_some()))
        .unwrap_or(last);
    (row + band).min(last)
}

/// The row of `block` showing source position `pos` (columns as [`RawPos`] counts them): the
/// cursor's row.  Usually [`row_for_line`]'s.  But a line can render on several rows, the first of
/// them chrome: a marker on a row of its own above the block its item opens (`- - a`, `- > q`,
/// `- # H`).  The line's chars show on a later row, so the cursor goes on the first one that places
/// its column exactly, which is also where a click on that char puts it back.
pub fn row_for_pos(parsed: &ParsedDoc, block: usize, pos: RawPos) -> usize {
    let row = row_for_line(parsed, block, pos.line);
    let (origins, band) = own_origins(parsed, block);
    let chrome = row
        .checked_sub(band)
        .and_then(|r| origins.get(r))
        .is_some_and(|o| o.cols == ColOrigin::Chrome);
    if !chrome {
        return row;
    }
    let line = to_u32(pos.line);
    (row + 1..)
        .take_while(|&r| lines_of_row(parsed, block, r).is_some_and(|l| l.contains(&line)))
        .find(|&r| raw_to_rendered_col(parsed, block, r, pos).is_some())
        .unwrap_or(row)
}

/// The source lines row `row` of `block` shows; `None` for a row no line owns (a table's top
/// border, an unclosed fence's placeholder) and for a math-preview band row.
pub fn lines_of_row(parsed: &ParsedDoc, block: usize, row: usize) -> Option<Range<u32>> {
    let (origins, band) = own_origins(parsed, block);
    origins.get(row.checked_sub(band)?)?.lines.clone()
}

/// The block-relative source line row `row` of `block` belongs to: the first line it shows, or,
/// for a row no line owns, the nearest owned line above it (0 when there is none).
pub fn line_for_row(parsed: &ParsedDoc, block: usize, row: usize) -> usize {
    let (origins, band) = own_origins(parsed, block);
    let Some(row) = row.checked_sub(band) else {
        return 0;
    };
    let row = row.min(origins.len().saturating_sub(1));
    origins
        .get(..=row)
        .unwrap_or(&[])
        .iter()
        .rev()
        .find_map(RowOrigin::first_line)
        .map_or(0, |l| l as usize)
}

/// The block-relative source line row `row` of diagram `block` (a mermaid fence, `$$…$$` math)
/// paints while revealed: its rows show the source lines 1:1, shifted down past any math-preview
/// band.  `None` for a band row, which paints empty behind the formula, for a reserved row past
/// the source (the origins clamp it to the last line, but it paints as padding until the
/// reservation shrinks to the source), and past the block's rows.  The one rule the click, the
/// raw row count and the view share for a diagram's rows.
pub fn revealed_diagram_line(parsed: &ParsedDoc, block: usize, row: usize) -> Option<usize> {
    let (origins, band) = own_origins(parsed, block);
    let k = row.checked_sub(band)?;
    let line = origins.get(k)?.lines.as_ref()?.start as usize;
    (line == k).then_some(line)
}

/// The source lines row `row` of `block` expands to when it is the revealed cursor row: `Some`
/// for an inline row over several lines, whose raw form is those lines stacked, `None` for
/// every other row, which reveals in place.  Such a row is a reflowed paragraph's flow (taller
/// raw than the one wrapped row it renders as), a multi-line setext heading's text, or a row
/// holding a multi-line code span, reflow on or off.  A reflowed paragraph's flow stacks even
/// over one line (each item of a list of one-liners): it reflows when reflow is on and it has
/// no hard break ([`paragraph_reflows`](crate::markdown::renderer::paragraph_reflows), the
/// renderer's rule), and is then its only row, a `Flow` origin over the paragraph's lines.
/// [`cursor_stack`] builds the cursor's stack from it.
pub fn stacked_lines(parsed: &ParsedDoc, block: usize, row: usize) -> Option<Range<u32>> {
    let (origins, band) = own_origins(parsed, block);
    let origin = origins.get(row.checked_sub(band)?)?;
    let ColOrigin::Content {
        kind: kind @ (ContentKind::Inline | ContentKind::Flow),
        ..
    } = origin.cols
    else {
        return None;
    };
    let lines = origin.lines.clone()?;
    if lines.len() > 1 {
        return Some(lines);
    }
    if !parsed.reflow_paragraphs || kind != ContentKind::Flow {
        return None;
    }
    let range_start = parsed.source_map.original_range_for_block(block)?.start;
    let ast = parsed.real_block_for_byte(range_start)?;
    match leaf_at(ast, lines.start)? {
        Block::Paragraph { inlines, .. }
            if crate::markdown::renderer::paragraph_reflows(parsed.reflow_paragraphs, inlines) =>
        {
            Some(lines)
        }
        _ => None,
    }
}

/// The row of `block` the cursor at `pos` reveals as stacked source lines, and those lines:
/// the one gate the reveal patch (`EffectiveRows`), the view, the click and the reveal timer
/// share.  Usually the cursor's row ([`row_for_pos`]) and its [`stacked_lines`].  Two cases add
/// to that:
///
/// - The cursor's line renders no row of its own (a link reference definition inside a
///   container, a bare list marker, a nested setext underline) and shares a neighbor's
///   ([`row_for_line`]: the next row, or the last for a line past every row).  The stack is
///   then that row's lines and the cursor's, so the row it shares still shows, whether or not
///   it stacks by itself.  The union is contiguous, since any line between the two has no row
///   either.  But a marker row whose line goes on to show on the rows below it (`- - a`) stacks
///   the cursor's line alone: its own line would show twice, raw and rendered.
/// - The cursor is on a setext underline with a rule row of its own: the heading's text row
///   stacks, so every text line shows while the rule reveals as the underline.
///
/// `None` in a diagram, whose rows show its lines one for one, and for a shared table row,
/// which reveals cell by cell.
pub fn cursor_stack(parsed: &ParsedDoc, block: usize, pos: RawPos) -> Option<(usize, Range<u32>)> {
    if parsed.is_diagram_reveal_block(block) {
        return None;
    }
    let line = to_u32(pos.line);
    let row = row_for_pos(parsed, block, pos);
    let own = lines_of_row(parsed, block, row)?;
    if !own.contains(&line) {
        if table_row(parsed, block, row).is_some() {
            return None;
        }
        if lines_of_row(parsed, block, row + 1).is_some_and(|next| next.contains(&own.start)) {
            return Some((row, line..line + 1));
        }
        let lines = stacked_lines(parsed, block, row).unwrap_or(own);
        return Some((row, lines.start.min(line)..lines.end.max(line + 1)));
    }
    if let Some(lines) = stacked_lines(parsed, block, row) {
        return Some((row, lines));
    }
    // A setext underline's rule row: stack the heading's text above it.
    let range_start = parsed.source_map.original_range_for_block(block)?.start;
    let leaf = leaf_at(parsed.real_block_for_byte(range_start)?, line)?;
    if !leaf.is_setext_heading() || line + 1 != leaf.span().end {
        return None;
    }
    let text = row_for_line(parsed, block, leaf.span().start as usize);
    stacked_lines(parsed, block, text).map(|lines| (text, lines))
}

// ── Columns ───────────────────────────────────────────────────────────────

/// A position in a block's source: a block-relative line and a char column on it.  Ordered
/// line first, so a row's positions ascend.
///
/// The public functions take and return columns in the space every consumer slices the block
/// in: from the block's range start on its first line (an indented code block's range starts
/// past its indent), from the line start on every other.  Internally they count from the line
/// start, as the origins do.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawPos {
    pub line: usize,
    pub col: usize,
}

/// What a row's column questions read, built on the first one and cached on the parse
/// ([`ParsedDoc::row_cache_or_init`]), one per entry of `ParsedDoc::lines`.  Nothing in it
/// depends on the cursor: the math-preview band only shifts which origin a row reads, and a
/// banded formula's rows are all chrome, which reads no positions.
#[derive(Debug, Clone)]
pub(crate) struct RowCache {
    /// The row's chars.
    chars: Box<[char]>,
    /// Where its block's original range starts; `None` for a block with none.
    range_start: Option<usize>,
    /// The source line holding that start: block-relative line 0.
    first_line: usize,
    /// Chars on that line before the range starts (an indented code block's indent).
    lead: usize,
    /// The raw position per content char, then the end of the content; `None` inside when no
    /// map renders exactly what the row shows.  Built on first use.
    positions: OnceCell<Option<Box<[RawPos]>>>,
}

impl RowCache {
    /// Physical row `abs` of `block`; `None` past the last row.
    fn new(parsed: &ParsedDoc, block: usize, abs: usize) -> Option<Self> {
        let chars = parsed
            .lines
            .get(abs)?
            .spans
            .iter()
            .flat_map(|s| s.content.chars())
            .collect();
        let range_start = parsed
            .source_map
            .original_range_for_block(block)
            .map(|r| r.start);
        let first_line = range_start.map_or(0, |b| parsed.byte_to_line(b));
        let lead = range_start
            .and_then(|b| parsed.source().get(parsed.line_start_byte(first_line)..b))
            .map_or(0, |t| t.chars().count());
        Some(Self {
            chars,
            range_start,
            first_line,
            lead,
            positions: OnceCell::new(),
        })
    }
}

/// Lines' slices joined by `\n` and mapped as one text: the raw position of each rendered char,
/// and which of them are breaks.  A paragraph's is built once per parse and shared by its rows
/// ([`ParsedDoc::with_joined_map`]), each of which takes its [`part`](Self::part): mapping the
/// whole paragraph per row cost a 500-line paragraph 100 ms over a screenful.
#[derive(Debug, Clone)]
pub(crate) struct JoinedMap {
    positions: Box<[RawPos]>,
    /// Every break, in order.
    breaks: Box<[Cut]>,
}

/// A break in a [`JoinedMap`]: where its rendered char is (or, for one that renders as nothing,
/// the char after it), the line it ends, and how many chars it renders, 1 or 0.
#[derive(Debug, Clone, Copy)]
struct Cut {
    at: usize,
    line: usize,
    len: usize,
}

impl JoinedMap {
    /// The map over `slices`, as [`Row::slices`] cuts them, hard breaks kept.
    fn new(slices: &[(usize, usize, &str)], labels: &crate::markdown::RefLabels) -> Self {
        let joined: Vec<&str> = slices.iter().map(|&(_, _, s)| s).collect();
        let map = InlineColMap::build_inline(&joined.join("\n"), labels);
        // Joined char index → `(line, col)`: walk the slices, each one char longer for its `\n`.
        let mut starts = Vec::with_capacity(slices.len());
        let mut at = 0usize;
        for &(_, _, s) in slices {
            starts.push(at);
            at += s.chars().count() + 1;
        }
        let pos = |c: usize| {
            let i = starts.partition_point(|&s| s <= c).saturating_sub(1);
            let (line, col, _) = slices[i];
            RawPos {
                line,
                col: col + (c - starts[i]),
            }
        };
        let forward = &map.rendered_to_raw_vec()[..map.rendered_len()];
        // One pass in rendered order, so in line order too: a vanished break comes before the
        // char it sits before, even one that is a break itself.
        let mut vanished = map.vanished_breaks().iter().peekable();
        let mut breaks = Vec::new();
        for (k, &raw) in forward.iter().enumerate() {
            while let Some(&(at, raw)) = vanished.next_if(|&&(at, _)| at == k) {
                breaks.push(Cut {
                    at,
                    line: pos(raw).line,
                    len: 0,
                });
            }
            if map.is_break(k) {
                breaks.push(Cut {
                    at: k,
                    line: pos(raw).line,
                    len: 1,
                });
            }
        }
        // Any sitting past the last char: a blank link's break, the link last and its fallback
        // empty (`[⏎]()`).
        breaks.extend(vanished.map(|&(at, raw)| Cut {
            at,
            line: pos(raw).line,
            len: 0,
        }));
        Self {
            positions: forward.iter().map(|&c| pos(c)).collect(),
            breaks: breaks.into_boxed_slice(),
        }
    }

    /// The raw positions of the rendered chars on `lines`: those between the last break on a
    /// line above them and the first break on their last line.  For a reflowed flow, `lines`
    /// are every line mapped, and its breaks are inside it.
    fn part(&self, lines: Range<u32>) -> Option<Vec<RawPos>> {
        let (first, last) = (lines.start as usize, lines.end.saturating_sub(1) as usize);
        // A break's line never falls below an earlier one's.
        let before = |line: usize| self.breaks.partition_point(|cut| cut.line < line);
        let from = before(first)
            .checked_sub(1)
            .map_or(0, |i| self.breaks[i].at + self.breaks[i].len);
        let to = self
            .breaks
            .get(before(last))
            .map_or(self.positions.len(), |cut| cut.at);
        self.positions.get(from..to).map(<[RawPos]>::to_vec)
    }
}

/// One logical row, resolved for a column question.
struct Row<'a> {
    parsed: &'a ParsedDoc,
    block: usize,
    origin: &'a RowOrigin,
    cache: &'a RowCache,
    /// The row's chars.
    chars: &'a [char],
    /// The char where its content starts: the origin's `rendered_col`, a cell, as a char.
    start: usize,
    range_start: Option<usize>,
    first_line: usize,
    lead: usize,
}

impl<'a> Row<'a> {
    /// Row `row` of `block`; `None` for a math-preview band row or past the block's rows.
    fn new(parsed: &'a ParsedDoc, block: usize, row: usize) -> Option<Self> {
        let (origins, band) = own_origins(parsed, block);
        let origin = origins.get(row.checked_sub(band)?)?;
        // The row's text is physical row `abs`, its origin row `row - band`, and its cache is
        // kept by `abs`.  The two differ only under a math-preview band, and a banded formula's
        // rows are all chrome, which reads no positions.
        debug_assert!(
            band == 0 || origin.cols == ColOrigin::Chrome,
            "a math-preview band over content rows"
        );
        let abs = parsed.source_map.rendered_lines_for_block(block).start + row;
        let cache = parsed.row_cache_or_init(abs, || RowCache::new(parsed, block, abs))?;
        let chars = &cache.chars[..];
        let start = match origin.cols {
            ColOrigin::Content { rendered_col, .. } => char_at_cell(chars, rendered_col as usize),
            ColOrigin::Chrome => 0,
        };
        Some(Self {
            parsed,
            block,
            origin,
            cache,
            chars,
            start,
            range_start: cache.range_start,
            first_line: cache.first_line,
            lead: cache.lead,
        })
    }

    /// How many chars of content the row shows past its prefix.
    fn content_len(&self) -> usize {
        self.chars.len() - self.start
    }

    /// `pos` from the space callers use (columns from the block's range start) into the
    /// origins' (columns from the line start).
    fn line_space(&self, pos: RawPos) -> RawPos {
        match pos.line {
            0 => RawPos {
                line: 0,
                col: pos.col + self.lead,
            },
            _ => pos,
        }
    }

    /// [`line_space`](Self::line_space)'s inverse.
    fn caller_space(&self, pos: RawPos) -> RawPos {
        match pos.line {
            0 => RawPos {
                line: 0,
                col: pos.col.saturating_sub(self.lead),
            },
            _ => pos,
        }
    }

    /// The real block's AST, `None` for a blank line's virtual block.
    fn ast(&self) -> Option<&'a Block> {
        self.parsed.real_block_for_byte(self.range_start?)
    }

    /// Where content starts on block-relative `line`, as its leaf recorded it.
    fn content_col(&self, line: u32) -> Option<u32> {
        let src = leaf_at(self.ast()?, line)?.src()?;
        src.col((line - src.first) as usize)
    }

    /// Where a click on a chrome row showing `line` lands: the line's content column, or, on a
    /// line that is all chrome (a fence, a setext underline), the nearest content column of the
    /// same leaf on a line with text there, below first, then above.  That puts it past the
    /// container prefix (`- `, `> `), on the fence or rule itself.  0 when the leaf has none.
    fn chrome_col(&self, line: u32) -> usize {
        let Some(src) = self
            .ast()
            .and_then(|b| leaf_at(b, line))
            .and_then(Block::src)
        else {
            return 0;
        };
        nearest_content_col(src, line, |l| self.line_len(l))
    }

    /// The row's raw position per content char, then the end of its content; `None` when no
    /// map renders exactly what the row shows.  Cached per row.
    fn positions(&self) -> Option<&'a [RawPos]> {
        let cache = self.cache;
        cache
            .positions
            .get_or_init(|| self.build_positions().map(Vec::into_boxed_slice))
            .as_deref()
    }

    /// An inline row's (or flow's) lines, each sliced past its content column and mapped by
    /// its own [`InlineColMap`], one space for each break that didn't vanish; failing that, a joined map's part on
    /// the row ([`JoinedMap::part`]), for an inline spanning a break
    /// (`*a⏎b*`).  Line by line first, since joined, a continuation reading `===` or `- a` turns
    /// into block syntax it wasn't in the document.  Accepted only when the map renders as many
    /// chars as the row shows (a footnote definition's trailing ` ↩` back-link aside).
    /// References resolve against the document's definitions, and an ATX heading's closing
    /// sequence is left out, as the renderer leaves them.
    fn build_positions(&self) -> Option<Vec<RawPos>> {
        let ColOrigin::Content {
            raw_col,
            kind: ContentKind::Inline | ContentKind::Flow,
            ..
        } = self.origin.cols
        else {
            return None;
        };
        let lines = self.origin.lines.clone()?;
        let leaf = self.ast().and_then(|b| leaf_at(b, lines.start));
        let labels = self.parsed.ref_labels();
        let slices = self.slices(lines.clone(), raw_col, leaf, false);

        let shown = self.content_len();
        let back_link = self.chars.ends_with(&[' ', '↩']);
        let fits = |len: usize| len == shown || (back_link && len + 2 == shown);

        let mut by_line = Vec::with_capacity(shown + 1);
        let content = &self.chars[self.start..];
        for (i, &(line, col, slice)) in slices.iter().enumerate() {
            // A break shows as a space unless it vanished: asked of the chars the row shows either
            // side of it, as the renderer asked, the test can't misjudge a kept break, whose
            // space never vanishes.  A map misaligned before this point fails `fits` below.
            let at = by_line.len();
            let vanished = at
                .checked_sub(1)
                .and_then(|before| content.get(before))
                .zip(content.get(at))
                .is_some_and(|(&before, &after)| segment_break::vanishes(before, after));
            if i > 0 && !vanished {
                let (prev, prev_col, prev_slice) = slices[i - 1];
                by_line.push(RawPos {
                    line: prev,
                    col: prev_col + prev_slice.chars().count(),
                });
            }
            let map = InlineColMap::build_inline(slice, labels);
            let forward = map.rendered_to_raw_vec();
            by_line.extend(
                forward[..map.rendered_len()]
                    .iter()
                    .map(|&c| RawPos { line, col: col + c }),
            );
        }
        let end = slices
            .last()
            .map_or(RawPos::default(), |&(line, col, slice)| RawPos {
                line,
                col: col + slice.chars().count(),
            });
        if fits(by_line.len()) {
            by_line.push(end);
            return Some(by_line);
        }
        // A paragraph's row is one of the segments its breaks cut it into, so an inline it
        // shares with the row above or below (`a *b⏎c* d`) reads right only over every line.
        // That map is the paragraph's, so every row of it shares one.
        let mut joined = match leaf {
            Some(Block::Paragraph { src, .. }) => {
                let first_col = src.col(0)?;
                self.parsed.with_joined_map(
                    (self.block, src.first),
                    || JoinedMap::new(&self.slices(src.span(), first_col, leaf, true), labels),
                    |map| map.part(lines),
                )?
            }
            _ if slices.len() >= 2 => {
                JoinedMap::new(&self.slices(lines.clone(), raw_col, leaf, true), labels)
                    .part(lines)?
            }
            _ => return None,
        };
        if !fits(joined.len()) {
            return None;
        }
        joined.push(end);
        Some(joined)
    }

    /// `(line, first col, slice)` per line of `lines`: its text past its content column
    /// (`first_col` on the first), less an ATX heading's closing sequence and, unless
    /// `hard_breaks`, a hard break's trailing `\`.  Mapped alone, a line's break is a space past
    /// its slice either way; joined, the `\` keeps it a hard break, which never vanishes
    /// between CJK glyphs, and keeps a line of nothing else from reading as a blank one.
    fn slices(
        &self,
        lines: Range<u32>,
        first_col: u32,
        leaf: Option<&Block>,
        hard_breaks: bool,
    ) -> Vec<(usize, usize, &'a str)> {
        let leaf_end = leaf.map_or(0, |l| l.span().end);
        let atx =
            leaf.is_some_and(|l| matches!(l, Block::Heading { .. }) && !l.is_setext_heading());
        let start = lines.start;
        lines
            .map(|l| {
                let line = self.line_text(l as usize);
                let col = if l == start {
                    Some(first_col)
                } else {
                    self.content_col(l)
                };
                // No column: the line continues an atomic inline begun above (a code span,
                // math, inline HTML, an image's alt), past its container prefix.
                let col = col.map_or_else(
                    || {
                        line.chars()
                            .take_while(|c| matches!(c, '>' | ' ' | '\t'))
                            .count()
                    },
                    |c| c as usize,
                );
                let byte = line.char_indices().nth(col).map_or(line.len(), |(b, _)| b);
                let slice = &line[byte..];
                // A trailing `\` breaks the line only where the leaf continues past it, and only
                // unescaped: an odd run (`a\\\` is an escaped `\`, then the break).
                let trailing = slice.chars().rev().take_while(|&c| c == '\\').count();
                let slice = match slice.strip_suffix('\\') {
                    Some(s) if !hard_breaks && l + 1 < leaf_end && trailing % 2 == 1 => s,
                    _ => slice,
                };
                let slice = if atx { strip_atx_closing(slice) } else { slice };
                (l as usize, col, slice)
            })
            .collect()
    }

    /// The row's first source line, or the nearest owned line above it.
    fn home_line(&self, row: usize) -> usize {
        line_for_row(self.parsed, self.block, row)
    }

    /// Block-relative `line`'s text from its start, `\r` aside; `""` for a block with no range.
    fn line_text(&self, line: usize) -> &'a str {
        if self.range_start.is_none() {
            return "";
        }
        let text = self.parsed.source_line(self.first_line + line);
        text.strip_suffix('\r').unwrap_or(text)
    }

    /// Chars on block-relative `line`, `\r` aside.
    fn line_len(&self, line: usize) -> usize {
        self.line_text(line).chars().count()
    }

    /// The raw column the rendered prefix's end lines up with on `line`: the content column,
    /// less however many more spaces the raw prefix ends in than the rendered one.  A marker
    /// padded out to its content (`1.  foo`, `-   foo`) then still lines up with its glyph,
    /// and the surplus spaces, which nothing renders, land on the content start.
    fn prefix_anchor(&self, line: usize, raw_col: usize) -> usize {
        let raw: Vec<char> = self.line_text(line).chars().take(raw_col).collect();
        let raw_gap = raw
            .iter()
            .rev()
            .take_while(|c| matches!(c, ' ' | '\t'))
            .count();
        let rendered_gap = self.chars[..self.start]
            .iter()
            .rev()
            .take_while(|&&c| c == ' ')
            .count();
        raw_col - raw_gap.saturating_sub(rendered_gap)
    }
}

/// The char of `chars` at cell `cell`, or the row's end.
fn char_at_cell(chars: &[char], cell: usize) -> usize {
    let mut at = 0usize;
    for (i, &ch) in chars.iter().enumerate() {
        if at >= cell {
            return i;
        }
        at += char_cells(ch);
    }
    chars.len()
}

/// The leaf `line` (block-relative) belongs to inside `block`.
/// `parsed_doc::set_table_widths_at` walks the same containers; a new one needs adding to both.
fn leaf_at(block: &Block, line: u32) -> Option<&Block> {
    match block {
        Block::BlockQuote { blocks, .. } | Block::FootnoteDefinition { blocks, .. } => {
            blocks.iter().find_map(|b| leaf_at(b, line))
        }
        Block::List { items, .. } => items
            .iter()
            .flat_map(|i| &i.blocks)
            .find_map(|b| leaf_at(b, line)),
        leaf => leaf.span().contains(&line).then_some(leaf),
    }
}

/// The content column of block-relative `line` of the leaf `src`, or, on a line that is all
/// chrome (a fence, a setext underline), the nearest one of the same leaf on a line with text
/// there, below first, then above: past the container prefix (`- `, `> `).  0 when the leaf has
/// none.  `line_len` gives a block-relative line's length in chars.
fn nearest_content_col(src: &SrcLines, line: u32, line_len: impl Fn(usize) -> usize) -> usize {
    let k = (line - src.first) as usize;
    let at = |i: usize| {
        let col = src.col(i)? as usize;
        (col < line_len(src.first as usize + i)).then_some(col)
    };
    (k..src.len())
        .find_map(at)
        .or_else(|| (0..k).rev().find_map(at))
        .unwrap_or(0)
}

/// The indent the reveal paints block-relative source `line` of `block` behind, in the space
/// every reveal consumer slices the block in (from the range start on its first line): the one
/// measure the painter, `EffectiveRows`, the click and the cursor's sub-row share.
///
/// Read from the parse, never guessed from the text: continuation rows hang where the line's
/// content starts past its containers and marker (its leaf's `SrcLines` column, in cells), so
/// a footnote's `[^1]: ` hangs and an escaped `1\. ` doesn't; a verbatim leaf's line (a
/// diagram's body) also hangs under its own indentation.  A line all chrome (a fence) takes the
/// leaf's nearest content column, and one in no leaf (a container's hidden link definition)
/// none.
///
/// The `lead` keeps the text where the rendered row showed it: when the row showing the line
/// started its content further right than the line's raw prefix ends (a right-aligned ` 6.`
/// beside `10.`, a nested item rendered at its 4-cell nesting), the first row is padded by the
/// difference, so the reveal doesn't shift it left (issue #65).  A line with no prefix (a lazy
/// continuation) is never padded.
pub fn revealed_indent(parsed: &ParsedDoc, block: usize, line: usize) -> Indent {
    indent_and_skip(parsed, block, line).map_or(Indent::NONE, |(indent, _)| indent)
}

/// How the rendered views lay out a whole buffer line: its first `skip` chars aren't painted,
/// and the rest wrap behind `indent`.  See [`source_line_layout`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LineLayout {
    /// Chars at the line's start that no row paints.
    pub skip: usize,
    /// The indent the painted rest wraps behind.
    pub indent: Indent,
}

/// The layout of source line `line` of the parse as the cursor's vertical navigation, which
/// steps whole buffer lines, must model it to land where the cursor shows.
///
/// A line that reveals is laid out as the reveal paints it: from its block's range start (a
/// paragraph indented ` ` to `   ` drops those spaces), behind [`revealed_indent`].  A line
/// whose row never de-renders (a code body, frontmatter, raw HTML; [`reveals`]) shows as that
/// row: its raw chars from the origin's `raw_col` on (a list's or a fence's indentation hidden),
/// at its `rendered_col` (past a code row's pad cell), hanging as the row does.
pub fn source_line_layout(parsed: &ParsedDoc, line: usize) -> LineLayout {
    let byte = parsed.line_start_byte(line);
    let Some(block) = parsed.source_map.block_for_byte(byte) else {
        return LineLayout::default();
    };
    let first = parsed
        .source_map
        .original_range_for_block(block)
        .map_or(line, |r| parsed.byte_to_line(r.start));
    let rel = line.saturating_sub(first);
    let Some((indent, range_skip)) = indent_and_skip(parsed, block, rel) else {
        return LineLayout::default();
    };
    let row = row_for_line(parsed, block, rel);
    if !reveals(parsed, block, row) {
        let (origins, band) = own_origins(parsed, block);
        let origin = row.checked_sub(band).and_then(|r| origins.get(r));
        if let Some(RowOrigin {
            lines: Some(lines),
            cols:
                ColOrigin::Content {
                    raw_col,
                    rendered_col,
                    ..
                },
            hang,
        }) = origin
        {
            if lines.contains(&to_u32(rel)) {
                return LineLayout {
                    // Origins count from the line start, range start or not.
                    skip: *raw_col as usize,
                    indent: Indent {
                        lead: *rendered_col as usize,
                        hang: *hang as usize,
                    },
                };
            }
        }
    }
    LineLayout {
        skip: range_skip,
        indent,
    }
}

/// [`revealed_indent`], and the chars of the line before its block's range start (0 past the
/// block's first line), which the reveal doesn't paint.
fn indent_and_skip(parsed: &ParsedDoc, block: usize, line: usize) -> Option<(Indent, usize)> {
    let range_start = parsed
        .source_map
        .original_range_for_block(block)
        .map(|r| r.start)?;
    let ast = parsed.real_block_for_byte(range_start)?;
    let first_line = parsed.byte_to_line(range_start);
    let rel = to_u32(line);
    let src = leaf_at(ast, rel).and_then(Block::src)?;
    let text_of = |l: usize| parsed.source_line(first_line + l);
    let chars: Vec<char> = text_of(line).chars().collect();
    // The painted text starts at the range start on the block's first line.
    let skip = if line == 0 {
        parsed
            .source()
            .get(parsed.line_start_byte(first_line)..range_start)
            .map_or(0, |t| t.chars().count())
    } else {
        0
    };
    let own_col = src.col((rel - src.first) as usize);
    let col = own_col.map_or_else(
        || nearest_content_col(src, rel, |l| text_of(l).chars().count()),
        |c| c as usize,
    );
    let cells = |from: usize, to: usize| -> usize {
        chars
            .get(from.min(chars.len())..to.min(chars.len()))
            .map_or(0, |cs| cs.iter().map(|&c| char_cells(c)).sum())
    };
    let prefix = cells(skip.min(col), col);
    let own_indent = if leaf_at(ast, rel).is_some_and(is_verbatim_leaf) {
        chars
            .get(col..)
            .map_or(0, |rest| rest.iter().take_while(|&&c| c == ' ').count())
    } else {
        0
    };
    // Only a line with a prefix of its own is padded: a lazy continuation, written flush, shows
    // as written rather than gaining an indent the file doesn't have.
    let lead = own_col
        .filter(|_| prefix > 0)
        .and_then(|_| {
            let (origins, band) = own_origins(parsed, block);
            let row = row_for_line(parsed, block, line);
            let origin = origins.get(row.checked_sub(band)?)?;
            if !origin.lines.as_ref()?.contains(&rel) {
                return None;
            }
            match origin.cols {
                ColOrigin::Content { rendered_col, .. } => {
                    Some((rendered_col as usize).saturating_sub(prefix))
                }
                ColOrigin::Chrome => None,
            }
        })
        .unwrap_or(0);
    let indent = Indent {
        lead,
        hang: lead + prefix + own_indent,
    };
    Some((indent, skip))
}

/// Whether `leaf` shows its lines verbatim: a code block, raw HTML, frontmatter, or a diagram
/// (an image block revealing its fence's source).
fn is_verbatim_leaf(leaf: &Block) -> bool {
    matches!(
        leaf,
        Block::CodeBlock { .. }
            | Block::Html(..)
            | Block::MetadataBlock { .. }
            | Block::ImageBlock { .. }
    )
}

/// Whether row `row` of `block` de-renders to raw source when it is the revealed cursor row.
/// Every row does but one showing characters verbatim (a code body, frontmatter, raw HTML),
/// which would look the same raw.  A row the origins don't hold (a band row, a blank line's
/// missing row) reveals.
pub fn reveals(parsed: &ParsedDoc, block: usize, row: usize) -> bool {
    let (origins, band) = own_origins(parsed, block);
    let origin = row.checked_sub(band).and_then(|r| origins.get(r));
    !matches!(
        origin.map(|o| o.cols),
        Some(ColOrigin::Content {
            kind: ContentKind::Verbatim,
            ..
        })
    )
}

/// The source position rendered char `rendered` of row `row` of `block` shows: where a click on
/// it lands.  A char in the row's prefix (a marker, a bar, a leader) lands on the raw prefix
/// right-aligned with it, so a task box or footnote leader is hit exactly; a code row's pad cell,
/// which stands for nothing, on the content start.  One past the content lands on its end.  A
/// chrome row lands on its line's content start, or, for a line with none (a fence), on its
/// leaf's nearest one, past any container prefix.
pub fn rendered_to_raw_col(
    parsed: &ParsedDoc,
    block: usize,
    row: usize,
    rendered: usize,
) -> RawPos {
    let Some(r) = Row::new(parsed, block, row) else {
        return RawPos {
            line: line_for_row(parsed, block, row),
            col: 0,
        };
    };
    let ColOrigin::Content { raw_col, kind, .. } = r.origin.cols else {
        let line = r.home_line(row);
        let col = r.chrome_col(to_u32(line));
        return r.caller_space(RawPos {
            line,
            col: col.min(r.line_len(line)),
        });
    };
    if rendered < r.start && kind != ContentKind::Verbatim {
        // The prefix lines up with the raw one from the right, so a click on a task box, a
        // footnote leader or a list marker lands on the raw marker it stands for whatever
        // indent, bullet or number padding the two disagree on.  Indentation stands for nothing
        // and lands past itself: on the marker, or on a continuation line's content.
        let line = r.home_line(row);
        let text = r.line_text(line);
        let indent = text.chars().take_while(|c| matches!(c, ' ' | '\t')).count();
        let anchor = r.prefix_anchor(line, raw_col as usize);
        let col = (rendered + anchor).saturating_sub(r.start).max(indent);
        // One reaching the content start lands where its first char does, past any marker
        // hiding there (`*a*`), as a click on that char would.
        if col < anchor {
            return r.caller_space(RawPos { line, col });
        }
    }
    let k = rendered.saturating_sub(r.start).min(r.content_len());
    if let Some(positions) = r.positions() {
        return r.caller_space(positions[k.min(positions.len() - 1)]);
    }
    // Verbatim, or content no map renders exactly: one char for one past the content start.
    let line = r.home_line(row);
    r.caller_space(RawPos {
        line,
        col: (raw_col as usize).saturating_add(k).min(r.line_len(line)),
    })
}

/// The rendered char of row `row` of `block` showing source position `pos`: where its cursor
/// indicator sits and where an overlay starting or ending there paints.  A position in the
/// row's raw prefix lands on the rendered prefix right-aligned with it (the inverse of
/// [`rendered_to_raw_col`]), and in a code row's indent on the content start.  `None` when the
/// row can't place it exactly: a chrome row, a line the row doesn't show, content no inline map
/// renders exactly.  An overlay then skips rather than painting off by N.
pub fn raw_to_rendered_col(
    parsed: &ParsedDoc,
    block: usize,
    row: usize,
    pos: RawPos,
) -> Option<usize> {
    let r = Row::new(parsed, block, row)?;
    let ColOrigin::Content { raw_col, kind, .. } = r.origin.cols else {
        return None;
    };
    let pos = r.line_space(pos);
    let lines = r.origin.lines.clone()?;
    if !lines.contains(&to_u32(pos.line)) {
        return None;
    }
    if pos.line == lines.start as usize
        && pos.col < raw_col as usize
        && kind != ContentKind::Verbatim
    {
        // In the raw prefix: the inverse of `rendered_to_raw_col`'s right alignment.
        let anchor = r.prefix_anchor(pos.line, raw_col as usize);
        return Some((pos.col + r.start).saturating_sub(anchor).min(r.start));
    }
    if kind == ContentKind::Verbatim {
        let k = pos
            .col
            .saturating_sub(raw_col as usize)
            .min(r.content_len());
        return Some(r.start + k);
    }
    let positions = r.positions()?;
    Some(r.start + positions.partition_point(|p| *p < pos).min(r.content_len()))
}

/// [`raw_to_rendered_col`], or its best guess where that has no exact answer: one char for one
/// past the content start on the row's own line, else the content start, and on a chrome row
/// the column itself.  For the cursor indicator, which must sit somewhere.
pub fn raw_to_rendered_col_near(
    parsed: &ParsedDoc,
    block: usize,
    row: usize,
    pos: RawPos,
) -> usize {
    if let Some(col) = raw_to_rendered_col(parsed, block, row, pos) {
        return col;
    }
    let Some(r) = Row::new(parsed, block, row) else {
        return pos.col;
    };
    let pos = r.line_space(pos);
    match r.origin.cols {
        ColOrigin::Content { raw_col, .. } if r.origin.first_line() == Some(to_u32(pos.line)) => {
            r.start
                + pos
                    .col
                    .saturating_sub(raw_col as usize)
                    .min(r.content_len())
        }
        ColOrigin::Content { .. } => r.start,
        ColOrigin::Chrome => pos.col.min(r.chars.len()),
    }
}

// ── Lists ─────────────────────────────────────────────────────────────────

/// The content columns of the list items holding source `line` (counted in the parse's text),
/// outermost first: the column a line written into each item starts at.  What places a table
/// inserted on a blank line below an item inside that item.
///
/// Empty when no item holds the line, and when a quote or a footnote does: a quote's lines carry
/// a `>` a blank line lacks, and a footnote's first line puts its items' content past the label,
/// further right than on its later lines.  An item whose column can't be read off a leaf (one
/// holding only code, a quote or a nested list) is left out.
pub fn item_content_cols(parsed: &ParsedDoc, line: usize) -> Vec<usize> {
    let Some((block, first)) = parsed.real_block_at_line(line) else {
        return Vec::new();
    };
    block
        .items_holding(to_u32(line - first))
        .map(|items| items.into_iter().filter_map(item_content_col).collect())
        .unwrap_or_default()
}

/// Where `item`'s content starts: the column of its first leaf other than code, whose column
/// sits past an indented block's code indent.
fn item_content_col(item: &ListItem) -> Option<usize> {
    item.blocks
        .iter()
        .filter(|b| !matches!(b, Block::CodeBlock { .. }))
        .find_map(|b| b.src()?.cols().flatten().next())
        .map(|c| c as usize)
}

// ── Tables ────────────────────────────────────────────────────────────────

/// The table holding source `line` (counted in the parse's text), at any nesting depth: the
/// line its header is on and, per line of the table, the char column its content starts at, past
/// any container prefix and a footnote's label.  The delimiter row's is `None`, recorded as
/// chrome.  What the editing path (`table_edit`) splits a table's rows from; `None` off a table.
pub fn table_lines(parsed: &ParsedDoc, line: usize) -> Option<(usize, Vec<Option<usize>>)> {
    let (block, first) = parsed.real_block_at_line(line)?;
    let Some(Block::Table { src, .. }) = leaf_at(block, to_u32(line - first)) else {
        return None;
    };
    let cols = src.cols().map(|c| c.map(|c| c as usize)).collect();
    Some((first + src.first as usize, cols))
}

/// The table row a row of a block belongs to, from the origins: what a click, an overlay and
/// the cursor indicator need to find before `table_layout`'s cell geometry maps the columns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableRowHit {
    /// The table row's block-relative source line.
    pub line: usize,
    /// Its index in the table: 0 the header, `1 + i` data row `i`.
    pub index: u32,
    /// The wrap chunk the row shows; 0 for a border or separator snapped onto the table row.
    pub sub: usize,
    /// Whether the row shows the table row's cells, rather than a border or separator.
    pub cells: bool,
    /// The block's rows showing the table row's cells, one per wrap chunk.
    pub rows: Range<usize>,
    /// The table row's content column on its line (its origin's `raw_col`): where the row
    /// starts past any container prefix, so its pipes are counted from there.
    pub raw_col: usize,
}

/// The table row that row `row` of `block` belongs to; `None` outside a table.  A row of cells
/// is its own.  A border or separator (chrome inside a table leaf) snaps onto a table row: the
/// one showing the same line (a separator or the bottom border, onto the row above it), else the
/// one directly below (the top border onto the header, the heavy rule onto the first data row),
/// else the nearest above (the heavy rule of a table with no data rows).
pub fn table_row(parsed: &ParsedDoc, block: usize, row: usize) -> Option<TableRowHit> {
    let (origins, band) = own_origins(parsed, block);
    let r = row.checked_sub(band)?;
    let origin = origins.get(r)?;
    let cells_of = |o: &RowOrigin| match o.cols {
        ColOrigin::Content {
            raw_col,
            kind: ContentKind::TableRow { row, sub },
            ..
        } => Some((
            o.first_line()? as usize,
            row,
            sub as usize,
            raw_col as usize,
        )),
        _ => None,
    };
    let (at, (line, index, sub, raw_col)) = if let Some(hit) = cells_of(origin) {
        (r, hit)
    } else {
        if origin.cols != ColOrigin::Chrome {
            return None;
        }
        // The top border shows no line; the header below it does.
        let line = origin
            .first_line()
            .or_else(|| origins.get(r + 1)?.first_line())?;
        let range_start = parsed.source_map.original_range_for_block(block)?.start;
        let ast = parsed.real_block_for_byte(range_start)?;
        if !matches!(leaf_at(ast, line), Some(Block::Table { .. })) {
            return None;
        }
        // A row of cells showing the same line is always above: the top border's line and the
        // delimiter line show on no row of cells.
        let shows = |o: &RowOrigin| cells_of(o).is_some_and(|(l, ..)| l == line as usize);
        let at = origins[..r]
            .iter()
            .rposition(shows)
            .or_else(|| origins.get(r + 1).and_then(cells_of).map(|_| r + 1))
            .or_else(|| origins[..r].iter().rposition(|o| cells_of(o).is_some()))?;
        let (line, index, _, raw_col) = cells_of(&origins[at])?;
        (at, (line, index, 0, raw_col))
    };
    let same = |o: &RowOrigin| cells_of(o).is_some_and(|(l, i, ..)| l == line && i == index);
    let first = origins[..at]
        .iter()
        .rposition(|o| !same(o))
        .map_or(0, |i| i + 1);
    let end = origins[at..]
        .iter()
        .position(|o| !same(o))
        .map_or(origins.len(), |i| at + i);
    Some(TableRowHit {
        line,
        index,
        sub,
        cells: at == r,
        rows: first + band..end + band,
        raw_col,
    })
}

/// What one rendered row of a table draws, as the renderer recorded it.  Data row `row` is
/// `TableInfo` row `2 + row` (past the header and the delimiter row).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TablePart {
    /// `┌─┬─┐`.
    TopBorder,
    /// Chunk `sub` of the header.
    Header { sub: usize },
    /// `┝━┿━┥`, under the header.
    HeavyRule,
    /// Chunk `sub` of data row `row`.
    DataRow { row: usize, sub: usize },
    /// Between two data rows: `├─┼─┤`, or a blank stripe under `row_striping`.
    Separator,
    /// `└─┴─┘`.
    BottomBorder,
}

/// Per row of a block, the table it belongs to (the line its header is on) and the part of it
/// the row draws: [`table_parts`]'s answer.
pub type TableParts = Vec<Option<(usize, TablePart)>>;

/// Per row of `block` (indexed as [`table_row`]'s `row`), the table the row belongs to, as the
/// block-relative line its header is on, and the part of it the row draws; `None` off a table.
/// Empty for a block that draws no table.  What the table handles' geometry is built from, at
/// any nesting depth.
///
/// Read off the origins' sequence rather than their lines: a table starts at the one chrome row
/// showing no line directly above a header chunk (its top border), and a chrome row is a
/// separator when a data row follows it, else the bottom border.  The heavy rule and the bottom
/// border of a table with no data rows show the same line, and a separator shows the line of
/// the row above it, as the bottom border does.
pub fn table_parts(parsed: &ParsedDoc, block: usize) -> TableParts {
    let (origins, band) = own_origins(parsed, block);
    let cells = |i: usize| match origins.get(i)?.cols {
        ColOrigin::Content {
            kind: ContentKind::TableRow { row, sub },
            ..
        } => Some((row as usize, sub as usize)),
        _ => None,
    };
    if !(0..origins.len()).any(|i| cells(i).is_some()) {
        return Vec::new();
    }
    let mut out = vec![None; band + origins.len()];
    let data = |i: usize| cells(i).filter(|&(row, _)| row > 0);
    let chrome = |i: usize| origins.get(i).is_some_and(|o| o.cols == ColOrigin::Chrome);
    let mut i = 0;
    while i < origins.len() {
        if !(chrome(i) && origins[i].lines.is_none() && cells(i + 1) == Some((0, 0))) {
            i += 1;
            continue;
        }
        let Some(header) = origins[i + 1].first_line().map(|l| l as usize) else {
            i += 1;
            continue;
        };
        let mut mark = |i: usize, part| out[band + i] = Some((header, part));
        mark(i, TablePart::TopBorder);
        i += 1;
        while let Some((0, sub)) = cells(i) {
            mark(i, TablePart::Header { sub });
            i += 1;
        }
        if chrome(i) {
            mark(i, TablePart::HeavyRule);
            i += 1;
        }
        while chrome(i) || data(i).is_some() {
            if let Some((row, sub)) = data(i) {
                mark(i, TablePart::DataRow { row: row - 1, sub });
            } else if data(i + 1).is_some() {
                mark(i, TablePart::Separator);
            } else {
                mark(i, TablePart::BottomBorder);
                i += 1;
                break;
            }
            i += 1;
        }
    }
    out
}

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

    fn theme() -> &'static Theme {
        Box::leak(Box::new(Theme::default()))
    }

    fn doc(src: &str) -> ParsedDoc {
        ParsedDoc::build(src, theme(), true, 4)
    }

    /// Rows and lines of the block holding `byte`.
    fn block_at(doc: &ParsedDoc, byte: usize) -> usize {
        doc.source_map.block_for_byte(byte).unwrap()
    }

    /// Navigation's layout of a whole line: a revealing line drops what precedes its block's
    /// range and hangs as the reveal does; a code line shows from its content past the hidden
    /// indentation, behind the row's pad cell, hanging under its own indent.
    #[test]
    fn a_source_lines_layout_is_what_its_row_paints() {
        let d = doc("  para text\n\n- a\n\n  ```\n    x\n  ```\n");
        let at = |line| source_line_layout(&d, line);
        assert_eq!(
            at(0),
            LineLayout {
                skip: 2,
                indent: Indent::NONE
            }
        );
        assert_eq!(
            at(2),
            LineLayout {
                skip: 0,
                indent: Indent::hanging(2)
            }
        );
        // `    x` in a list item: the item's 2 columns hidden, then the 2 cells the block renders
        // in by and its pad cell, and the code's own 2-space indent joining the hang.
        assert_eq!(
            at(5),
            LineLayout {
                skip: 2,
                indent: Indent { lead: 3, hang: 5 }
            }
        );
    }

    #[test]
    fn a_line_with_no_row_shares_the_next_lines_row() {
        // A link reference definition inside a quote renders no row.
        let d = doc("> a\n>\n> [r]: /u\n> b\n");
        let b = block_at(&d, 0);
        assert_eq!(
            (0..4).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [0, 1, 2, 2]
        );
        assert_eq!(line_for_row(&d, b, 2), 3);
    }

    #[test]
    fn a_blank_between_an_items_blocks_has_a_row_of_its_own() {
        let d = doc("- a\n\n  b\n");
        let b = block_at(&d, 0);
        assert_eq!(
            (0..3).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [0, 1, 2]
        );
        // So does a blank between a nested loose list's items.
        let d = doc("- x\n  - b\n\n  - d\n");
        let b = block_at(&d, 0);
        assert_eq!(
            (0..4).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [0, 1, 2, 3]
        );
    }

    #[test]
    fn a_marker_on_a_row_of_its_own_keeps_the_rows_below_on_their_lines() {
        // Rows: `•`, ` bash ` label, body, closing fence, `• next`.
        let d = doc("- ```bash\n  code\n  ```\n- next\n");
        let b = block_at(&d, 0);
        assert_eq!(
            (0..4).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [0, 2, 3, 4]
        );
        assert_eq!(
            (0..5).map(|r| line_for_row(&d, b, r)).collect::<Vec<_>>(),
            [0, 0, 1, 2, 3]
        );
    }

    #[test]
    fn a_row_no_line_owns_belongs_to_the_line_above() {
        // An unclosed fence's closing placeholder.
        let d = doc("- a\n  ```\n  x\n- b\n");
        let b = block_at(&d, 0);
        assert_eq!(lines_of_row(&d, b, 3), None);
        assert_eq!(line_for_row(&d, b, 3), 2);
        assert_eq!(row_for_line(&d, b, 3), 4);
    }

    /// A line past every row (a cursor on the blank line a block's range absorbs) lands on the
    /// last row that shows a line, not on a trailing placeholder.
    #[test]
    fn a_line_past_every_row_skips_trailing_chrome() {
        let d = doc("- a\n  ```\n  x\n");
        let b = block_at(&d, 0);
        let rows = d.block_own_line_count(b);
        assert_eq!(
            lines_of_row(&d, b, rows - 1),
            None,
            "the placeholder closes the block"
        );
        assert_eq!(row_for_line(&d, b, 9), rows - 2);
    }

    #[test]
    fn a_table_line_lands_on_its_first_content_row() {
        // Rows: top border, header, heavy rule, data row, bottom border.
        let d = doc("| a | b |\n|---|---|\n| 1 | 2 |\n");
        let b = block_at(&d, 0);
        assert_eq!(
            (0..3).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [1, 2, 3]
        );
        assert_eq!(line_for_row(&d, b, 0), 0);
        assert_eq!(line_for_row(&d, b, 4), 2);
    }

    /// Every row of a table finds its table row: cells their own, a border or separator the one
    /// it snaps onto.
    #[test]
    fn a_tables_borders_snap_onto_its_rows() {
        // Rows: top border, header, heavy rule, data 1, thin separator, data 2, bottom border.
        let d = doc("| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n");
        let b = block_at(&d, 0);
        let hit = |r| table_row(&d, b, r).map(|h| (h.line, h.index, h.cells));
        assert_eq!(
            (0..7).map(hit).collect::<Vec<_>>(),
            [
                Some((0, 0, false)),
                Some((0, 0, true)),
                Some((2, 1, false)),
                Some((2, 1, true)),
                Some((2, 1, false)),
                Some((3, 2, true)),
                Some((3, 2, false)),
            ]
        );
        assert_eq!(table_row(&d, b, 3).unwrap().rows, 3..4);
    }

    /// A table nested in a list item is found by its origins, behind the item's other rows; the
    /// item's own rows are no table's.
    #[test]
    fn a_nested_tables_rows_are_found_inside_their_block() {
        let d = doc("- item\n\n  | a | b |\n  |---|---|\n  | 1 | 2 |\n");
        let b = block_at(&d, 0);
        assert_eq!(table_row(&d, b, 0), None, "the item's text");
        let header = row_for_line(&d, b, 2);
        assert_eq!(
            table_row(&d, b, header - 1).map(|h| (h.line, h.cells)),
            Some((2, false)),
            "the top border"
        );
        let data = row_for_line(&d, b, 4);
        let hit = table_row(&d, b, data).unwrap();
        assert_eq!((hit.line, hit.index, hit.sub, hit.cells), (4, 1, 0, true));
        assert_eq!(hit.rows, data..data + 1);
        assert_eq!(
            table_row(&d, b, data - 1).map(|h| h.line),
            Some(4),
            "heavy rule"
        );
    }

    /// A row that wraps is one table row over several rows, each its own chunk.
    #[test]
    fn a_wrapped_table_rows_chunks_share_it() {
        let src = "| a | b |\n|---|---|\n| x | aa bb cc dd ee ff |\n";
        let d = ParsedDoc::build_with_overrides(
            src,
            theme(),
            true,
            4,
            None,
            None,
            false,
            16,
            false,
            false,
            true,
            false,
            None,
        );
        let b = block_at(&d, 0);
        let first = row_for_line(&d, b, 2);
        let hit = table_row(&d, b, first + 1).unwrap();
        assert!(hit.rows.len() > 1, "fixture: the row wraps");
        assert_eq!((hit.line, hit.sub, hit.rows.start), (2, 1, first));
    }

    /// A row showing several lines (a multi-line heading's text) is the row of each of them.
    #[test]
    fn every_line_of_a_multi_line_row_lands_on_it() {
        // Rows: the heading's text (lines 0–1), its rule (line 2).
        let d = doc("Title\nmore\n=====\n");
        let b = block_at(&d, 0);
        assert_eq!(lines_of_row(&d, b, 0), Some(0..2));
        assert_eq!(
            (0..3).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [0, 0, 1]
        );
        assert_eq!(line_for_row(&d, b, 1), 2);
    }

    /// The math-preview band sits above a revealed formula's source rows: its rows show no
    /// line, and every line moves down past it.
    #[test]
    fn a_math_preview_band_shifts_the_source_rows_down() {
        let mut d = doc("$$\nx\n$$\n");
        let b = block_at(&d, 0);
        d.math_source_offset = Some((b, 1));
        assert_eq!(lines_of_row(&d, b, 0), None);
        assert_eq!(
            line_for_row(&d, b, 0),
            0,
            "a band row resolves to the first line"
        );
        assert_eq!(
            (0..3).map(|l| row_for_line(&d, b, l)).collect::<Vec<_>>(),
            [1, 2, 3]
        );
        assert_eq!(
            (1..4).map(|r| line_for_row(&d, b, r)).collect::<Vec<_>>(),
            [0, 1, 2]
        );
    }

    #[test]
    fn an_image_pins_every_reserved_row_to_its_line() {
        let d = doc("![alt](missing.png)\n");
        let b = block_at(&d, 0);
        assert_eq!(d.block_own_line_count(b), 4);
        assert!((0..4).all(|r| line_for_row(&d, b, r) == 0));
        assert_eq!(row_for_line(&d, b, 0), 0);
    }

    /// A line whose first row is a marker of its own shows its chars on the row below, and the
    /// cursor goes there; a line no later row shows stays on its first.
    #[test]
    fn a_position_lands_on_the_row_showing_its_char() {
        // Rows: `•`, `  • a`, `    • b`, `• c`.
        let d = doc("- - a\n  - b\n- c\n");
        let b = block_at(&d, 0);
        assert_eq!(row_for_line(&d, b, 0), 0);
        for col in [0, 2, 4, 5] {
            assert_eq!(row_for_pos(&d, b, RawPos { line: 0, col }), 1, "col {col}");
        }
        assert_eq!(row_for_pos(&d, b, RawPos { line: 2, col: 2 }), 3);
        // Rows: `•`, the ` bash ` label, the body, the closing fence.
        let d = doc("- ```bash\n  x\n  ```\n");
        let b = block_at(&d, 0);
        assert_eq!(row_for_pos(&d, b, RawPos { line: 0, col: 4 }), 0);
    }

    // ── Columns ───────────────────────────────────────────────────────────

    /// The row of `block` whose text contains `needle`.
    fn row_with(d: &ParsedDoc, block: usize, needle: &str) -> usize {
        let rows = d.source_map.rendered_lines_for_block(block);
        rows.clone()
            .position(|r| {
                d.lines[r]
                    .spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
                    .contains(needle)
            })
            .expect("row present")
    }

    fn pos(line: usize, col: usize) -> RawPos {
        RawPos { line, col }
    }

    /// A fenced block reveals its fence rows and never its body; an unclosed fence's last line
    /// is ordinary code; an indented block reveals nothing; prose reveals.
    #[test]
    fn only_verbatim_rows_never_reveal() {
        let d = doc("```rust\nlet x = 1;\n```\n\n    indented\n\npara\n\n```\nopen\n");
        let fenced = block_at(&d, 0);
        assert_eq!(
            (0..3).map(|r| reveals(&d, fenced, r)).collect::<Vec<_>>(),
            [true, false, true]
        );
        let src = d.source();
        let indented = block_at(&d, src.find("indented").unwrap());
        assert!(!reveals(&d, indented, 0));
        assert!(reveals(&d, block_at(&d, src.find("para").unwrap()), 0));
        let open = block_at(&d, src.find("open").unwrap());
        assert!(!reveals(&d, open, row_with(&d, open, "open")));
    }

    /// A figures-off `$$…$$` formula reveals its `$$` rows, never its body.
    #[test]
    fn a_figures_off_formula_reveals_only_its_delimiters() {
        let d = ParsedDoc::build_with_overrides(
            "$$\nE = mc^2\n$$\n",
            theme(),
            true,
            4,
            None,
            None,
            false,
            80,
            false,
            false,
            false,
            false,
            None,
        );
        let b = block_at(&d, 0);
        let body = row_with(&d, b, "E = mc^2");
        assert!(!reveals(&d, b, body));
        assert!(reveals(&d, b, body - 1) && reveals(&d, b, body + 1));
    }

    /// A code body renders behind one pad cell, past the indent pulldown-cmark stripped; a click
    /// on the pad lands on the first content char, one in the fill past the line on its end.
    #[test]
    fn a_code_row_maps_past_its_pad_cell() {
        // Inside a list item: the item indent is stripped too, and the block renders under the
        // item's text, two cells in.
        let d = doc("- a\n\n  ```\n  let x = 1;\n  ```\n");
        let b = block_at(&d, 0);
        let row = row_with(&d, b, "let x");
        let eq = 2 + "let x ".len();
        assert_eq!(rendered_to_raw_col(&d, b, row, 9), pos(3, eq));
        assert_eq!(raw_to_rendered_col(&d, b, row, pos(3, eq)), Some(9));
        assert_eq!(
            rendered_to_raw_col(&d, b, row, 2),
            pos(3, 2),
            "the pad cell"
        );
        assert_eq!(
            rendered_to_raw_col(&d, b, row, 0),
            pos(3, 2),
            "the item's indent"
        );
        assert_eq!(rendered_to_raw_col(&d, b, row, 60), pos(3, 12), "the fill");
        // A column in the stripped indent shows on the first content cell.
        assert_eq!(raw_to_rendered_col(&d, b, row, pos(3, 0)), Some(3));
    }

    /// A click on a chrome row whose line is all chrome (a fence, a setext underline) lands past
    /// the container prefix, on the fence or rule itself, not in the indent or on the `>`.
    #[test]
    fn a_chrome_rows_click_lands_past_the_container_prefix() {
        // Rows: `• a`, the ` rust ` label, the body, the closing fence.
        let d = doc("- a\n\n  ```rust\n  x\n  ```\n");
        let b = block_at(&d, 0);
        let label = row_with(&d, b, "rust");
        assert_eq!(rendered_to_raw_col(&d, b, label, 3), pos(2, 2));
        assert_eq!(rendered_to_raw_col(&d, b, label + 2, 0), pos(4, 2));
        // The fence opens on the item's marker line, inside a quote.
        let d = doc("> - ```\n>   x\n>   ```\n");
        let b = block_at(&d, 0);
        let body = row_with(&d, b, "x");
        assert_eq!(rendered_to_raw_col(&d, b, body + 1, 0), pos(2, 4));
        assert_eq!(rendered_to_raw_col(&d, b, body - 1, 0), pos(0, 4));
        // The underline takes the heading text's column.
        let d = doc("> Foo\n> ===\n");
        let b = block_at(&d, 0);
        assert_eq!(lines_of_row(&d, b, 1), Some(1..2), "the rule row");
        assert_eq!(rendered_to_raw_col(&d, b, 1, 0), pos(1, 2));
    }

    /// An indented block's range starts past its indent, and columns on its first line count
    /// from there, as the callers slice it.
    #[test]
    fn an_indented_blocks_first_line_counts_from_its_range() {
        let d = doc("Intro.\n\n    let x = 1;\n");
        let b = block_at(&d, d.source().find("let").unwrap());
        assert_eq!(rendered_to_raw_col(&d, b, 0, 7), pos(0, 6));
        assert_eq!(raw_to_rendered_col(&d, b, 0, pos(0, 6)), Some(7));
    }

    /// A marker's cells line up with the raw marker from the right, so a task box is hit
    /// exactly; indentation lands past itself.
    #[test]
    fn a_prefix_aligns_with_its_raw_marker_from_the_right() {
        let d = doc("- a\n  - [ ] b\n");
        let b = block_at(&d, 0);
        let row = row_with(&d, b, "b");
        // Rendered `    • [ ] b` (or the bullet-less task form): the `[` is right-aligned.
        let text: String = d.lines[row]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        let bracket = text.chars().position(|c| c == '[').unwrap();
        assert_eq!(rendered_to_raw_col(&d, b, row, bracket), pos(1, 4));
        assert_eq!(raw_to_rendered_col(&d, b, row, pos(1, 4)), Some(bracket));
        assert_eq!(
            rendered_to_raw_col(&d, b, row, 0),
            pos(1, 2),
            "indent lands on the marker"
        );
    }

    /// A marker padded out to its content with more spaces than the rendered one still lines up
    /// with its glyph; the surplus spaces render nothing and show on the content start.
    #[test]
    fn a_padded_marker_aligns_with_its_glyph() {
        for (src, marker) in [("1.  foo\n", "1."), ("-   foo\n", "-"), (">   foo\n", ">")] {
            let d = doc(src);
            let b = block_at(&d, 0);
            let content = src.find('f').unwrap();
            for (i, _) in marker.char_indices() {
                assert_eq!(
                    rendered_to_raw_col(&d, b, 0, i),
                    pos(0, i),
                    "{src:?} char {i}"
                );
                assert_eq!(
                    raw_to_rendered_col(&d, b, 0, pos(0, i)),
                    Some(i),
                    "{src:?} col {i}"
                );
            }
            let start = raw_to_rendered_col(&d, b, 0, pos(0, content)).unwrap();
            assert_eq!(
                raw_to_rendered_col(&d, b, 0, pos(0, content - 1)),
                Some(start),
                "{src:?}: a surplus space"
            );
        }
    }

    /// A line ending in an escaped backslash (`a\\`) has no hard break to drop: its rendered `\`
    /// maps to the backslash that shows, not the one escaping it.
    #[test]
    fn an_escaped_trailing_backslash_maps_to_itself() {
        let d = doc("a\\\\\nb\n");
        let b = block_at(&d, 0);
        assert_eq!(rendered_to_raw_col(&d, b, 0, 1), pos(0, 2));
        assert_eq!(raw_to_rendered_col(&d, b, 0, pos(0, 2)), Some(1));
    }

    /// A flow maps across its lines, a break onto the end of the line it ends; an inline
    /// spanning a break maps through the joined text.
    #[test]
    fn a_flow_maps_across_its_lines() {
        let d = ParsedDoc::build_with_overrides(
            "one\n*two\nthree*\n",
            theme(),
            true,
            4,
            None,
            None,
            false,
            80,
            false,
            false,
            true,
            true,
            None,
        );
        let b = block_at(&d, 0);
        // Rendered `one two three`.
        assert_eq!(rendered_to_raw_col(&d, b, 0, 3), pos(0, 3), "the break");
        assert_eq!(
            rendered_to_raw_col(&d, b, 0, 4),
            pos(1, 1),
            "`t` past the `*`"
        );
        assert_eq!(rendered_to_raw_col(&d, b, 0, 8), pos(2, 0));
        assert_eq!(raw_to_rendered_col(&d, b, 0, pos(2, 2)), Some(10));
        assert_eq!(
            raw_to_rendered_col(&d, b, 0, pos(1, 0)),
            Some(4),
            "a marker shows on the next char"
        );
    }

    /// A row a break cuts out of a paragraph maps as part of the whole paragraph: its own line
    /// alone reads `c* d` with a literal `*`.
    #[test]
    fn a_row_cut_from_an_inline_maps_through_its_paragraph() {
        let d = doc("a *b\nc* d\n");
        let b = block_at(&d, 0);
        assert_eq!(lines_of_row(&d, b, 0), Some(0..1));
        assert_eq!(lines_of_row(&d, b, 1), Some(1..2));
        // Rendered `a b`, then `c d`.
        assert_eq!(
            rendered_to_raw_col(&d, b, 0, 2),
            pos(0, 3),
            "`b` past the `*`"
        );
        assert_eq!(
            raw_to_rendered_col(&d, b, 0, pos(0, 4)),
            Some(3),
            "the row's end"
        );
        assert_eq!(rendered_to_raw_col(&d, b, 1, 0), pos(1, 0));
        assert_eq!(
            rendered_to_raw_col(&d, b, 1, 2),
            pos(1, 3),
            "`d` past the `*`"
        );
        assert_eq!(raw_to_rendered_col(&d, b, 1, pos(1, 1)), Some(1), "the `*`");
    }

    /// Where no map renders exactly what the row shows, columns can't be placed exactly, and
    /// the indicator falls back to one char for one past the content start.
    #[test]
    fn a_row_no_map_matches_has_no_exact_columns() {
        // pulldown-cmark folds `ss` and `ß` to one label; the maps' lowercasing doesn't, so the
        // reference collapses in the row but stays literal in the map.
        let d = doc("x[^ss] y\n\n[^ß]: n\n");
        let b = block_at(&d, 0);
        assert_eq!(raw_to_rendered_col(&d, b, 0, pos(0, 7)), None);
        assert_eq!(raw_to_rendered_col_near(&d, b, 0, pos(0, 7)), 7);
    }

    /// A reference link or footnote the document defines renders as the document parsed it, so
    /// its row maps exactly; an undefined footnote reference stays literal and maps one for one.
    #[test]
    fn a_rows_references_resolve_against_the_documents_definitions() {
        let d = doc("see [it][r] now [^n] [^x]\n\n[r]: /u\n[^n]: note\n");
        let b = block_at(&d, 0);
        let text: String = d.lines[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(text.starts_with("see it now [n] [^x]"), "{text:?}");
        assert_eq!(
            rendered_to_raw_col(&d, b, 0, 7),
            pos(0, 12),
            "the `n` of `now`"
        );
        assert_eq!(raw_to_rendered_col(&d, b, 0, pos(0, 12)), Some(7));
        assert_eq!(
            raw_to_rendered_col(&d, b, 0, pos(0, 19)),
            Some(13),
            "the `]` of `[^n]`"
        );
        assert_eq!(
            raw_to_rendered_col(&d, b, 0, pos(0, 23)),
            Some(17),
            "the `x` of `[^x]`"
        );
    }

    /// An ATX heading's closing sequence renders nothing, and its row maps exactly up to it.
    #[test]
    fn an_atx_headings_closing_sequence_is_not_content() {
        for src in ["## Title ##\n", "> ## Title ##\n"] {
            let d = doc(src);
            let b = block_at(&d, 0);
            let row = row_with(&d, b, "Title");
            let t = src.find('T').unwrap();
            let shown = raw_to_rendered_col(&d, b, row, pos(0, t)).expect("an exact map");
            assert_eq!(
                raw_to_rendered_col(&d, b, row, pos(0, t + 4)),
                Some(shown + 4),
                "{src:?}"
            );
            assert_eq!(
                rendered_to_raw_col(&d, b, row, shown + 4),
                pos(0, t + 4),
                "{src:?}"
            );
        }
    }

    /// Every row's table part, read off the origins: borders, the heavy rule, a wrapped data
    /// row's chunks and the separators between rows, striped or ruled alike, and nothing for the
    /// list marker's own row above a table opening on it.
    #[test]
    fn table_parts_follow_the_rows_the_renderer_drew() {
        use TablePart::*;
        let build = |src: &str, striping: bool| {
            ParsedDoc::build_with_overrides(
                src,
                theme(),
                true,
                4,
                None,
                None,
                striping,
                24,
                false,
                false,
                true,
                false,
                None,
            )
        };
        let wrapped = "| a | b |\n|---|---|\n| 1 | alpha bravo charlie delta |\n| 3 | 4 |\n";
        for striping in [false, true] {
            let parsed = build(wrapped, striping);
            let parts: Vec<_> = table_parts(&parsed, 0).into_iter().flatten().collect();
            let want = [
                TopBorder,
                Header { sub: 0 },
                HeavyRule,
                DataRow { row: 0, sub: 0 },
                DataRow { row: 0, sub: 1 },
                Separator,
                DataRow { row: 1, sub: 0 },
                BottomBorder,
            ];
            assert_eq!(parts, want.map(|p| (0, p)), "striping {striping}");
        }

        assert!(
            table_parts(&doc("para\n"), 0).is_empty(),
            "a block with no table"
        );

        // A table with no data rows: its heavy rule and bottom border show the same line.
        let parsed = doc("| a |\n|---|\n");
        let parts: Vec<_> = table_parts(&parsed, 0).into_iter().flatten().collect();
        let want = [TopBorder, Header { sub: 0 }, HeavyRule, BottomBorder];
        assert_eq!(parts, want.map(|p| (0, p)));

        // In a list item opening on the table, the marker's row comes first and is no part;
        // the second table's header is on block-relative line 4.
        let parsed = doc("- | a |\n  |---|\n  | 1 |\n\n  | c |\n  |---|\n");
        let parts = table_parts(&parsed, 0);
        assert_eq!(parts[0], None, "the marker's row");
        assert_eq!(parts[1], Some((0, TopBorder)));
        assert_eq!(parts[4], Some((0, DataRow { row: 0, sub: 0 })));
        assert_eq!(parts[5], Some((0, BottomBorder)));
        let second: Vec<_> = parts.iter().flatten().filter(|(h, _)| *h == 4).collect();
        assert_eq!(second.first(), Some(&&(4, TopBorder)));
        assert_eq!(second.last(), Some(&&(4, BottomBorder)));
    }

    /// The items holding a line, outermost first, each at its content column; none in a quote
    /// or a footnote, or outside a list.
    #[test]
    fn item_content_cols_name_each_item_holding_a_line() {
        let cases: [(&str, usize, &[usize]); 8] = [
            ("- foo\n", 0, &[2]),
            ("10. foo\n", 0, &[4]),
            ("-   foo\n  bar\n", 1, &[4]),
            ("- outer\n  - inner\n", 1, &[2, 4]),
            ("- outer\n  - inner\n\n  more\n", 3, &[2]),
            ("> - foo\n", 0, &[]),
            ("x[^n]\n\n[^n]: - foo\n", 2, &[]),
            ("para\n", 0, &[]),
        ];
        for (src, line, want) in cases {
            assert_eq!(
                item_content_cols(&doc(src), line),
                want,
                "{src:?} line {line}"
            );
        }
    }
}