catcher 0.9.1

A minimal, local-first markdown notes TUI over plain files
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
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
//! Markdown → styled cells for the full-page preview (^P).
//!
//! Block structure comes from pulldown-cmark here; the live-preview editor is
//! line-based instead. Both share the palette in [`crate::md::theme`].
//!
//! The preview keeps more than text: every cell remembers whether it belongs to
//! a link, every line remembers which source line it came from, and checkbox and
//! image lines are tagged. That is what makes the preview clickable — open a
//! link, toggle a checkbox, or click anywhere else to land in the editor at the
//! same place.

use crate::config::TableStyle;
use crate::md::theme;
use pulldown_cmark::{Alignment, Event, Options, Parser, Tag, TagEnd};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

/// One rendered character: what to draw, which link (if any) it belongs to, and
/// where in the source it came from — `None` for scaffolding the renderer added
/// itself (bullets, table padding, code-block indents, image labels).
#[derive(Clone, Debug, PartialEq)]
pub struct PCell {
    pub ch: char,
    pub style: Style,
    pub link: Option<usize>,
    /// (source line, source column in chars) this character was drawn from.
    pub src: Option<(usize, usize)>,
}

/// An inline image the preview would like to draw.
#[derive(Clone, Debug, PartialEq)]
pub struct ImageSpec {
    pub alt: String,
    pub url: String,
}

/// One rendered line, plus what a click on it should do.
#[derive(Clone, Debug, Default)]
pub struct PLine {
    pub cells: Vec<PCell>,
    /// Source line to toggle when this line's checkbox is clicked.
    pub checkbox: Option<usize>,
    /// Index into [`Rendered::images`] when this line stands in for an image.
    pub image: Option<usize>,
    /// Source line this rendered line came from, for click → cursor.
    pub src_line: Option<usize>,
    /// This line is deliberately wider than the page and must not be
    /// soft-wrapped: it is one row of a scrolling table, and the page pans
    /// sideways across it instead.
    pub wide: bool,
}

/// Merge equal-styled cells into a ratatui line.
pub fn to_line(cells: &[PCell]) -> Line<'static> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut text = String::new();
    let mut current: Option<Style> = None;
    for cell in cells {
        if current != Some(cell.style) {
            if let Some(s) = current {
                spans.push(Span::styled(std::mem::take(&mut text), s));
            }
            current = Some(cell.style);
        }
        text.push(cell.ch);
    }
    if let Some(s) = current {
        spans.push(Span::styled(text, s));
    }
    Line::from(spans)
}

impl PLine {
    /// The plain text of the line, for tests and debugging.
    #[cfg(test)]
    pub fn text(&self) -> String {
        self.cells.iter().map(|c| c.ch).collect()
    }
}

/// A whole rendered page.
#[derive(Clone, Debug, Default)]
pub struct Rendered {
    pub lines: Vec<PLine>,
    pub urls: Vec<String>,
    pub images: Vec<ImageSpec>,
}

impl Rendered {
    pub fn url(&self, i: usize) -> Option<&str> {
        self.urls.get(i).map(String::as_str)
    }
}

/// Options: GitHub-flavoured enough for notes.
fn options() -> Options {
    Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_TABLES
}

/// Unbounded-width render, for tests that don't care about the page width.
#[cfg(test)]
pub fn render(markdown: &str) -> Rendered {
    render_wide(markdown, usize::MAX)
}

/// Render for a page `width` columns wide, with the default table shape.
#[cfg(test)]
pub fn render_wide(markdown: &str, width: usize) -> Rendered {
    render_page(markdown, width, TableStyle::default())
}

/// Render for a page `width` columns wide, drawing wide tables the way the
/// settings ask for.
/// Test-only since the reading view started slicing the front matter off: the
/// app always knows what line its markdown began on, so it always has an
/// offset to pass. This is that call with the offset zero.
#[cfg(test)]
pub fn render_page(markdown: &str, width: usize, tables: TableStyle) -> Rendered {
    render_page_at(markdown, 0, width, tables)
}

/// The same, when `markdown` is a slice of a longer file that begins at source
/// line `first_line` — the reading view hands us a body with its front matter
/// already cut off. Every line number a cell reports is file-absolute, because
/// `PCell::src` and `PLine::src_line` are what a click in the preview turns
/// back into a position in the buffer.
pub fn render_page_at(
    markdown: &str,
    first_line: usize,
    width: usize,
    tables: TableStyle,
) -> Rendered {
    let mut r = Ren::new(markdown, first_line, width, tables);
    r.run(markdown);
    r.finish()
}

/// Add the linked-mentions footer to an already-rendered page: a rule, a count,
/// and one row per note that links here.
///
/// It is appended rather than rendered because it is not part of the note — the
/// file on disk says nothing about who points at it, and nothing the footer
/// draws should ever map back into the buffer. Every cell it makes carries no
/// source position and every line no source line, so a click in the footer can
/// open the note it names but can never land the cursor in the note you are
/// reading.
///
/// With no mentions there is no footer at all, not even a rule: a note nothing
/// links to should look like a note, not like a note with an empty drawer at
/// the bottom.
pub fn append_mentions(r: &mut Rendered, mentions: &[crate::mentions::Mention], width: usize) {
    if mentions.is_empty() {
        return;
    }
    let dim = theme::marker();
    r.lines.push(PLine::default());
    r.lines.push(PLine {
        // the same rule the document itself draws for `---`, so the footer is
        // separated the way a section of the note would be
        cells: str_cells(&"".repeat(width.min(40)), dim),
        ..Default::default()
    });
    let count = match mentions.len() {
        1 => "1 note links here".to_string(),
        n => format!("{n} notes link here"),
    };
    r.lines.push(PLine {
        cells: str_cells(&count, dim),
        ..Default::default()
    });

    // one name column for the whole footer, so the excerpts line up and read
    // as a column rather than as ragged sentences
    let namew = mentions
        .iter()
        .map(|m| crate::md::str_width(&m.name))
        .max()
        .unwrap_or(0)
        .min(MAX_NAME_COLS)
        .min(width.saturating_sub(2));
    for m in mentions {
        let idx = r.urls.len();
        // an exact file, not a name to resolve again: two notes called `spec`
        // must not send the click to whichever one the resolver prefers
        r.urls
            .push(crate::md::LinkTarget::Note(m.path.to_string_lossy().into_owned()).href());
        let mut cells = str_cells("  ", dim);
        let mut name = truncate_cells(&str_cells(&m.name, theme::link()), namew);
        for c in &mut name {
            c.link = Some(idx);
        }
        let pad = namew.saturating_sub(cells_width(&name));
        cells.extend(name);
        cells.extend(str_cells(&" ".repeat(pad), dim));
        // ×3 is the whole reason the row collapsed, so its room is taken
        // before the excerpt's and it is never the thing that gets cut away
        let tail = if m.count > 1 {
            format!(" ×{}", m.count)
        } else {
            String::new()
        };
        let room = width
            .saturating_sub(cells_width(&cells) + 2 + crate::md::str_width(&tail))
            .min(MAX_EXCERPT_COLS);
        // a narrow page should show fewer things rather than shredded ones: an
        // excerpt with a dozen columns to live in says nothing worth the space
        if room >= 12 && !m.excerpt.is_empty() {
            cells.extend(str_cells("  ", dim));
            cells.extend(excerpt_cells(&m.excerpt, m.link, dim, room));
        }
        cells.extend(str_cells(&tail, dim));
        r.lines.push(PLine {
            // never wider than the page: the footer must not be the thing that
            // makes a page of prose pan sideways
            cells: truncate_cells(&cells, width),
            ..Default::default()
        });
    }
}

/// The widest an excerpt is ever drawn, however wide the window is. Past this
/// the eye stops reading the column and starts reading the page twice.
const MAX_EXCERPT_COLS: usize = 80;
/// The widest the name column gets: a longer name is cut, so one note with a
/// long name cannot push every excerpt off the page.
const MAX_NAME_COLS: usize = 28;

/// An excerpt styled the way the editor would style it — bold as bold, a
/// wikilink as its label — and cut to `room` columns around the link at
/// `link` (a char span in `excerpt`), so the link itself is always on screen.
/// The cells carry no link and no source position: the footer is not the
/// note, and a click on an excerpt has nowhere in the note to go.
fn excerpt_cells(
    excerpt: &str,
    link: (usize, usize),
    base: Style,
    room: usize,
) -> Vec<PCell> {
    let cells: Vec<PCell> = crate::md::style_inline(excerpt)
        .into_iter()
        .map(|c| PCell {
            ch: c.ch,
            style: base.patch(c.style),
            link: None,
            src: Some((0, c.src)),
        })
        .collect();
    if cells_width(&cells) <= room {
        return strip_src(cells);
    }
    // where the link landed once the brackets were hidden
    let first = cells.iter().position(|c| c.src.is_some_and(|s| s.1 >= link.0));
    let last = cells.iter().rposition(|c| c.src.is_some_and(|s| s.1 < link.1));
    let (Some(first), Some(last)) = (first, last) else {
        return strip_src(truncate_cells(&cells, room));
    };
    let before = cells_width(&cells[..first]);
    let linkw = cells_width(&cells[first..=last]);
    // the link fits from the start: cut from the right as any row would be
    if before + linkw < room {
        return strip_src(truncate_cells(&cells, room));
    }
    // otherwise open a window with the link a third of the way in, so what
    // was said before it is read as context and what came after as the point
    let lead = room.saturating_sub(linkw + 2) / 3;
    let mut skip = first;
    let mut skipped = 0;
    while skip > 0 && skipped + crate::md::char_width(cells[skip - 1].ch) <= lead {
        skip -= 1;
        skipped += crate::md::char_width(cells[skip].ch);
    }
    let mut out = str_cells("", base);
    out.extend(truncate_cells(&cells[skip..], room.saturating_sub(1)));
    strip_src(out)
}

/// Forget the source columns the inline styler recorded: they were only ever
/// there to find the link, and a footer cell must not map into the note.
fn strip_src(mut cells: Vec<PCell>) -> Vec<PCell> {
    for c in &mut cells {
        c.src = None;
    }
    cells
}

/// Where cells are currently going: the page, or a table cell being measured.
enum Sink {
    Page,
    Table,
}

#[derive(Default)]
struct Table {
    aligns: Vec<Alignment>,
    rows: Vec<Vec<Vec<PCell>>>,
    in_head: bool,
    row: Vec<Vec<PCell>>,
}

struct Ren {
    /// The source, kept so cells can remember the column they came from.
    src: String,
    out: Rendered,
    cells: Vec<PCell>,
    cell_buf: Vec<PCell>,
    sink: Sink,
    styles: Vec<Style>,
    link: Option<usize>,
    /// How many `▌ ` rails the line being built sits behind — one per
    /// enclosing plain blockquote.
    rails: usize,
    /// Inside a callout box (`> [!type]`). Only the outermost callout gets a
    /// box; a callout inside it is drawn as a rail.
    boxed: bool,
    /// Columns the open box spans, fixed when it opened: the page width is
    /// narrowed while a table is laid out, and the box must not follow it.
    box_w: usize,
    /// A quote has just opened and nothing has been drawn inside it yet, so a
    /// block asking for a blank line above itself does not get a rail-only row.
    quote_fresh: bool,
    /// The last row emitted was a rail-only (or box-only) blank row.
    quote_blank: bool,
    /// Columns the continuation rows of the line being built hang in under
    /// its marker — a list item wraps under its text, not under its bullet.
    hang: usize,
    list_depth: usize,
    in_code_block: bool,
    table: Option<Table>,
    /// How a table wider than the page is drawn.
    tables: TableStyle,
    /// Page width in columns, used to size tables.
    width: usize,
    /// Byte offset of the start of each source line.
    line_starts: Vec<usize>,
    /// Source line the slice being rendered starts at in the file.
    first_line: usize,
    /// Source line for the line currently being built.
    src_line: Option<usize>,
    pending_checkbox: Option<usize>,
    done_item: bool,
    image_alt: Option<(String, String)>,
    /// Byte offset the renderer has already drawn past. pulldown-cmark has
    /// never heard of a wikilink and hands `[[a|b]]` back as a run of separate
    /// text events, one per bracket: the first of them is where the whole span
    /// is recognised and drawn from the source, and the rest have to be
    /// swallowed rather than drawn a second time.
    wiki_until: usize,
}

impl Ren {
    fn new(markdown: &str, first_line: usize, width: usize, tables: TableStyle) -> Ren {
        let mut line_starts = vec![0usize];
        for (i, b) in markdown.bytes().enumerate() {
            if b == b'\n' {
                line_starts.push(i + 1);
            }
        }
        Ren {
            src: markdown.to_string(),
            out: Rendered::default(),
            cells: Vec::new(),
            cell_buf: Vec::new(),
            sink: Sink::Page,
            styles: vec![Style::default()],
            link: None,
            rails: 0,
            boxed: false,
            box_w: 0,
            quote_fresh: false,
            quote_blank: false,
            hang: 0,
            list_depth: 0,
            in_code_block: false,
            table: None,
            tables,
            width,
            line_starts,
            first_line,
            src_line: None,
            pending_checkbox: None,
            done_item: false,
            image_alt: None,
            wiki_until: 0,
        }
    }

    fn style(&self) -> Style {
        *self.styles.last().unwrap()
    }

    fn buf(&mut self) -> &mut Vec<PCell> {
        match self.sink {
            Sink::Page => &mut self.cells,
            Sink::Table => &mut self.cell_buf,
        }
    }

    /// Push scaffolding the renderer invented: it maps back to no source column.
    fn push(&mut self, text: &str, style: Style, link: Option<usize>) {
        self.push_at(text, style, link, None);
    }

    /// Push text, optionally carrying the source byte offset of its first
    /// character so each cell remembers where it came from.
    fn push_at(&mut self, text: &str, style: Style, link: Option<usize>, off: Option<usize>) {
        let mut off = off;
        let mut cells: Vec<PCell> = Vec::with_capacity(text.len());
        for ch in text.chars() {
            cells.push(PCell {
                ch,
                style,
                link,
                src: off.map(|o| self.pos_of(o)),
            });
            if let Some(o) = off.as_mut() {
                *o += ch.len_utf8();
            }
        }
        self.buf().extend(cells);
    }

    fn line_of(&self, offset: usize) -> usize {
        match self.line_starts.binary_search(&offset) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        }
    }

    /// Source byte offset → (line, column in chars), the line counted from the
    /// top of the *file*. `line_of` stays slice-relative on purpose: its
    /// result indexes `line_starts` and `src`, both of which are the slice's.
    fn pos_of(&self, offset: usize) -> (usize, usize) {
        let line = self.line_of(offset);
        let start = self.line_starts.get(line).copied().unwrap_or(0);
        let offset = offset.min(self.src.len());
        let col = self.src.get(start..offset).map_or(0, |s| s.chars().count());
        (self.first_line + line, col)
    }

    fn flush(&mut self) {
        if self.cells.is_empty() {
            return;
        }
        let cells = std::mem::take(&mut self.cells);
        let checkbox = self.pending_checkbox.take();
        let src_line = self.src_line;
        let hang = std::mem::take(&mut self.hang);
        self.emit_wrapped(cells, checkbox, None, src_line, hang);
    }

    /// Width the text of a line may use once the quote decoration around it
    /// — box edges and rails — has taken its share.
    fn inner_width(&self) -> usize {
        let taken = self.rails * 2 + if self.boxed { 4 } else { 0 };
        if self.width == usize::MAX {
            usize::MAX
        } else {
            self.width.saturating_sub(taken).max(8)
        }
    }

    /// Width a callout box is drawn at. A width no page has means the caller
    /// did not care, so the box takes a comfortable default.
    fn box_width(&self) -> usize {
        if self.width == usize::MAX {
            80
        } else {
            self.width.max(8)
        }
    }

    /// Wrap a line to the room inside its quote decoration and emit each row
    /// with its rails and box edges. Wrapping happens here, not in the draw,
    /// so every row a quote takes gets its bar — the draw only sees rows that
    /// already fit the page.
    fn emit_wrapped(
        &mut self,
        cells: Vec<PCell>,
        checkbox: Option<usize>,
        image: Option<usize>,
        src_line: Option<usize>,
        hang: usize,
    ) {
        if self.rails == 0 && !self.boxed {
            self.emit_line(PLine {
                cells,
                checkbox,
                image,
                src_line,
                wide: false,
            });
            return;
        }
        let avail = self.inner_width();
        let rest = avail.saturating_sub(hang).max(4);
        for (i, row) in wrap_hang(&cells, avail, rest).into_iter().enumerate() {
            let mut cells = if i == 0 {
                Vec::new()
            } else {
                str_cells(&" ".repeat(hang), theme::PLAIN)
            };
            cells.extend(row);
            self.emit_line(PLine {
                cells,
                checkbox: if i == 0 { checkbox } else { None },
                image: if i == 0 { image } else { None },
                src_line,
                wide: false,
            });
        }
    }

    /// Put one row on the page, behind whatever rails and box edges the row
    /// is inside. Every row the renderer makes goes through here, so a table
    /// or a code line inside a quote is decorated like a paragraph is. A wide
    /// (panning) row is left bare: its edges would pan off with it.
    fn emit_line(&mut self, mut line: PLine) {
        if !line.wide && (self.rails > 0 || self.boxed) {
            let mut cells = Vec::new();
            if self.boxed {
                cells.extend(str_cells("", theme::state()));
            }
            for _ in 0..self.rails {
                cells.extend(str_cells(&format!("{} ", theme::QUOTE_BAR), theme::marker()));
            }
            cells.extend(line.cells);
            if self.boxed {
                let pad = self.box_w.saturating_sub(cells_width(&cells) + 2);
                cells.extend(str_cells(&" ".repeat(pad), theme::PLAIN));
                cells.extend(str_cells("", theme::state()));
            }
            line.cells = cells;
        }
        self.quote_fresh = false;
        self.quote_blank = false;
        self.out.lines.push(line);
    }

    fn blank(&mut self) {
        self.flush();
        if self.rails > 0 || self.boxed {
            // a rail-only row, once, and never as the first thing in a quote
            if self.quote_fresh || self.quote_blank {
                return;
            }
            self.emit_line(PLine::default());
            self.quote_blank = true;
            return;
        }
        if !self
            .out
            .lines
            .last()
            .map(|l| l.cells.is_empty())
            .unwrap_or(true)
        {
            self.out.lines.push(PLine::default());
        }
    }

    /// Open a callout box: the title row, in the accent.
    fn open_box(&mut self, kind: &str, title: &str) {
        let w = self.box_width();
        self.box_w = w;
        let mut cells = str_cells("╭─ ", theme::state());
        if let Some(g) = callout_glyph(kind) {
            cells.extend(str_cells(&format!("{g} "), theme::state()));
        }
        cells.extend(str_cells(kind, theme::state()));
        if !title.is_empty() {
            cells.extend(str_cells(" · ", theme::state()));
            cells.extend(str_cells(
                title,
                theme::state().add_modifier(Modifier::BOLD),
            ));
        }
        cells.push(PCell {
            ch: ' ',
            style: theme::state(),
            link: None,
            src: None,
        });
        let cells = truncate_cells(&cells, w.saturating_sub(1));
        let mut row = cells;
        let dashes = w.saturating_sub(cells_width(&row) + 1);
        row.extend(str_cells(&"".repeat(dashes), theme::state()));
        row.extend(str_cells("", theme::state()));
        self.out.lines.push(PLine {
            cells: row,
            checkbox: None,
            image: None,
            src_line: self.src_line,
            wide: false,
        });
    }

    fn close_box(&mut self) {
        let w = self.box_w;
        let row = format!("{}", "".repeat(w.saturating_sub(2)));
        self.out.lines.push(PLine {
            cells: str_cells(&row, theme::state()),
            checkbox: None,
            image: None,
            src_line: self.src_line,
            wide: false,
        });
    }

    fn indent(&self) -> String {
        "  ".repeat(self.list_depth.saturating_sub(1))
    }

    /// The `[[wikilink]]` starting at byte offset `off` of the source, as
    /// (byte offset just past it, target, label start, label end).
    ///
    /// It reads the source rather than the event's text because pulldown hands
    /// the brackets back one at a time — there is no single event to split
    /// around. The escape and embed guards are repeated here rather than left
    /// to `md::wikilink_at` because the char slice below starts at `off` and
    /// cannot see the character before it.
    ///
    /// One limitation worth knowing: inside a GFM table cell an unescaped `|`
    /// is the cell delimiter, so `[[note|label]]` is cut into two cells before
    /// the renderer ever sees it. Obsidian has the same problem and the same
    /// answer (`\|`), and escaping it splits the events so the whole thing
    /// stays literal. Plain and `#heading` wikilinks in a cell are fine.
    fn wikilink_here(&self, off: usize) -> Option<(usize, String, usize, usize)> {
        if !crate::md::links::enabled() || !self.src[off..].starts_with("[[") {
            return None;
        }
        let before = &self.src[..off];
        if before.ends_with('\\') || before.ends_with('!') {
            return None;
        }
        // bounded by the line, and only paid for when a `[[` is really there
        let line_end = self.src[off..]
            .find('\n')
            .map_or(self.src.len(), |n| off + n);
        let chars: Vec<char> = self.src[off..line_end].chars().collect();
        let w = crate::md::wikilink_at(&chars, 0)?;
        let mut byte_at: Vec<usize> = Vec::with_capacity(chars.len() + 1);
        let mut b = off;
        for ch in &chars {
            byte_at.push(b);
            b += ch.len_utf8();
        }
        byte_at.push(b);
        Some((
            byte_at[w.end],
            w.target,
            byte_at[w.label_start],
            byte_at[w.label_end],
        ))
    }

    /// Text from the document: scan for `==highlight==` and bare URLs.
    /// `off` is the source byte offset of `text`, when it is a verbatim slice.
    fn emit_text(&mut self, text: &str, off: Option<usize>) {
        let base = self.style();
        let link = self.link;
        let chars: Vec<char> = text.chars().collect();
        // byte offset of each char, so every run knows where it started
        let mut byte_at: Vec<usize> = Vec::with_capacity(chars.len() + 1);
        let mut b = 0;
        for ch in &chars {
            byte_at.push(b);
            b += ch.len_utf8();
        }
        byte_at.push(b);
        let at = |i: usize| off.map(|o| o + byte_at[i]);

        let mut i = 0;
        let mut run = String::new();
        let mut run_start = 0usize;
        while i < chars.len() {
            // ==highlight==
            if chars[i] == '=' && chars.get(i + 1) == Some(&'=') {
                if let Some(end) = find_pair(&chars, i + 2) {
                    self.push_at(&std::mem::take(&mut run), base, link, at(run_start));
                    let body: String = chars[i + 2..end].iter().collect();
                    self.push_at(&body, base.patch(theme::highlight()), link, at(i + 2));
                    i = end + 2;
                    run_start = i;
                    continue;
                }
            }
            // bare URL, when not already inside a link
            if link.is_none() && starts_url(&chars, i) {
                let mut end = i;
                while end < chars.len() && !chars[end].is_whitespace() {
                    end += 1;
                }
                while end > i && matches!(chars[end - 1], '.' | ',' | ')' | ']' | '!' | '?') {
                    end -= 1;
                }
                let url: String = chars[i..end].iter().collect();
                self.push_at(&std::mem::take(&mut run), base, None, at(run_start));
                let idx = self.out.urls.len();
                self.out.urls.push(crate::md::LinkTarget::Url(url.clone()).href());
                self.push_at(&url, base.patch(theme::link()), Some(idx), at(i));
                i = end;
                run_start = i;
                continue;
            }
            if run.is_empty() {
                run_start = i;
            }
            run.push(chars[i]);
            i += 1;
        }
        self.push_at(&run, base, link, at(run_start));
    }

    fn run(&mut self, markdown: &str) {
        for (event, range) in Parser::new_ext(markdown, options()).into_offset_iter() {
            // file-absolute, like `pos_of`: this is the number a preview click
            // and a checkbox toggle both index the buffer with
            let src_line = self.first_line + self.line_of(range.start);
            if self.cells.is_empty() && matches!(self.sink, Sink::Page) {
                self.src_line = Some(src_line);
            }
            self.event(event, src_line, range);
        }
        self.flush();
    }

    fn event(&mut self, event: Event<'_>, src_line: usize, range: std::ops::Range<usize>) {
        // a `[[wikilink]]` is drawn whole, from its own source, the moment the
        // first event inside it arrives; pulldown then goes on walking what is
        // left of the span one event at a time. Every one of those would draw
        // a second time — the leftover `]]` as text, but also an inline `` `x` ``
        // between the brackets as code, which `md::wikilink_at` allows inside a
        // target and which the live editor draws as part of the label. So the
        // whole span is skipped, not just its text.
        if range.start < self.wiki_until && emits_cells(&event) {
            return;
        }
        match event {
            Event::Start(Tag::Heading { level, .. }) => {
                self.blank();
                self.src_line = Some(src_line);
                self.styles.push(theme::heading(level as usize));
            }
            Event::End(TagEnd::Heading(_)) => {
                self.styles.pop();
                self.flush();
            }
            Event::Start(Tag::Paragraph) => {
                if self.list_depth == 0 && self.table.is_none() {
                    self.blank();
                    self.src_line = Some(src_line);
                }
            }
            Event::End(TagEnd::Paragraph) => self.flush(),
            Event::Start(Tag::BlockQuote(_)) => {
                self.blank();
                self.src_line = Some(src_line);
                match callout_at(&self.src, range.start) {
                    Some((kind, title, end)) if !self.boxed => {
                        self.open_box(&kind, &title);
                        self.boxed = true;
                        // the `[!type] Title` line is the box's title, not
                        // its first paragraph: nothing in it is drawn again
                        self.wiki_until = self.wiki_until.max(end);
                    }
                    Some((_, _, end)) => {
                        self.rails += 1;
                        self.wiki_until = self.wiki_until.max(end);
                    }
                    None => self.rails += 1,
                }
                self.quote_fresh = true;
                self.styles.push(theme::quote());
            }
            Event::End(TagEnd::BlockQuote(_)) => {
                self.styles.pop();
                self.flush();
                if self.rails > 0 {
                    self.rails -= 1;
                } else if self.boxed {
                    self.boxed = false;
                    self.close_box();
                }
                self.quote_fresh = false;
                self.quote_blank = false;
            }
            Event::Start(Tag::List(_)) => {
                if self.list_depth == 0 {
                    self.blank();
                }
                self.list_depth += 1;
            }
            Event::End(TagEnd::List(_)) => {
                self.list_depth = self.list_depth.saturating_sub(1);
                self.flush();
            }
            Event::Start(Tag::Item) => {
                self.flush();
                self.src_line = Some(src_line);
                let text = format!("{}{} ", self.indent(), theme::BULLET);
                self.hang = crate::md::str_width(&text);
                self.push(&text, theme::marker(), None);
            }
            Event::End(TagEnd::Item) => {
                if self.done_item {
                    self.styles.pop();
                    self.done_item = false;
                }
                self.flush()
            }
            Event::TaskListMarker(done) => {
                // replace the bullet we pushed at the start of the item
                self.cells.clear();
                let (mark, style) = if done {
                    (theme::CHECKED, theme::done())
                } else {
                    (theme::UNCHECKED, theme::marker())
                };
                let text = format!("{}{mark} ", self.indent());
                self.hang = crate::md::str_width(&text);
                self.push(&text, style, None);
                self.pending_checkbox = Some(src_line);
                if done {
                    // done items read as struck-through and dim until the item ends
                    self.styles.push(self.style().patch(theme::done_text()));
                    self.done_item = true;
                }
            }
            Event::Start(Tag::CodeBlock(_)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.in_code_block = true;
            }
            Event::End(TagEnd::CodeBlock) => {
                self.in_code_block = false;
                self.flush();
            }
            Event::Start(Tag::Emphasis) => self
                .styles
                .push(self.style().add_modifier(Modifier::ITALIC)),
            Event::Start(Tag::Strong) => {
                self.styles.push(self.style().add_modifier(Modifier::BOLD))
            }
            Event::Start(Tag::Strikethrough) => self
                .styles
                .push(self.style().add_modifier(Modifier::CROSSED_OUT)),
            Event::End(TagEnd::Emphasis)
            | Event::End(TagEnd::Strong)
            | Event::End(TagEnd::Strikethrough) => {
                self.styles.pop();
            }
            Event::Start(Tag::Link { dest_url, .. }) => {
                let idx = self.out.urls.len();
                // through `LinkTarget`, not straight in: a href written in the
                // note is a stranger's text, and `[x](note:/etc/passwd)` must
                // not arrive at the other end looking like a file the app
                // found for itself
                self.out
                    .urls
                    .push(crate::md::LinkTarget::Url(dest_url.into_string()).href());
                self.link = Some(idx);
                self.styles.push(self.style().patch(theme::link()));
            }
            Event::End(TagEnd::Link) => {
                self.styles.pop();
                self.link = None;
            }
            Event::Start(Tag::Image { dest_url, .. }) => {
                self.image_alt = Some((String::new(), dest_url.into_string()));
            }
            Event::End(TagEnd::Image) => {
                if let Some((alt, url)) = self.image_alt.take() {
                    self.flush();
                    let idx = self.out.images.len();
                    self.out.images.push(ImageSpec {
                        alt: alt.clone(),
                        url: url.clone(),
                    });
                    let label = if alt.is_empty() {
                        format!("🖼 {url}")
                    } else {
                        format!("🖼 {alt} ({url})")
                    };
                    self.push(&label, theme::marker(), None);
                    let cells = std::mem::take(&mut self.cells);
                    let src_line = self.src_line;
                    self.emit_wrapped(cells, None, Some(idx), src_line, 0);
                }
            }
            // tables
            Event::Start(Tag::Table(aligns)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.table = Some(Table {
                    aligns,
                    ..Table::default()
                });
            }
            Event::End(TagEnd::Table) => self.emit_table(),
            Event::Start(Tag::TableHead) => {
                if let Some(t) = self.table.as_mut() {
                    t.in_head = true;
                }
            }
            Event::End(TagEnd::TableHead) | Event::End(TagEnd::TableRow) => {
                if let Some(t) = self.table.as_mut() {
                    let row = std::mem::take(&mut t.row);
                    t.rows.push(row);
                    t.in_head = false;
                }
            }
            Event::Start(Tag::TableRow) => {}
            Event::Start(Tag::TableCell) => {
                self.cell_buf.clear();
                self.sink = Sink::Table;
                if self.table.as_ref().is_some_and(|t| t.in_head) {
                    self.styles.push(self.style().add_modifier(Modifier::BOLD));
                }
            }
            Event::End(TagEnd::TableCell) => {
                if self.table.as_ref().is_some_and(|t| t.in_head) {
                    self.styles.pop();
                }
                self.sink = Sink::Page;
                let cell = std::mem::take(&mut self.cell_buf);
                if let Some(t) = self.table.as_mut() {
                    t.row.push(cell);
                }
            }
            Event::Code(code) => {
                let style = self.style().patch(theme::code());
                let link = self.link;
                // the range spans the backticks too; the content starts after them
                let ticks = self.src[range.clone()]
                    .chars()
                    .take_while(|c| *c == '`')
                    .count();
                self.push_at(&code.into_string(), style, link, Some(range.start + ticks));
            }
            Event::Text(text) => {
                if let Some((alt, _)) = self.image_alt.as_mut() {
                    alt.push_str(&text);
                } else if self.in_code_block {
                    let mut off = range.start;
                    // split_inclusive, not lines(): the line ending has to be
                    // counted as it is in the file, `\r\n` included, or every
                    // later offset in a CRLF note drifts by a byte a line
                    for raw in text.split_inclusive('\n') {
                        let l = raw.trim_end_matches('\n').trim_end_matches('\r');
                        // the two-space indent is ours; the code itself is the file's
                        self.push("  ", theme::code(), None);
                        self.push_at(l, theme::code(), None, Some(off));
                        off += raw.len();
                        let cells = std::mem::take(&mut self.cells);
                        let src_line = self.src_line;
                        self.emit_wrapped(cells, None, None, src_line, 2);
                    }
                } else if let Some((end, target, ls, le)) = self.wikilink_here(range.start) {
                    // the label keeps its own source bytes, so `push_at` gives
                    // every cell its true (line, column) and a preview click
                    // lands inside the link rather than at the start of it
                    let label = self.src[ls..le].to_string();
                    let idx = self.out.urls.len();
                    self.out
                        .urls
                        .push(crate::md::LinkTarget::Wiki(target.clone()).href());
                    let style = crate::md::wiki_style(self.style(), &target);
                    self.push_at(&label, style, Some(idx), Some(ls));
                    self.wiki_until = end;
                } else {
                    self.emit_text(&text, Some(range.start));
                }
            }
            Event::SoftBreak => {
                if matches!(self.sink, Sink::Table) {
                    self.push(" ", self.style(), self.link);
                } else {
                    self.flush();
                    self.src_line = Some(src_line);
                }
            }
            Event::HardBreak => self.flush(),
            Event::Rule => {
                self.blank();
                self.push(&"".repeat(40), theme::marker(), None);
                self.flush();
            }
            _ => {}
        }
    }

    /// Lay out the buffered table. Three shapes, because one shape cannot
    /// serve a two-column table and an eight-column one on the same page:
    /// a grid, a grid whose cells wrap, or one labelled block per row.
    fn emit_table(&mut self) {
        let Some(t) = self.table.take() else { return };
        if t.rows.is_empty() {
            return;
        }
        // inside a quote the table has only the room its rails leave it
        let page = self.width;
        self.width = self.inner_width();
        self.emit_table_in(&t);
        self.width = page;
    }

    fn emit_table_in(&mut self, t: &Table) {
        let cols = t.rows.iter().map(|r| r.len()).max().unwrap_or(0);
        let measured: Vec<Vec<usize>> = t
            .rows
            .iter()
            .map(|r| r.iter().map(|c| cells_width(c)).collect())
            .collect();
        let natural = crate::md::column_widths(&measured, cols);
        let seps = crate::md::COL_SEP.chars().count() * cols.saturating_sub(1);
        let fits = natural.iter().sum::<usize>() + seps <= self.width;

        match self.table_shape(cols, seps, fits) {
            Shape::Grid { wrap } => {
                let widths = crate::md::fit_widths(&natural, self.width);
                self.emit_grid(t, cols, &widths, wrap, false);
            }
            Shape::Scroll => {
                let widths = self.scroll_widths(&natural);
                self.emit_grid(t, cols, &widths, true, true);
            }
            Shape::Cards => self.emit_cards(t, cols),
        }
    }

    /// Which shape this table gets. `auto` keeps the grid while its columns are
    /// still wide enough to read a phrase in, and gives up on it — rather than
    /// shaving every column to a stub and an ellipsis — once they are not.
    fn table_shape(&self, cols: usize, seps: usize, fits: bool) -> Shape {
        // below this the columns hit their floor and the grid runs off the
        // page whatever it is told to do, so cards are the only shape left
        let grid_possible = self.width >= cols * crate::md::MIN_COL + seps;
        match self.tables {
            TableStyle::Fit => Shape::Grid { wrap: false },
            TableStyle::Wrap if grid_possible => Shape::Grid { wrap: !fits },
            TableStyle::Wrap => Shape::Cards,
            TableStyle::Cards => Shape::Cards,
            TableStyle::Scroll => Shape::Scroll,
            // a table that already fits is left exactly as it was; one that
            // does not keeps its columns readable and pans instead
            TableStyle::Auto if fits => Shape::Grid { wrap: false },
            TableStyle::Auto => Shape::Scroll,
        }
    }

    /// Column widths for a scrolling table: each column as wide as its widest
    /// cell, capped so a single long URL cannot push every other column off
    /// the far side. The cap is a share of the page, not a fixed number, so it
    /// scales with the window the way Obsidian's does.
    fn scroll_widths(&self, natural: &[usize]) -> Vec<usize> {
        /// Narrowest a column is ever capped to, and the share of the page a
        /// single column may claim before it starts wrapping.
        const FLOOR: usize = 12;
        let cap = (self.width / 3).clamp(FLOOR, 44);
        natural.iter().map(|w| (*w).min(cap).max(1)).collect()
    }

    /// Aligned columns with a light rule under the head. `wrap` lets a cell
    /// that does not fit run onto further lines instead of being cut.
    fn emit_grid(&mut self, t: &Table, cols: usize, widths: &[usize], wrap: bool, wide: bool) {
        let src_line = self.src_line;
        // a rule between body rows only earns its keep once rows are taller
        // than one line, where without it the eye loses which row it is on
        let mut ruled = false;
        for (ri, row) in t.rows.iter().enumerate() {
            let empty: Vec<PCell> = Vec::new();
            // every cell, already broken into the lines it will occupy
            let parts: Vec<Vec<Vec<PCell>>> = (0..cols)
                .map(|ci| {
                    let cell = row.get(ci).unwrap_or(&empty);
                    let w = widths.get(ci).copied().unwrap_or(0);
                    if wrap {
                        wrap_pcells(cell, w.max(1))
                    } else {
                        vec![truncate_cells(cell, w)]
                    }
                })
                .collect();
            let height = parts.iter().map(|p| p.len()).max().unwrap_or(1);
            if height > 1 {
                ruled = true;
            }
            for line in 0..height {
                let mut cells: Vec<PCell> = Vec::new();
                for (ci, w) in widths.iter().enumerate().take(cols) {
                    if ci > 0 {
                        cells.extend(str_cells(crate::md::COL_SEP, theme::marker()));
                    }
                    let blank: Vec<PCell> = Vec::new();
                    let part = parts[ci].get(line).unwrap_or(&blank);
                    let align = align_of(t.aligns.get(ci).copied().unwrap_or(Alignment::None));
                    let (left, right) = crate::md::pad_for(cells_width(part), *w, align);
                    cells.extend(str_cells(&" ".repeat(left), theme::PLAIN));
                    cells.extend(part.iter().cloned());
                    cells.extend(str_cells(&" ".repeat(right), theme::PLAIN));
                }
                self.emit_line(PLine {
                    cells,
                    checkbox: None,
                    image: None,
                    src_line,
                    wide,
                });
            }
            // under the head always; between wrapped body rows as well
            let last = ri + 1 == t.rows.len();
            if ri == 0 || (ruled && !last) {
                let rule = crate::md::table_rule(widths);
                self.emit_line(PLine {
                    cells: str_cells(&rule, theme::marker()),
                    checkbox: None,
                    image: None,
                    src_line,
                    wide,
                });
            }
        }
    }

    /// One block per row: the row's first cells as a heading, then every other
    /// column as `label  value` under it. Nothing is truncated, so a table
    /// twenty columns wide is still readable on an eighty-column terminal —
    /// it is simply taller.
    fn emit_cards(&mut self, t: &Table, cols: usize) {
        let src_line = self.src_line;
        let empty: Vec<PCell> = Vec::new();
        let head: Vec<String> = (0..cols)
            .map(|ci| {
                t.rows
                    .first()
                    .and_then(|r| r.get(ci))
                    .map(|c| c.iter().map(|p| p.ch).collect::<String>())
                    .unwrap_or_default()
                    .trim()
                    .to_string()
            })
            .collect();
        // the label column is as wide as the widest heading, so the values
        // line up down the whole table and can be read as a column
        let labelw = head
            .iter()
            .skip(1)
            .map(|h| crate::md::str_width(h))
            .max()
            .unwrap_or(0);

        let mut made: Vec<Vec<PCell>> = Vec::new();
        let push = |cells: Vec<PCell>, made: &mut Vec<Vec<PCell>>| made.push(cells);

        for (ri, row) in t.rows.iter().enumerate().skip(1) {
            if ri > 1 {
                push(Vec::new(), &mut made);
            }
            // the heading: the first column, which is nearly always the row's
            // name or date, marked with the same bar a blockquote uses
            let mut title = str_cells(&format!("{} ", crate::md::theme::QUOTE_BAR), theme::state());
            let first = truncate_cells(row.first().unwrap_or(&empty), self.width.saturating_sub(2));
            title.extend(first.iter().map(|c| {
                let mut c = c.clone();
                c.style = c.style.patch(theme::heading(3)).fg(theme::palette().accent);
                c
            }));
            push(title, &mut made);

            for ci in 1..cols {
                let value = row.get(ci).unwrap_or(&empty);
                // an empty cell says nothing worth a line of its own
                if value.iter().all(|c| c.ch.is_whitespace()) {
                    continue;
                }
                let label = head.get(ci).cloned().unwrap_or_default();
                let pad = labelw.saturating_sub(crate::md::str_width(&label));
                let indent = 2 + labelw + 2;
                let avail = self.width.saturating_sub(indent).max(8);
                for (i, part) in wrap_pcells(value, avail).into_iter().enumerate() {
                    let mut cells = if i == 0 {
                        let mut c = str_cells("  ", theme::PLAIN);
                        c.extend(str_cells(&label, theme::marker()));
                        c.extend(str_cells(&" ".repeat(pad + 2), theme::PLAIN));
                        c
                    } else {
                        // continuation lines hang under the value, not the label
                        str_cells(&" ".repeat(indent), theme::PLAIN)
                    };
                    cells.extend(part);
                    push(cells, &mut made);
                }
            }
        }
        for cells in made {
            self.emit_line(PLine {
                cells,
                checkbox: None,
                image: None,
                src_line,
                wide: false,
            });
        }
    }

    fn finish(mut self) -> Rendered {
        self.flush();
        self.out
    }
}

/// The three ways a table can be laid out, once `auto` has made up its mind.
enum Shape {
    Grid {
        wrap: bool,
    },
    /// Natural column widths, capped so no one column runs away with the
    /// table, and the page pans across whatever that adds up to.
    Scroll,
    Cards,
}

/// Word-wrap a run of rendered cells into rows no wider than `width` display
/// columns. Shared by the preview's own soft wrap and by table cells, so a
/// wrapped cell breaks where a wrapped paragraph would.
pub fn wrap_pcells(cells: &[PCell], width: usize) -> Vec<Vec<PCell>> {
    if width == 0 || cells_width(cells) <= width {
        return vec![cells.to_vec()];
    }
    let chars: Vec<char> = cells.iter().map(|c| c.ch).collect();
    crate::md::wrap_breaks(&chars, width, width)
        .into_iter()
        .map(|(s, e)| cells[s..e].to_vec())
        .collect()
}

/// Word-wrap like [`wrap_pcells`], but with `first` columns for the first row
/// and `rest` for every row after it — the room a hanging indent leaves.
fn wrap_hang(cells: &[PCell], first: usize, rest: usize) -> Vec<Vec<PCell>> {
    if cells_width(cells) <= first {
        return vec![cells.to_vec()];
    }
    let chars: Vec<char> = cells.iter().map(|c| c.ch).collect();
    crate::md::wrap_breaks(&chars, first, rest)
        .into_iter()
        .map(|(s, e)| cells[s..e].to_vec())
        .collect()
}

/// The Obsidian callout a blockquote starting at byte `start` opens with, if
/// any: `> [!type] Title` (a `-`/`+` fold marker after the type is ignored).
/// Returns (type, title, byte offset of the line ending), the offset so the
/// caller can skip everything the parser hands back from that line.
fn callout_at(src: &str, start: usize) -> Option<(String, String, usize)> {
    let rest = src.get(start..)?;
    let line_end = rest.find('\n').map_or(rest.len(), |i| i + 1);
    let line = &rest[..line_end];
    let body = line.trim_start_matches(|c: char| c == '>' || c == ' ' || c == '\t');
    let inner = body.strip_prefix("[!")?;
    let close = inner.find(']')?;
    let kind = inner[..close].trim();
    if kind.is_empty() || kind.chars().any(|c| c.is_whitespace()) {
        return None;
    }
    let after = inner[close + 1..].trim_start_matches(['-', '+']);
    let title = after.trim().to_string();
    Some((kind.to_lowercase(), title, start + line_end))
}

/// The glyph a callout type is drawn with in its title row.
fn callout_glyph(kind: &str) -> Option<char> {
    match kind {
        "summary" | "abstract" | "tldr" => Some(''),
        "note" | "info" => Some('i'),
        "tip" | "hint" => Some(''),
        "warning" | "caution" => Some('!'),
        "danger" | "error" | "bug" => Some(''),
        "question" | "help" => Some('?'),
        "example" => Some(''),
        "quote" => Some(''),
        _ => None,
    }
}

/// pulldown's alignment in the shared vocabulary.
fn align_of(a: Alignment) -> crate::md::Align {
    match a {
        Alignment::Right => crate::md::Align::Right,
        Alignment::Center => crate::md::Align::Center,
        _ => crate::md::Align::Left,
    }
}

fn str_cells(s: &str, style: Style) -> Vec<PCell> {
    s.chars()
        .map(|ch| PCell {
            ch,
            style,
            link: None,
            src: None,
        })
        .collect()
}

/// A cell run cut to `width` columns, ellipsis included when it was cut.
fn truncate_cells(cells: &[PCell], width: usize) -> Vec<PCell> {
    if cells_width(cells) <= width {
        return cells.to_vec();
    }
    let mut out: Vec<PCell> = Vec::new();
    let mut used = 0;
    for c in cells {
        let cw = crate::md::char_width(c.ch);
        if used + cw > width.saturating_sub(1) {
            break;
        }
        out.push(c.clone());
        used += cw;
    }
    let style = out.last().map(|c| c.style).unwrap_or(theme::PLAIN);
    out.push(PCell {
        ch: '',
        style,
        link: None,
        src: None,
    });
    out
}

/// Display width of a run of cells, in terminal columns.
pub fn cells_width(cells: &[PCell]) -> usize {
    cells.iter().map(|c| crate::md::char_width(c.ch)).sum()
}

/// Does this event put something on the page at a source offset of its own?
///
/// Only these can be dropped inside a span that has already been drawn.
/// Structural events are deliberately not in the list: their ranges cover the
/// whole construct they open, so skipping one that happens to start inside a
/// wikilink would leave the style stack unbalanced for the rest of the page.
fn emits_cells(event: &Event<'_>) -> bool {
    matches!(
        event,
        Event::Text(_)
            | Event::Code(_)
            | Event::Html(_)
            | Event::InlineHtml(_)
            | Event::InlineMath(_)
            | Event::DisplayMath(_)
            | Event::FootnoteReference(_)
    )
}

fn starts_url(chars: &[char], i: usize) -> bool {
    let rest: String = chars[i..].iter().take(8).collect();
    (rest.starts_with("http://") || rest.starts_with("https://"))
        && (i == 0 || !chars[i - 1].is_alphanumeric())
}

fn find_pair(chars: &[char], from: usize) -> Option<usize> {
    (from..chars.len().saturating_sub(1)).find(|&k| chars[k] == '=' && chars[k + 1] == '=')
}

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

    fn flat(r: &Rendered) -> String {
        r.lines
            .iter()
            .map(|l| l.text())
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn renders_without_panic() {
        let md = "# Title\n\nSome **bold** and *italic* and `code`.\n\n- one\n- [ ] task\n- [x] done\n\n> quote\n\n```\nlet x = 1;\n```\n\n---\n";
        let r = render(md);
        assert!(r.lines.len() > 5);
        let flat = flat(&r);
        assert!(flat.contains("Title"));
        assert!(flat.contains("bold"));
        assert!(flat.contains("let x = 1;"));
    }

    #[test]
    fn code_block_offsets_survive_crlf() {
        for md in [
            "# T\n\n```\nlet x = 1;\nlet y = 2;\n```\n\ntail\n",
            "# T\r\n\r\n```\r\nlet x = 1;\r\nlet y = 2;\r\n```\r\n\r\ntail\r\n",
        ] {
            let src_lines: Vec<&str> = md.lines().collect();
            for line in &render(md).lines {
                for c in &line.cells {
                    // every mapped cell points at its own character
                    if let Some((l, col)) = c.src {
                        let at = src_lines[l].chars().nth(col);
                        assert_eq!(at, Some(c.ch), "{md:?} at ({l},{col})");
                    }
                }
            }
        }
    }

    const WIDE: &str = "| a | bbbbbbbbbbbbbbbbbbbb |\n| --- | --- |\n| 1 | 2 |\n";

    /// The table this whole feature exists for: eight columns of real content.
    const JOB_LOG: &str = concat!(
        "| date | company | title | comp | location | path | doc | status |\n",
        "|---|---|---|---|---|---|---|---|\n",
        "| 2026-08-25 | Harrison Consulting | Director of Product | $220K/yr | ",
        "Seattle, WA | LinkedIn Easy Apply | doc | applied |\n",
    );

    #[test]
    fn a_wide_table_is_squeezed_into_the_page_width() {
        let r = render_page(WIDE, 16, TableStyle::Fit);
        for l in &r.lines {
            assert!(cells_width(&l.cells) <= 16);
        }
        let head: String = r.lines[0].cells.iter().map(|c| c.ch).collect();
        assert_eq!(head, "a │ bbbbbbbbbbb…");
    }

    #[test]
    fn a_line_is_either_inside_the_page_or_marked_wide() {
        // the whole contract in one assertion: a shape either fits the page,
        // or says it does not so the view pans across it instead of wrapping
        for width in [24usize, 40, 80, 100] {
            for style in [
                TableStyle::Auto,
                TableStyle::Scroll,
                TableStyle::Wrap,
                TableStyle::Cards,
            ] {
                for l in &render_page(JOB_LOG, width, style).lines {
                    assert!(
                        l.wide || cells_width(&l.cells) <= width,
                        "{style:?} at {width}: {:?}",
                        l.text()
                    );
                }
            }
        }
    }

    #[test]
    fn a_scrolling_table_keeps_its_columns_and_cuts_nothing() {
        let r = render_page(JOB_LOG, 60, TableStyle::Scroll);
        let table: Vec<&PLine> = r.lines.iter().filter(|l| l.wide).collect();
        assert!(!table.is_empty());
        let text: String = table.iter().map(|l| l.text()).collect();
        // no column was shaved down to an ellipsis
        assert!(!text.contains(''), "{text}");
        // and the words are whole, not broken across a nine-column cell
        assert!(text.contains("Harrison"), "{text}");
        assert!(text.contains("applied"), "{text}");
        // the table is genuinely wider than the page — that is the point
        assert!(table.iter().any(|l| cells_width(&l.cells) > 60));
        // every row of it is the same width, so the columns line up while it pans
        let widths: Vec<usize> = table.iter().map(|l| cells_width(&l.cells)).collect();
        assert!(widths.windows(2).all(|w| w[0] == w[1]), "{widths:?}");
    }

    #[test]
    fn one_runaway_column_cannot_push_the_others_off_the_far_side() {
        let md = concat!(
            "| a | b |\n|---|---|\n",
            "| short | https://example.com/an/extremely/long/url/that/goes/on/and/on/forever |\n",
        );
        let r = render_page(md, 60, TableStyle::Scroll);
        // capped at a third of the page, so the long cell wraps rather than
        // making the table hundreds of columns wide
        for l in r.lines.iter().filter(|l| l.wide) {
            assert!(cells_width(&l.cells) <= 60 + 60 / 3, "{:?}", l.text());
        }
    }

    #[test]
    fn wrapping_keeps_every_word_a_squeezed_grid_would_have_cut() {
        let r = render_page(WIDE, 16, TableStyle::Wrap);
        let text: String = r.lines.iter().map(|l| l.text()).collect();
        assert!(text.contains("bbbbbbbb"), "{text:?}");
        // nothing was cut, so no ellipsis was needed
        assert!(!text.contains(''), "{text:?}");
    }

    #[test]
    fn cards_label_every_value_and_truncate_nothing() {
        let md = concat!(
            "| date | company | status |\n|---|---|---|\n",
            "| 2026-08-25 | Harrison Consulting | applied |\n",
        );
        let r = render_page(md, 30, TableStyle::Cards);
        let text: String = r.lines.iter().map(|l| format!("{}\n", l.text())).collect();
        // the first column heads the block; the rest are labelled under it
        assert!(text.contains("2026-08-25"), "{text}");
        assert!(text.contains("company"), "{text}");
        assert!(text.contains("Harrison Consulting"), "{text}");
        assert!(text.contains("status"), "{text}");
        assert!(text.contains("applied"), "{text}");
        // the header row is the labels, never a card of its own
        assert!(!text.contains("▌ date"), "{text}");
        assert!(!text.contains(''), "{text}");
    }

    #[test]
    fn auto_leaves_a_table_that_fits_alone_and_scrolls_one_that_does_not() {
        // two roomy columns: still a grid, with the head rule under it
        let narrow = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        let grid: String = render_page(narrow, 80, TableStyle::Auto)
            .lines
            .iter()
            .map(|l| format!("{}\n", l.text()))
            .collect();
        assert!(grid.contains(''), "{grid}");
        assert!(!grid.contains(''), "{grid}");

        // one that does not fit keeps its columns and pans instead
        let r = render_page(JOB_LOG, 60, TableStyle::Auto);
        assert!(r.lines.iter().any(|l| l.wide));
        let text: String = r.lines.iter().map(|l| l.text()).collect();
        assert!(!text.contains(''), "{text}");
    }

    #[test]
    fn tables_get_aligned_columns_and_a_head_rule() {
        let md = "| a | bbbb |\n| --- | ---: |\n| 1 | 2 |\n";
        let r = render(md);
        let rows: Vec<String> = r
            .lines
            .iter()
            .map(|l| l.text())
            .filter(|t| !t.trim().is_empty())
            .collect();
        assert_eq!(rows[0], "a │ bbbb");
        assert_eq!(rows[1], "──┼─────");
        assert_eq!(rows[2], "1 │    2"); // right aligned
                                         // the header is bold
        assert!(r.lines[0].cells[0]
            .style
            .add_modifier
            .contains(Modifier::BOLD));
    }

    #[test]
    fn table_columns_are_measured_in_display_columns() {
        let r = render("| 漢字 | b |\n| --- | --- |\n| x | y |\n");
        let rows: Vec<&PLine> = r
            .lines
            .iter()
            .filter(|l| !l.text().trim().is_empty())
            .collect();
        let widths: Vec<usize> = rows.iter().map(|l| cells_width(&l.cells)).collect();
        // every row, rule included, lines up at the same width
        assert!(widths.windows(2).all(|w| w[0] == w[1]), "{widths:?}");
    }

    #[test]
    fn every_quoted_line_gets_its_bar() {
        // the first line of a quote needs the bar as much as its continuations
        let r = render("> first line\n> second line\n\nafter\n");
        let quoted: Vec<String> = r
            .lines
            .iter()
            .map(|l| l.text())
            .filter(|t| t.contains("line"))
            .collect();
        assert_eq!(quoted, vec!["▌ first line", "▌ second line"]);
        // text outside the quote keeps its bar off
        assert!(r.lines.iter().any(|l| l.text() == "after"));
    }

    #[test]
    fn the_rail_runs_down_blank_and_wrapped_rows_alike() {
        let md = "> one two three four five six seven eight nine ten\n>\n> - alpha beta gamma delta epsilon zeta eta\n\nafter\n";
        let r = render_wide(md, 24);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let quoted: Vec<&String> = rows.iter().filter(|t| t.starts_with("")).collect();
        // one paragraph and one bullet, each wrapped, with a blank row between
        assert!(quoted.len() >= 5, "{rows:?}");
        assert!(quoted.iter().any(|t| t.trim() == ""), "blank row keeps its bar: {rows:?}");
        for t in &quoted {
            assert!(crate::md::str_width(t) <= 24, "{t:?}");
        }
        // the wrapped bullet hangs under its text, not under the bullet
        let bullet = rows.iter().position(|t| t.contains("• alpha")).unwrap();
        assert!(rows[bullet + 1].starts_with(""), "{:?}", rows[bullet + 1]);
        // nothing after the quote carries a bar, and the quote body is not dim
        assert!(rows.iter().any(|t| t == "after"));
        let body = r.lines.iter().find(|l| l.text().contains("one two")).unwrap();
        let word = body.cells.iter().find(|c| c.ch == 'o').unwrap();
        assert_eq!(word.style, Style::default());
    }

    #[test]
    fn a_callout_becomes_a_box_the_width_of_the_page() {
        let md = "> [!summary] TL;DR\n> **Situation:**\n>\n> - At Airstream, during the MY22 launch, the connected vehicle platform.\n\nafter\n";
        let w = 40;
        let r = render_wide(md, w);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let top = rows.iter().find(|t| t.starts_with('')).expect("top edge");
        let bottom = rows.iter().find(|t| t.starts_with('')).expect("bottom edge");
        assert_eq!(crate::md::str_width(top), w, "{top:?}");
        assert_eq!(crate::md::str_width(bottom), w, "{bottom:?}");
        assert!(top.ends_with('') && bottom.ends_with(''));
        assert!(top.contains("≡ summary · TL;DR"), "{top:?}");
        let ti = rows.iter().position(|t| t.starts_with('')).unwrap();
        let bi = rows.iter().position(|t| t.starts_with('')).unwrap();
        assert!(bi > ti + 2);
        for t in &rows[ti + 1..bi] {
            assert!(t.starts_with('') && t.ends_with(''), "{t:?}");
            assert_eq!(crate::md::str_width(t), w, "{t:?}");
        }
        assert!(rows.iter().all(|t| !t.contains("[!summary]")), "{rows:?}");
        assert!(rows.iter().any(|t| t.contains("Situation:")));
        // the bullet wrapped inside the box, and blank quoted rows are bare box rows
        assert!(rows[ti + 1..bi].iter().any(|t| t.trim_matches(|c| c == '' || c == ' ').is_empty()));
        assert!(rows[ti + 1..bi].iter().filter(|t| t.contains("Airstream") || t.contains("platform")).count() >= 2);
        // text in the box still knows its source line
        let sit = r.lines.iter().find(|l| l.text().contains("Situation")).unwrap();
        assert_eq!(sit.cells.iter().find(|c| c.ch == 'S').unwrap().src, Some((1, 4)));
        assert!(rows.iter().any(|t| t == "after"));
    }

    #[test]
    fn a_callout_without_a_title_and_with_a_fold_marker_still_boxes() {
        let r = render_wide("> [!tip]- \n> body\n", 30);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let top = rows.iter().find(|t| t.starts_with('')).unwrap();
        assert!(top.contains("✓ tip ─"), "{top:?}");
        assert!(!top.contains('·'));
        assert!(rows.iter().any(|t| t.starts_with("│ body")));
    }

    #[test]
    fn highlight_gets_the_highlight_style() {
        let r = render("a ==wow== b");
        let line = r.lines.iter().find(|l| l.text().contains("wow")).unwrap();
        assert_eq!(line.text(), "a wow b");
        let cell = line.cells.iter().find(|c| c.ch == 'w').unwrap();
        assert_eq!(cell.style.bg, theme::highlight().bg);
    }

    #[test]
    fn checkboxes_render_and_remember_their_source_line() {
        let r = render("# t\n\n- [ ] todo\n- [x] done\n");
        let todo = r.lines.iter().find(|l| l.text().contains("todo")).unwrap();
        assert_eq!(todo.text(), "☐ todo");
        assert_eq!(todo.checkbox, Some(2));
        let done = r.lines.iter().find(|l| l.text().contains("done")).unwrap();
        assert_eq!(done.text(), "✓ done");
        assert_eq!(done.checkbox, Some(3));
        assert!(done.cells[0].style.fg == theme::done().fg);
    }

    /// What the reading view hands the renderer: the body, and the line it
    /// starts on, with the front matter already cut away.
    fn body_of(content: &str) -> Rendered {
        let (skip, first) = crate::notes::front_matter_range(content)
            .map_or((0, 0), |r| (r.end, content[..r.end].lines().count()));
        render_page_at(&content[skip..], first, usize::MAX, TableStyle::default())
    }

    #[test]
    fn a_page_rendered_from_a_slice_still_reports_file_line_numbers() {
        let r = render_page_at("# Title\n\nprose\n", 4, usize::MAX, TableStyle::default());
        let title = r.lines.iter().find(|l| l.text().contains("Title")).unwrap();
        assert_eq!(title.src_line, Some(4));
        assert_eq!(title.cells[0].src, Some((4, 2)));
        let prose = r.lines.iter().find(|l| l.text().contains("prose")).unwrap();
        assert_eq!(prose.src_line, Some(6));
        assert_eq!(prose.cells[0].src, Some((6, 0)));
    }

    #[test]
    fn the_reading_view_renders_the_body_and_never_the_front_matter() {
        let r = body_of("---\ntype: log\ntags: work\n---\n\n# Title\n\nprose\n");
        let page: String = r
            .lines
            .iter()
            .map(|l| l.text())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(!page.contains("type: log"));
        assert!(!page.contains("tags"));
        assert!(!page.contains("---"));
        assert!(page.contains("Title"));
        assert!(page.contains("prose"));
        // a note without front matter is unchanged, offset and all
        let plain = body_of("# Title\n");
        assert_eq!(plain.lines[0].src_line, Some(0));
    }

    #[test]
    fn a_checkbox_under_front_matter_still_maps_to_its_own_source_line() {
        // the number the toggle indexes the buffer with, so an off-by-N here
        // would silently tick the wrong box
        let r = body_of("---\ntype: log\n---\n\n- [ ] todo\n- [x] done\n");
        let todo = r.lines.iter().find(|l| l.text().contains("todo")).unwrap();
        assert_eq!(todo.checkbox, Some(4));
        let done = r.lines.iter().find(|l| l.text().contains("done")).unwrap();
        assert_eq!(done.checkbox, Some(5));
        // and a click on the word lands inside it, not at the line's start
        assert_eq!(done.cells[2].src, Some((5, 6)));
    }

    #[test]
    fn links_and_bare_urls_are_recorded() {
        let r = render("see [docs](http://x.y) and https://z.example/p now");
        let line = r.lines.iter().find(|l| l.text().contains("docs")).unwrap();
        let docs = line.cells.iter().find(|c| c.ch == 'd').unwrap();
        assert_eq!(r.url(docs.link.unwrap()), Some("http://x.y"));
        let bare = line
            .cells
            .iter()
            .find(|c| c.link.map(|i| r.urls[i].starts_with("https://z")) == Some(true))
            .unwrap();
        assert_eq!(r.url(bare.link.unwrap()), Some("https://z.example/p"));
        assert!(line.text().contains("https://z.example/p"));
    }

    #[test]
    fn a_wikilink_renders_as_its_text_and_records_a_wikilink_target() {
        let r = render("see [[note]] now\n");
        assert_eq!(flat(&r).trim(), "see note now");
        let cell = r.lines[0].cells.iter().find(|c| c.link.is_some()).unwrap();
        assert_eq!(r.url(cell.link.unwrap()), Some("wikilink:note"));
        // a piped one shows only its label, and the target loses the heading
        let r = render("[[stories/story-matrix#Method|the matrix]]\n");
        assert_eq!(flat(&r).trim(), "the matrix");
        assert_eq!(r.url(0), Some("wikilink:stories/story-matrix"));
    }

    #[test]
    fn brackets_pulldown_hands_back_one_at_a_time_are_not_drawn_twice() {
        // pulldown gives `[`, `[`, `note`, `]`, `]` as five separate text
        // events; without the watermark the closing pair is drawn after the
        // label and the line reads "note]]"
        let r = render("see [[note]] and [[a|b]] here\n");
        let text = flat(&r);
        assert_eq!(text.trim(), "see note and b here");
        assert!(!text.contains(']'), "{text}");
        assert_eq!(text.matches("here").count(), 1);
    }

    #[test]
    fn nothing_else_pulldown_finds_inside_a_wikilink_is_drawn_after_it_either() {
        // `md::wikilink_at` lets a backtick sit inside a target — it bails on
        // `[`, `]` and a newline, and on nothing else — so the live editor
        // draws this whole label. pulldown, which knows nothing of wikilinks,
        // sees inline code in the middle of it and hands back a `Code` event
        // for the `b`; drawn, it would be a second `b` after the label and the
        // two views would disagree about one line
        let r = render("[[a `b` c]] tail\n");
        assert_eq!(flat(&r).trim(), "a `b` c tail");
    }

    #[test]
    fn a_href_in_the_note_can_never_claim_the_scheme_the_app_uses_for_a_file() {
        // the footer's own rows name a file by path; a note body saying the
        // same words is a stranger's text and must reach the desktop opener
        // instead of `App::open_path`
        let r = render("[report](note:/etc/passwd)\n");
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(0).unwrap()),
            crate::md::LinkTarget::Url("note:/etc/passwd".to_string())
        );
        let r = render("<https://x.y/a>\n");
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(0).unwrap()),
            crate::md::LinkTarget::Url("https://x.y/a".to_string())
        );
    }

    #[test]
    fn a_wikilink_in_a_table_cell_is_still_a_link() {
        let r = render_wide("| a | b |\n| - | - |\n| [[note]] | x |\n", 40);
        let row = r
            .lines
            .iter()
            .find(|l| l.text().contains("note"))
            .expect("the cell is drawn");
        assert!(row.cells.iter().any(|c| c.link.is_some()));
        // the column is measured from the label, not from the source: the
        // brackets are gone, so nothing pads out to their width
        assert!(!row.text().contains("[["), "{}", row.text());
        assert_eq!(r.urls.iter().filter(|u| *u == "wikilink:note").count(), 1);
    }

    #[test]
    fn a_wikilink_in_a_list_item_is_still_a_link() {
        let r = render("- see [[note]]\n- and [[other]]\n");
        let linked: Vec<String> = r
            .lines
            .iter()
            .filter(|l| l.cells.iter().any(|c| c.link.is_some()))
            .map(|l| l.text())
            .collect();
        assert_eq!(linked.len(), 2, "{linked:?}");
        assert_eq!(r.urls, vec!["wikilink:note", "wikilink:other"]);
    }

    #[test]
    fn an_escaped_or_embedded_wikilink_is_left_as_text() {
        let r = render("\\[[x]] and ![[y.png]]\n");
        let text = flat(&r);
        assert!(text.contains("[[x]]"), "{text}");
        assert!(text.contains("[[y.png]]"), "{text}");
        assert!(r.urls.is_empty(), "{:?}", r.urls);
    }

    #[test]
    fn a_wikilink_cell_remembers_the_source_column_of_its_label() {
        // preview click → edit indexes the buffer with this, so the first
        // label cell has to be the label's own column, not the bracket's
        let r = render("see [[note|label]] now\n");
        let cell = r.lines[0].cells.iter().find(|c| c.link.is_some()).unwrap();
        assert_eq!(cell.ch, 'l');
        assert_eq!(cell.src, Some((0, "see [[note|".len())));
    }

    #[test]
    fn images_become_their_own_line() {
        let r = render("![a cat](cat.png)\n");
        let line = r.lines.iter().find(|l| l.image.is_some()).unwrap();
        assert_eq!(line.text(), "🖼 a cat (cat.png)");
        assert_eq!(
            r.images[line.image.unwrap()],
            ImageSpec {
                alt: "a cat".into(),
                url: "cat.png".into()
            }
        );
    }

    fn mention(name: &str, excerpt: &str, count: usize) -> crate::mentions::Mention {
        // the link span is whatever the scan would have recorded for the
        // first wikilink; an excerpt without one has an empty span
        let link = crate::md::wikilinks(excerpt)
            .first()
            .map(|w| (w.start, w.end))
            .unwrap_or((0, 0));
        crate::mentions::Mention {
            path: std::path::PathBuf::from(format!("/vault/{name}.md")),
            name: name.to_string(),
            excerpt: excerpt.to_string(),
            link,
            count,
        }
    }

    fn footer_row<'a>(r: &'a Rendered, name: &str) -> &'a PLine {
        r.lines
            .iter()
            .find(|l| l.text().starts_with(&format!("  {name}")))
            .unwrap()
    }

    #[test]
    fn no_mentions_means_no_footer_line_at_all() {
        let mut r = render("# Spec\n\nbody\n");
        let before = r.lines.len();
        append_mentions(&mut r, &[], 60);
        // not even a rule, and certainly not "0 notes link here"
        assert_eq!(r.lines.len(), before);
        assert!(!r.lines.iter().any(|l| l.text().contains("link here")));
    }

    #[test]
    fn the_footer_names_each_note_once_and_counts_the_rest() {
        let mut r = render("# Spec\n");
        append_mentions(
            &mut r,
            &[
                mention("meta-os-control", "…see [[spec]] for the", 3),
                mention("ford-mvp", "…pulled from [[spec]]", 1),
            ],
            60,
        );
        let text: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(text.iter().any(|t| t == "2 notes link here"));
        let first = text.iter().find(|t| t.contains("meta-os-control")).unwrap();
        assert!(first.contains("…see spec for the"));
        // several mentions in one note are one row, with the count beside it
        assert!(first.ends_with(" ×3"));
        let second = text.iter().find(|t| t.contains("ford-mvp")).unwrap();
        assert!(!second.contains('×'));
        // one note reads as one note
        let mut one = render("# Spec\n");
        append_mentions(&mut one, &[mention("meta", "x", 1)], 60);
        assert!(one.lines.iter().any(|l| l.text() == "1 note links here"));
    }

    #[test]
    fn every_footer_row_is_a_link_to_the_note_that_mentions_this_one() {
        let mut r = render("# Spec\n");
        append_mentions(&mut r, &[mention("meta", "about [[spec]]", 1)], 60);
        let row = r.lines.iter().find(|l| l.text().contains("meta")).unwrap();
        let link = row.cells.iter().find(|c| c.ch == 'm').unwrap().link.unwrap();
        // an exact file, so the click cannot land on another note of the same
        // name, and never a url the desktop would be handed
        assert_eq!(r.url(link), Some("note:/vault/meta.md"));
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(link).unwrap()),
            crate::md::LinkTarget::Note("/vault/meta.md".to_string())
        );
        // the excerpt is not part of the link
        assert!(row
            .cells
            .iter()
            .filter(|c| c.link.is_some())
            .all(|c| "meta".contains(c.ch)));
    }

    #[test]
    fn a_footer_row_carries_no_source_position_so_a_click_cannot_land_in_the_note() {
        let mut r = render("# Spec\n");
        let before = r.lines.len();
        append_mentions(&mut r, &[mention("meta", "about [[spec]]", 1)], 60);
        for line in &r.lines[before..] {
            assert_eq!(line.src_line, None);
            assert_eq!(line.checkbox, None);
            assert!(!line.wide);
            assert!(line.cells.iter().all(|c| c.src.is_none()));
        }
    }

    #[test]
    fn the_footer_never_makes_a_page_wider_than_the_page() {
        let mut r = render_wide("# Spec\n", 30);
        append_mentions(
            &mut r,
            &[mention(
                "a-note-with-a-very-long-name-indeed",
                "a sentence far longer than the page could ever hold, on and on",
                12,
            )],
            30,
        );
        assert!(r.lines.iter().all(|l| cells_width(&l.cells) <= 30));
    }

    #[test]
    fn the_footer_names_a_note_by_its_file_not_its_first_line() {
        let mut r = render("# Spec\n");
        let mut m = mention("meta-os-control", "about [[spec]]", 1);
        m.path = std::path::PathBuf::from("/vault/deep/meta-os-control.md");
        append_mentions(&mut r, &[m], 60);
        let row = footer_row(&r, "meta-os-control");
        let name: String = row
            .cells
            .iter()
            .filter(|c| c.link.is_some())
            .map(|c| c.ch)
            .collect();
        assert_eq!(name, "meta-os-control");
        assert!(row.cells.iter().filter(|c| c.link.is_some()).all(|c| c.style == theme::link()));
    }

    #[test]
    fn the_excerpt_is_styled_rather_than_shown_as_raw_markdown() {
        let mut r = render("# Spec\n");
        append_mentions(
            &mut r,
            &[mention("meta", "**Projects:** [[spec|the spec]] and `code`", 1)],
            80,
        );
        let row = footer_row(&r, "meta");
        let text = row.text();
        assert!(!text.contains("**"), "{text}");
        assert!(!text.contains("[["), "{text}");
        assert!(!text.contains('`'), "{text}");
        assert!(text.contains("Projects: the spec and code"), "{text}");
        // bold is bold, and the link reads as a link
        let p = row.cells.iter().find(|c| c.ch == 'P').unwrap();
        assert!(p.style.add_modifier.contains(Modifier::BOLD));
        let t = row.cells.iter().find(|c| c.ch == 't').unwrap();
        assert!(t.style.add_modifier.contains(Modifier::UNDERLINED));
        // and nothing in the excerpt maps back into the note
        assert!(row.cells.iter().all(|c| c.src.is_none()));
    }

    #[test]
    fn a_long_excerpt_is_cut_around_the_link_so_the_link_stays_on_screen() {
        let mut r = render("# Spec\n");
        let before = "word ".repeat(30);
        let after = " tail".repeat(30);
        let excerpt = format!("{before}[[spec]]{after}");
        append_mentions(&mut r, &[mention("meta", &excerpt, 1)], 60);
        let row = footer_row(&r, "meta");
        let text = row.text();
        assert!(text.contains("spec"), "{text}");
        // the window opens with an ellipsis, right after the name column
        assert!(text.starts_with("  meta  …"), "{text}");
        assert!(cells_width(&row.cells) <= 60);
        // and one that fits from the start is not moved
        let mut r = render("# Spec\n");
        let excerpt = format!("[[spec]]{after}");
        append_mentions(&mut r, &[mention("meta", &excerpt, 1)], 60);
        assert!(footer_row(&r, "meta").text().contains("  spec tail"));
    }

    #[test]
    fn a_narrow_page_keeps_the_titles_and_drops_the_excerpts() {
        let mut r = render_wide("# Spec\n", 18);
        append_mentions(&mut r, &[mention("meta", "about the spec", 1)], 18);
        let row = r.lines.iter().find(|l| l.text().contains("meta")).unwrap();
        assert!(!row.text().contains("about"));
    }
}