catcher 0.18.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
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
//! 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::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::theme;
use pulldown_cmark::{Alignment, CodeBlockKind, 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,
    /// Obsidian's `|300`: the width to draw at, in pixels.
    pub width: Option<u32>,
}

/// 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,
    /// Columns the rows this line wraps into after the first are indented
    /// by, so a list item's continuation sits under its text, not its marker.
    pub hang: usize,
}

/// Wrap a page line to `width`, honouring its hanging indent: every row after
/// the first is pushed in under the text the first row began with.
pub fn wrap_pline(line: &PLine, width: usize) -> Vec<Vec<PCell>> {
    let width = width.max(1);
    if line.hang == 0 {
        return wrap_pcells(&line.cells, width);
    }
    let rest = width.saturating_sub(line.hang).max(4);
    wrap_hang(&line.cells, width, rest)
        .into_iter()
        .enumerate()
        .map(|(i, row)| {
            if i == 0 {
                row
            } else {
                let mut cells = str_cells(&" ".repeat(line.hang), theme::PLAIN);
                cells.extend(row);
                cells
            }
        })
        .collect()
}

/// 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 {
    #[cfg(test)]
    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
        | Options::ENABLE_MATH
        | Options::ENABLE_FOOTNOTES
}

/// 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 {
    // block ids are addresses for links, not words for the page: blanked
    // rather than cut, so every byte offset pulldown reports still points at
    // the same place in the file the reader is looking at
    let markdown = &blank_block_ids(markdown);
    let mut r = Ren::new(markdown, first_line, width, tables);
    // `%% comments %%` are not part of the page: pulldown-cmark never sees
    // them, and every offset it reports is mapped back through the cuts
    let (stripped, cuts) = crate::md::strip_comments(markdown);
    // pulldown has never heard of `^[text]` either: each becomes a reference
    // to a definition appended past the end of the note, and every offset in
    // that tail is mapped back to the text it came from
    let (rewritten, notes) = inline_footnotes(&stripped);
    r.src = rewritten.clone();
    r.cuts = cuts;
    r.tail_start = rewritten.len() - notes.iter().map(|n| n.tail_len).sum::<usize>();
    r.inline_notes = notes;
    r.run(&rewritten);
    r.finish()
}

/// `markdown` with every trailing ` ^blockid` replaced by spaces of the same
/// byte length. Fenced code is left alone: a caret there is code.
pub fn blank_block_ids(markdown: &str) -> String {
    let mut out = String::with_capacity(markdown.len());
    let mut fenced = false;
    for raw in markdown.split_inclusive('\n') {
        let line = raw.trim_end_matches('\n').trim_end_matches('\r');
        if crate::md::is_fence(line) {
            fenced = !fenced;
        }
        match (fenced, crate::md::block_id_at(line)) {
            (false, Some((col, _))) => {
                let byte = line.char_indices().nth(col).map_or(line.len(), |(b, _)| b);
                out.push_str(&line[..byte]);
                out.extend(std::iter::repeat_n(' ', line.len() - byte));
                out.push_str(&raw[line.len()..]);
            }
            _ => out.push_str(raw),
        }
    }
    out
}

/// An Obsidian inline footnote `^[text]`, rewritten for pulldown as a
/// reference `[^~N]` whose definition is appended after the note.
#[derive(Debug, Clone, PartialEq, Eq)]
struct InlineNote {
    label: String,
    /// Its number, counted with the `[^label]` references in document order.
    ordinal: usize,
    /// Byte offset, in the rewritten body, of where the text stood inside
    /// the `^[…]` — the same as in the note unless an earlier footnote on
    /// the line was shorter than its label.
    orig: usize,
    /// Byte offset of the same text inside the appended definition.
    def: usize,
    /// The text's length in bytes.
    len: usize,
    /// How many bytes the appended definition took, blank line included.
    tail_len: usize,
}

/// Rewrite every `^[text]` in `markdown` into a `[^~N]` reference and append
/// the definitions. The label is padded to the text's own length, so every
/// other byte on the line keeps its offset and a click still lands where it
/// should; only a text shorter than its label shifts the rest of its line.
fn inline_footnotes(markdown: &str) -> (String, Vec<InlineNote>) {
    let mut out = String::with_capacity(markdown.len());
    let mut notes: Vec<InlineNote> = Vec::new();
    let mut bodies: Vec<&str> = Vec::new();
    let lines: Vec<&str> = markdown
        .split_inclusive('\n')
        .map(|raw| raw.trim_end_matches('\n').trim_end_matches('\r'))
        .collect();
    let counts = crate::md::footnote_counts(&lines);
    for (row, raw) in markdown.split_inclusive('\n').enumerate() {
        let line = lines[row];
        let mut ordinal = counts[row];
        // a line the count skipped — fenced, commented, or without a `^[` —
        // has nothing to rewrite
        let refs = if counts[row + 1] == ordinal || !line.contains("^[") {
            Vec::new()
        } else {
            crate::md::footnote_refs(line)
        };
        if refs.is_empty() {
            out.push_str(raw);
            continue;
        }
        // char columns → byte offsets within the line
        let bytes: Vec<usize> = line
            .char_indices()
            .map(|(b, _)| b)
            .chain(std::iter::once(line.len()))
            .collect();
        let mut at = 0;
        for r in refs {
            if !r.inline {
                ordinal += 1;
                continue;
            }
            let (start, end) = (bytes[r.start], bytes[r.end]);
            let (b0, b1) = (bytes[r.body.0], bytes[r.body.1]);
            out.push_str(&line[at..start]);
            let orig = out.len() + 2;
            let mut label = format!("~{ordinal}");
            while label.len() < b1 - b0 {
                label.push('~');
            }
            out.push_str("[^");
            out.push_str(&label);
            out.push(']');
            notes.push(InlineNote {
                label,
                ordinal,
                orig,
                def: 0,
                len: b1 - b0,
                tail_len: 0,
            });
            bodies.push(&line[b0..b1]);
            ordinal += 1;
            at = end;
        }
        out.push_str(&raw[at..]);
    }
    if notes.is_empty() {
        return (out, notes);
    }
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    let body_end = out.len();
    let mut tail_len = out.len();
    for (n, body) in notes.iter_mut().zip(bodies) {
        out.push_str("\n[^");
        out.push_str(&n.label);
        out.push_str("]: ");
        n.def = out.len();
        out.push_str(body);
        out.push('\n');
        n.tail_len = out.len() - tail_len;
        tail_len = out.len();
    }
    debug_assert_eq!(
        body_end + notes.iter().map(|n| n.tail_len).sum::<usize>(),
        out.len()
    );
    (out, notes)
}

/// 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(if width == usize::MAX { 40 } else { width }),
            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));
    // two sections under one rule: the notes that link here, then the notes
    // that only say this note's name. Each is left out when it is empty.
    let linked: Vec<&crate::mentions::Mention> = mentions.iter().filter(|m| m.linked).collect();
    let unlinked: Vec<&crate::mentions::Mention> = mentions.iter().filter(|m| !m.linked).collect();
    if !linked.is_empty() {
        let count = match linked.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()
        });
        for m in &linked {
            append_mention_row(r, m, namew, width);
        }
    }
    if !unlinked.is_empty() {
        if !linked.is_empty() {
            r.lines.push(PLine::default());
        }
        let count = match unlinked.len() {
            1 => "mentioned in 1 note".to_string(),
            n => format!("mentioned in {n} notes"),
        };
        r.lines.push(PLine {
            cells: str_cells(&count, dim),
            ..Default::default()
        });
        let shown = unlinked.len().min(crate::mentions::MAX_UNLINKED_ROWS);
        for m in &unlinked[..shown] {
            append_mention_row(r, m, namew, width);
        }
        if unlinked.len() > shown {
            r.lines.push(PLine {
                cells: str_cells(&format!("  {} more", unlinked.len() - shown), dim),
                ..Default::default()
            });
        }
    }
}

/// One footer row: the note's name as a link, then its excerpt.
fn append_mention_row(r: &mut Rendered, m: &crate::mentions::Mention, namew: usize, width: usize) {
    let dim = theme::marker();
    {
        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));
            // the words that made an unlinked row are shown in normal text
            // against the dim excerpt, which is what says why the row is here
            cells.extend(excerpt_cells(&m.excerpt, m.link, dim, room, !m.linked));
        }
        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 href on the properties box's top edge and on the line it folds to:
/// not a link anywhere, a click the app answers by flipping the setting.
pub const PROPERTIES_HREF: &str = "catcher:properties";

/// 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;

/// Put the note's front matter at the top of an already-rendered page, drawn
/// as a box of properties rather than the YAML the editor shows: one row per
/// key, keys in one column, `tags` as the `#tags` they are and clickable like
/// the inline kind, `aliases` run together, and an ISO date followed by how
/// far away it is from `today`.
///
/// Prepended rather than rendered because pulldown-cmark has no notion of front
/// matter and the body it is handed already has the block cut off. Every row
/// carries the file line of its key, so a click on a property lands the cursor
/// on the line that sets it; the frame carries none.
///
/// A note without front matter gets nothing, not even an empty frame.
pub fn prepend_properties(
    r: &mut Rendered,
    content: &str,
    width: usize,
    today: (i32, u32, u32),
    mode: crate::config::Properties,
) {
    use crate::config::Properties;
    let props = crate::md::front_matter_properties(content);
    if props.is_empty() || mode == Properties::Hide {
        return;
    }
    let border = theme::border();
    let width = if width == usize::MAX {
        40
    } else {
        width.max(8)
    };
    // the cells that take the click that folds the box or opens it again
    let toggle = r.urls.len();
    r.urls.push(PROPERTIES_HREF.to_string());
    let linked = |mut cells: Vec<PCell>| {
        for c in &mut cells {
            c.link = Some(toggle);
        }
        cells
    };

    if mode == Properties::Line {
        let n = props.len();
        let label = if n == 1 {
            "1 property".to_string()
        } else {
            format!("{n} properties")
        };
        let mut cells = linked(str_cells(theme::FOLDED, theme::fold()));
        cells.extend(linked(str_cells(&label, theme::marker())));
        let mut lines = vec![
            PLine {
                cells,
                ..Default::default()
            },
            PLine::default(),
        ];
        lines.append(&mut r.lines);
        r.lines = lines;
        return;
    }
    let inner = width - 4;
    let keyw = props
        .iter()
        .map(|p| crate::md::str_width(&p.key))
        .max()
        .unwrap_or(0)
        .min(inner / 2);

    let mut lines: Vec<PLine> = Vec::with_capacity(props.len() + 3);
    let mut top = str_cells("", border);
    top.extend(str_cells("properties", theme::grey()));
    top.push(cell(' ', border));
    // `hide` sits in the edge at the right, as dim as the rule; the whole
    // edge answers the click, the word only says what the click does
    let tail = str_cells(" hide ┐", border);
    let fill = width.saturating_sub(cells_width(&top) + cells_width(&tail));
    top.extend(str_cells(&"".repeat(fill), border));
    top.extend(tail);
    lines.push(PLine {
        cells: linked(top),
        ..Default::default()
    });

    for p in &props {
        let mut cells = str_cells("", border);
        let key = truncate_cells(&str_cells(&p.key, theme::grey()), keyw);
        let pad = keyw - cells_width(&key);
        cells.extend(key);
        cells.extend(str_cells(&" ".repeat(pad + 2), theme::PLAIN));
        let room = inner.saturating_sub(keyw + 2);
        let value = property_cells(r, p, today);
        cells.extend(truncate_cells(&value, room));
        let rest = width.saturating_sub(cells_width(&cells) + 1);
        cells.extend(str_cells(&" ".repeat(rest), theme::PLAIN));
        cells.push(cell('', border));
        lines.push(PLine {
            cells,
            src_line: Some(p.line),
            ..Default::default()
        });
    }

    let mut bottom = str_cells("", border);
    bottom.extend(str_cells(&"".repeat(width - 2), border));
    bottom.push(cell('', border));
    lines.push(PLine {
        cells: bottom,
        ..Default::default()
    });
    lines.push(PLine::default());
    lines.append(&mut r.lines);
    r.lines = lines;
}

/// The value column of one property row. Tags become clickable `#tags`,
/// aliases and any other list are joined with a middle dot, and a lone date
/// says how far off it is.
fn property_cells(r: &mut Rendered, p: &crate::md::Property, today: (i32, u32, u32)) -> Vec<PCell> {
    let mut cells = Vec::new();
    if p.key == "tags" {
        // `tags: a, b` and `tags: [a, b]` both arrive as text to split
        let tags: Vec<String> = p
            .values
            .iter()
            .flat_map(|v| v.split(|c: char| c == ',' || c.is_whitespace()))
            .map(|t| crate::md::tag_key(t.trim_matches(|c| c == '"' || c == '\'')))
            .filter(|t| !t.is_empty())
            .collect();
        for (i, tag) in tags.iter().enumerate() {
            if i > 0 {
                cells.push(cell(' ', theme::PLAIN));
            }
            let idx = r.urls.len();
            r.urls.push(crate::md::LinkTarget::Tag(tag.clone()).href());
            let mut run = str_cells(&format!("#{tag}"), theme::tag());
            for c in &mut run {
                c.link = Some(idx);
            }
            cells.extend(run);
        }
        return cells;
    }
    for (i, v) in p.values.iter().enumerate() {
        if i > 0 {
            cells.extend(str_cells(" · ", theme::grey()));
        }
        cells.extend(str_cells(v, theme::PLAIN));
        if let Some(date) = crate::dates::parse_iso(v) {
            let hint = crate::dates::relative(date, today);
            cells.extend(str_cells(&format!("  {hint}"), theme::marker()));
        }
    }
    cells
}

fn cell(ch: char, style: Style) -> PCell {
    PCell {
        ch,
        style,
        link: None,
        src: None,
    }
}

/// 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.
/// Take the folded sections out of a rendered page, before the footer goes
/// on: every row drawn from a hidden line goes, a folded heading gets the
/// `▸ ` marker in front and how many lines it hides at the right edge, the
/// way the editor draws one, and the blank rows either side of a section
/// that is gone collapse to one, so two headings end up spaced the way they
/// would be with nothing between them.
///
/// Rows are dropped rather than the source cut: the renderer never sees a
/// section boundary that is not there, and every line number the page keeps
/// still counts from the top of the file.
pub fn apply_folds(
    r: &mut Rendered,
    visible: &crate::fold::Visible,
    folded: &[usize],
    width: usize,
) {
    if visible.is_plain() {
        return;
    }
    let lines = std::mem::take(&mut r.lines);
    let mut out: Vec<PLine> = Vec::with_capacity(lines.len());
    for mut line in lines {
        match line.src_line {
            Some(l) if visible.is_hidden(l) => continue,
            Some(l) if folded.contains(&l) && !line.cells.is_empty() => {
                // the marker only on the heading's first row: a heading that
                // wrapped carries its line number on every row it took, and
                // a folded card's bottom edge carries the title's too
                let first = out.last().is_none_or(|p| p.src_line != Some(l));
                let edge = line.cells.iter().any(|c| c.ch == '');
                if first && line.cells.iter().any(|c| c.ch == '') {
                    mark_folded_card(&mut line, l, visible.hidden_under(l));
                } else if first && !edge {
                    mark_folded(&mut line, l, visible.hidden_under(l), width);
                }
            }
            // a card's `│   │` spacer row under a folded title went with the body
            None if !line.cells.is_empty()
                && out
                    .last()
                    .is_some_and(|p| p.src_line.is_some_and(|l| folded.contains(&l))) =>
            {
                continue
            }
            // a spacer next to one the section took with it
            None if line.cells.is_empty() && out.last().is_some_and(|p| p.cells.is_empty()) => {
                continue
            }
            _ => {}
        }
        out.push(line);
    }
    // a section folded at the very end leaves the spacer that stood before it
    while out.last().is_some_and(|l| l.cells.is_empty()) {
        out.pop();
    }
    r.lines = out;
}

/// A folded callout's title row: the `▸ ` inside the card's top edge, where
/// an open foldable card shows `▾ `, and how many lines it hides in the
/// dashes at the right when they have room. The row keeps its width.
fn mark_folded_card(line: &mut PLine, src: usize, hidden: usize) {
    let Some(open) = line.cells.iter().position(|c| c.ch == '') else {
        return;
    };
    let Some(close) = line.cells.iter().rposition(|c| c.ch == '') else {
        return;
    };
    let at = open + 3;
    let marker = |ch: char| PCell {
        ch,
        style: theme::fold(),
        link: None,
        src: Some((src, 0)),
    };
    let mut close = close;
    if line.cells.get(at).is_some_and(|c| c.ch == '') {
        line.cells[at] = marker('');
    } else if close > at + 2 && line.cells[close - 2..close].iter().all(|c| c.ch == '') {
        line.cells.splice(close - 2..close, []);
        line.cells.splice(at..at, [marker(''), marker(' ')]);
    } else {
        return;
    }
    let label = crate::md::fold_count(hidden);
    let dashes = line.cells[..close]
        .iter()
        .rev()
        .take_while(|c| c.ch == '')
        .count();
    let need = crate::md::str_width(&label) + 3;
    if dashes <= need {
        return;
    }
    let style = line.cells[close].style;
    let mut tail = str_cells(" ", style);
    tail.extend(str_cells(&label, theme::marker()));
    tail.extend(str_cells("", style));
    close = line
        .cells
        .iter()
        .rposition(|c| c.ch == '')
        .unwrap_or(close);
    line.cells.splice(close - need..close, tail);
}

/// The `▸ ` in front of a folded heading, standing for source column 0 the
/// way it does in the editor, and the count at the right edge when the row
/// has room for it and a gap besides.
fn mark_folded(line: &mut PLine, src: usize, hidden: usize, width: usize) {
    let marker: Vec<PCell> = theme::FOLDED
        .chars()
        .map(|ch| PCell {
            ch,
            style: theme::fold(),
            link: None,
            src: Some((src, 0)),
        })
        .collect();
    line.cells.splice(0..0, marker);
    let label = match hidden {
        1 => "1 line folded".to_string(),
        n => format!("{n} lines folded"),
    };
    let used = cells_width(&line.cells);
    let need = crate::md::str_width(&label) + 2;
    if width == usize::MAX || used + need > width {
        return;
    }
    line.cells.extend(str_cells(
        &" ".repeat(width - used - need + 2),
        theme::PLAIN,
    ));
    line.cells.extend(str_cells(&label, theme::marker()));
}

/// 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.
///
/// With `plain_span`, the chars inside `link` are drawn without `base` — the
/// matched words of an unlinked mention stand out of the dim excerpt.
fn excerpt_cells(
    excerpt: &str,
    link: (usize, usize),
    base: Style,
    room: usize,
    plain_span: bool,
) -> Vec<PCell> {
    let cells: Vec<PCell> = crate::md::style_inline(excerpt)
        .into_iter()
        .map(|c| PCell {
            ch: c.ch,
            style: if plain_span && c.src >= link.0 && c.src < link.1 {
                c.style
            } else {
                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>>,
}

/// One level of quote decoration around a row.
#[derive(Clone, Copy, Debug)]
enum Deco {
    /// A plain blockquote's `▌ `.
    Rail,
    /// A callout card: its colour, how wide it is, and the source line of
    /// its title, which its bottom edge answers to (so a fold on the title
    /// keeps the edge under it).
    Card {
        style: Style,
        w: usize,
        title: Option<usize>,
    },
}
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,
    /// The colour of the open callout box, by its kind.
    box_style: Style,
    /// The quote decoration around the line being built, outermost first:
    /// a rail for each plain blockquote, a card for each callout. A callout
    /// inside a callout is a card of its own, drawn inside the outer one.
    quotes: Vec<Deco>,
    /// 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,
    /// One entry per open list: the next number an ordered list will give its
    /// item, or `None` for a bulleted one.
    list_numbers: Vec<Option<u64>>,
    in_code_block: bool,
    /// Inside a ```mermaid fence: the body accumulated so far, and the source
    /// byte offset it started at. The whole body is held back until the
    /// closing fence, because whether it is drawn at all is only known once
    /// there is a diagram to draw.
    mermaid: Option<(String, usize)>,
    table: Option<Table>,
    /// How a table wider than the page is drawn.
    tables: TableStyle,
    /// Page width in columns, used to size tables.
    width: usize,
    /// The markdown as it is in the file, comments and all. `src` is what
    /// pulldown-cmark walks — the same text with its `%% comments %%` cut
    /// out — so every offset an event carries is into `src`, and `cuts`
    /// turns it back into an offset into this.
    orig: String,
    /// Where `src` lost bytes to a comment: (offset in `src`, bytes cut there),
    /// ascending. Empty when the note has no comments.
    cuts: Vec<(usize, usize)>,
    /// Byte offset of the start of each source line, in `orig`.
    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>,
    /// A footnote's superscript label, waiting for its first paragraph.
    footnote: Option<String>,
    /// The `^[text]` footnotes `inline_footnotes` rewrote, and where in `src`
    /// their appended definitions begin: offsets from there on map back to
    /// the text inside the `^[…]`.
    inline_notes: Vec<InlineNote>,
    tail_start: usize,
    done_item: bool,
    /// A list item has just opened and nothing but its marker is drawn, so a
    /// `[/] ` at the head of its text is a box in a state pulldown does not
    /// know, not text.
    item_fresh: 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,
    /// The inline HTML tags open at this point, innermost last. Each pushed
    /// one style onto `styles`, popped again when its `</tag>` arrives.
    html: Vec<String>,
    /// Inside a `<!-- comment` that a later HTML block line has yet to close.
    in_comment: bool,
}

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,
            box_style: Style::new(),
            quotes: Vec::new(),
            quote_fresh: false,
            quote_blank: false,
            hang: 0,
            list_depth: 0,
            list_numbers: Vec::new(),
            in_code_block: false,
            mermaid: None,
            table: None,
            tables,
            width,
            orig: markdown.to_string(),
            cuts: Vec::new(),
            line_starts,
            first_line,
            src_line: None,
            pending_checkbox: None,
            footnote: None,
            inline_notes: Vec::new(),
            tail_start: usize::MAX,
            done_item: false,
            item_fresh: false,
            image_alt: None,
            wiki_until: 0,
            html: Vec::new(),
            in_comment: false,
        }
    }

    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);
    }

    /// An offset into `src` as an offset into `orig`: every comment cut at or
    /// before it puts its bytes back.
    fn orig_offset(&self, offset: usize) -> usize {
        offset
            + self
                .cuts
                .iter()
                .take_while(|(at, _)| *at <= offset)
                .map(|(_, n)| n)
                .sum::<usize>()
    }

    /// A byte offset in the appended footnote tail, taken back to the
    /// `^[text]` it was copied from; anything in the body is its own.
    fn remap(&self, offset: usize) -> usize {
        if offset < self.tail_start {
            return offset;
        }
        let note = self
            .inline_notes
            .iter()
            .find(|n| offset <= n.def + n.len)
            .or(self.inline_notes.last());
        match note {
            Some(n) => n.orig + offset.saturating_sub(n.def).min(n.len),
            None => offset,
        }
    }

    /// A callout title with its footnote references drawn as superscripts:
    /// the title is copied as text, so a rewritten `[^~1]` would show.
    fn title_marks(&self, title: &str) -> String {
        let mut out = String::with_capacity(title.len());
        let mut rest = title;
        while let Some(i) = rest.find("[^") {
            let Some(len) = rest[i + 2..].find(']') else {
                break;
            };
            let label = &rest[i + 2..i + 2 + len];
            if label.is_empty() || label.contains(' ') {
                out.push_str(&rest[..i + 2]);
                rest = &rest[i + 2..];
                continue;
            }
            out.push_str(&rest[..i]);
            out.push_str(&self.footnote_mark(label));
            rest = &rest[i + 3 + len..];
        }
        out.push_str(rest);
        out
    }

    /// The superscript a footnote label is drawn as: an inline footnote's
    /// number, any other label as itself.
    fn footnote_mark(&self, label: &str) -> String {
        match self.inline_notes.iter().find(|n| n.label == label) {
            Some(n) => crate::md::superscript(&n.ordinal.to_string()),
            None => crate::md::superscript(label),
        }
    }

    /// The slice-relative line of an offset into `src`.
    fn line_of(&self, offset: usize) -> usize {
        let offset = self.orig_offset(self.remap(offset));
        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 `orig`, both of which are the slice's.
    fn pos_of(&self, offset: usize) -> (usize, usize) {
        let offset = self.remap(offset);
        let line = self.line_of(offset);
        let start = self.line_starts.get(line).copied().unwrap_or(0);
        let offset = self.orig_offset(offset).min(self.orig.len());
        let col = self
            .orig
            .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 = if self.quotes.is_empty() {
            self.rails * 2 + if self.boxed { 4 } else { 0 }
        } else {
            self.taken()
        };
        if self.width == usize::MAX {
            usize::MAX
        } else {
            self.width.saturating_sub(taken).max(8)
        }
    }

    /// Width a `---` rule is drawn at: the full width of the page, inside any
    /// quote decoration. A width no page has means the caller did not care.
    fn rule_width(&self) -> usize {
        match self.inner_width() {
            usize::MAX => 40,
            w => w,
        }
    }

    /// Columns the open quotes take: two for a rail, four for a card's edges.
    fn taken(&self) -> usize {
        self.quotes
            .iter()
            .map(|d| match d {
                Deco::Rail => 2,
                Deco::Card { .. } => 4,
            })
            .sum()
    }

    /// 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,
                hang,
            });
            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,
                hang: 0,
            });
        }
    }

    /// 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.quotes.is_empty() {
            let mut cells = Vec::new();
            let mut edges: Vec<(Style, usize)> = Vec::new();
            let mut x = 0;
            for deco in &self.quotes {
                match *deco {
                    Deco::Rail => cells.extend(str_cells(
                        &format!("{} ", theme::QUOTE_BAR),
                        theme::marker(),
                    )),
                    Deco::Card { style, w, .. } => {
                        cells.extend(str_cells("", style));
                        edges.push((style, x + w));
                    }
                }
                x += 2;
            }
            cells.extend(line.cells);
            // the right edges, innermost first, each out at its card's width
            for (style, end) in edges.into_iter().rev() {
                let used = cells_width(&cells);
                if used + 2 > end {
                    break;
                }
                cells.extend(str_cells(&" ".repeat(end - used - 2), theme::PLAIN));
                cells.extend(str_cells("", style));
            }
            line.cells = cells;
        } else if !line.wide && (self.rails > 0 || self.boxed) {
            let mut cells = Vec::new();
            if self.boxed {
                cells.extend(str_cells("", self.box_style));
            }
            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("", self.box_style));
            }
            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, then the card on the
    /// stack so the rows after it sit inside. A card inside another is as
    /// wide as the room the outer one leaves it. A card that can fold
    /// (`[!kind]-` or `[!kind]+`) carries `▾ ` before its glyph.
    fn open_box(&mut self, kind: &str, title: &str, marker: Option<char>) {
        let w = self.box_width().saturating_sub(self.taken());
        let style = theme::callout(kind);
        if !self.boxed {
            self.box_w = w;
            self.box_style = style;
        }
        let mut cells = str_cells("╭─ ", style);
        if marker.is_some() {
            cells.extend(str_cells(theme::UNFOLDED, style));
        }
        if let Some(g) = crate::md::callout_glyph(kind) {
            cells.extend(str_cells(&format!("{g} "), style));
        }
        cells.extend(str_cells(kind, style));
        if !title.is_empty() {
            cells.extend(str_cells(" · ", style));
            let title = self.title_marks(title);
            cells.extend(str_cells(&title, style.add_modifier(Modifier::BOLD)));
        }
        cells.push(PCell {
            ch: ' ',
            style,
            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), style));
        row.extend(str_cells("", style));
        let fresh = self.quote_fresh;
        self.emit_line(PLine {
            cells: row,
            checkbox: None,
            image: None,
            src_line: self.src_line,
            wide: false,
            hang: 0,
        });
        self.quote_fresh = fresh;
        self.quotes.push(Deco::Card {
            style,
            w,
            title: self.src_line,
        });
    }

    /// Close the innermost card: its bottom edge, inside whatever is around
    /// it, answering to the title's line so a fold keeps the two together.
    fn close_box(&mut self) {
        let Some(Deco::Card { style, w, title }) = self.quotes.pop() else {
            return;
        };
        let row = format!("{}", "".repeat(w.saturating_sub(2)));
        self.emit_line(PLine {
            cells: str_cells(&row, style),
            checkbox: None,
            image: None,
            src_line: title,
            wide: false,
            hang: 0,
        });
    }

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

    /// Draw a task's box in place of the bullet pushed when the item opened
    /// — or after its number, which a numbered task keeps. The item's text
    /// is struck from here on when the state is one that is over. `space`
    /// says whether to follow the glyph with its own space or leave that to
    /// the text pulldown sends next.
    fn task_box(&mut self, glyph: &'static str, style: Style, src_line: usize, space: bool) {
        let ordered = matches!(self.list_numbers.last(), Some(Some(_)));
        if !ordered {
            self.cells.clear();
            let indent = self.indent();
            self.hang = crate::md::str_width(&indent);
            self.push(&indent, style, None);
        }
        let mark = if space {
            format!("{glyph} ")
        } else {
            glyph.to_string()
        };
        self.hang += crate::md::str_width(glyph) + 1;
        self.push(&mark, style, None);
        self.pending_checkbox = Some(src_line);
        if crate::md::struck(glyph) {
            // 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;
        }
    }

    /// 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 byte_at = byte_offsets(&chars, off);
        Some((
            byte_at[w.end],
            w.full_target(),
            byte_at[w.label_start],
            byte_at[w.label_end],
        ))
    }

    /// An Obsidian embed, `![[picture.png]]`, whose `!` is at byte offset
    /// `off` and which has its line to itself, as (alt, url, byte offset just
    /// past the end of the line). Everything pulldown goes on to emit for the
    /// line is skipped the way the rest of a wikilink is.
    fn embed_here(&self, off: usize) -> Option<(String, String, Option<u32>, usize)> {
        if !crate::md::links::enabled() || !self.src[off..].starts_with("![[") {
            return None;
        }
        let line_start = self.src[..off].rfind('\n').map_or(0, |n| n + 1);
        let line_end = self.src[off..]
            .find('\n')
            .map_or(self.src.len(), |n| off + n);
        let line = &self.src[line_start..line_end];
        if line.trim_start().len() != line_end - off {
            return None; // the embed is not the first thing on its line
        }
        let (alt, url, width) = crate::md::embed_line(line)?;
        Some((alt, url, width, line_end))
    }

    /// An attachment embed, `![[report.pdf]]`, whose `!` is at byte offset
    /// `off` and which has its line to itself: (name, label, byte offset just
    /// past the end of the line).
    fn attachment_embed_here(&self, off: usize) -> Option<(String, Option<String>, usize)> {
        if !crate::md::links::enabled() || !self.src[off..].starts_with("![[") {
            return None;
        }
        let line_start = self.src[..off].rfind('\n').map_or(0, |n| n + 1);
        let line_end = self.src[off..]
            .find('\n')
            .map_or(self.src.len(), |n| off + n);
        let line = &self.src[line_start..line_end];
        if line.trim_start().len() != line_end - off {
            return None; // the embed is not the first thing on its line
        }
        let (name, label) = crate::md::attachment_embed_line(line)?;
        Some((name, label, line_end))
    }

    /// An Obsidian note embed, `![[note]]`, whose `!` is at byte offset `off`
    /// and which has its line to itself, with the byte offset just past the
    /// end of the line so the rest of what pulldown emits for it is skipped.
    fn note_embed_here(&self, off: usize) -> Option<(crate::md::NoteEmbed, usize)> {
        if !crate::md::links::enabled() || !self.src[off..].starts_with("![[") {
            return None;
        }
        let line_start = self.src[..off].rfind('\n').map_or(0, |n| n + 1);
        let line_end = self.src[off..]
            .find('\n')
            .map_or(self.src.len(), |n| off + n);
        let line = &self.src[line_start..line_end];
        if line.trim_start().len() != line_end - off {
            return None; // the embed is not the first thing on its line
        }
        let embed = crate::md::note_embed_line(line)?;
        Some((embed, line_end))
    }

    /// An embedded note in running text, `![[note]]` with its `!` at byte
    /// offset `off`: (byte offset just past it, target, label start, label
    /// end, whether the label was typed after a pipe). A picture is not one —
    /// `md::wikilink_at` sees the `!` and says so.
    fn note_link_here(&self, off: usize) -> Option<(usize, String, usize, usize, bool)> {
        if !crate::md::links::enabled() || !self.src[off..].starts_with("![[") {
            return None;
        }
        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, 1)?;
        let byte_at = byte_offsets(&chars, off);
        Some((
            byte_at[w.end],
            w.target,
            byte_at[w.label_start],
            byte_at[w.label_end],
            w.label_start != w.start + 2,
        ))
    }

    /// A `![[note]]` on a line of its own, as a card: a rail, the note's
    /// title (a link to it), its first lines, and how much was left out.
    fn emit_attachment_card(&mut self, name: &str, label: Option<&str>) {
        self.flush();
        let style = crate::md::embed_style();
        let idx = self.out.urls.len();
        self.out
            .urls
            .push(crate::md::LinkTarget::File(name.to_string()).href());
        let rail = format!("{} ", theme::QUOTE_BAR);
        self.push(&rail, style, None);
        match crate::md::attachment_card(name, label) {
            (text, true) => self.push(&text, style.add_modifier(Modifier::BOLD), Some(idx)),
            (text, false) => self.push(&text, theme::grey(), Some(idx)),
        }
        self.flush();
    }

    /// A `![[report.pdf]]` on a line of its own, as a card: a rail and one
    /// row naming the file and its size, a link the desktop opens.
    fn emit_embed_card(&mut self, embed: &crate::md::NoteEmbed) {
        self.flush();
        let card = crate::md::embed_card(embed);
        let style = crate::md::embed_style();
        let idx = self.out.urls.len();
        self.out
            .urls
            .push(crate::md::LinkTarget::Wiki(embed.target.clone()).href());
        let rail = format!("{} ", theme::QUOTE_BAR);
        self.push(&rail, style, None);
        match card.found {
            crate::md::embeds::Found::Missing => self.push(
                &format!("{} (no such note)", card.head()),
                theme::grey(),
                Some(idx),
            ),
            _ => self.push(&card.head(), style.add_modifier(Modifier::BOLD), Some(idx)),
        }
        self.flush();
        for line in &card.lines {
            self.push(&rail, style, None);
            let cells = crate::md::style_inline(line).into_iter().map(|c| PCell {
                ch: c.ch,
                style: c.style,
                link: None,
                src: None,
            });
            self.buf().extend(cells);
            self.flush();
        }
        if card.more > 0 {
            self.push(&rail, style, None);
            self.push(&crate::md::more_lines(card.more), theme::marker(), None);
            self.flush();
        }
    }

    /// One picture on a line of its own: the `🖼 alt (url)` label that stands
    /// in for it, tagged with the image it stands for.
    fn emit_image(&mut self, alt: String, url: String, width: Option<u32>) {
        self.flush();
        let idx = self.out.images.len();
        self.out.images.push(ImageSpec {
            alt: alt.clone(),
            url: url.clone(),
            width,
        });
        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);
    }

    /// 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 byte_at = byte_offsets(&chars, 0);
        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) = crate::md::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 let Some(end) = crate::md::url_at(&chars, i).filter(|_| link.is_none()) {
                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;
            }
            // #tag, when not inside a link. The first char of an event has no
            // char before it in `chars`, so the boundary is read off the
            // source: pulldown splits `x#y` and `` `x`#y `` into events that
            // both start at the `#`, and only the source tells them apart
            if link.is_none() && chars[i] == '#' && crate::md::tags::enabled() {
                let prev = match i {
                    0 => at(0).and_then(|o| self.src[..o].chars().next_back()),
                    _ => Some(chars[i - 1]),
                };
                if crate::md::tag_boundary(prev) {
                    if let Some(end) = crate::md::tag_at(&chars, i) {
                        let name: String = chars[i + 1..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::Tag(name).href());
                        let shown: String = chars[i..end].iter().collect();
                        self.push_at(&shown, base.patch(theme::tag()), 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));
    }

    /// Raw HTML from the document — one inline tag, or one line of an HTML
    /// block. Comments vanish; `<br>` breaks the line; a tag the page knows
    /// (`kbd`, `sub`, `sup`, `u`, `mark`) styles the text up to its close;
    /// any other tag is stripped and what it wrapped is kept. `off` is the
    /// source byte offset of `html`.
    fn emit_html(&mut self, html: &str, off: usize) {
        let chars: Vec<char> = html.chars().collect();
        let byte_at = byte_offsets(&chars, off);
        let mut i = 0;
        while i < chars.len() {
            if self.in_comment {
                match (i..chars.len()).find(|&k| crate::md::html_comment_close_at(&chars, k)) {
                    Some(k) => {
                        self.in_comment = false;
                        i = k + 3;
                    }
                    None => return,
                }
                continue;
            }
            if chars[i] == '<' {
                if let Some(end) = crate::md::html_comment_end(&chars, i) {
                    i = end;
                    continue;
                }
                if chars[i + 1..].starts_with(&['!', '-', '-']) {
                    // a comment this line does not close: dropped to `-->`
                    self.in_comment = true;
                    return;
                }
                if let Some(tag) = crate::md::html_tag_at(&chars, i) {
                    self.html_tag(&tag);
                    i = tag.end;
                    continue;
                }
            }
            if chars[i] == '\n' {
                self.flush();
                i += 1;
                continue;
            }
            let end = (i..chars.len())
                .find(|&k| chars[k] == '<' || chars[k] == '\n')
                .unwrap_or(chars.len());
            let run: String = chars[i..end].iter().collect();
            let run = run.trim_end_matches('\r');
            match self.script() {
                Some(sup) => self.push_script(run, sup, byte_at[i]),
                None => self.emit_text(run, Some(byte_at[i])),
            }
            i = end;
        }
    }

    /// One tag of inline HTML: open, close or `<br>`.
    fn html_tag(&mut self, tag: &crate::md::HtmlTag) {
        if tag.name == "br" {
            if matches!(self.sink, Sink::Table) {
                self.push(" ", self.style(), self.link);
            } else {
                self.flush();
            }
            return;
        }
        if tag.closing {
            if let Some(at) = self.html.iter().rposition(|n| *n == tag.name) {
                while self.html.len() > at {
                    self.html.pop();
                    self.styles.pop();
                }
            }
            return;
        }
        if tag.opens() {
            if let Some(style) = crate::md::html_style(&tag.name, self.style()) {
                self.styles.push(style);
                self.html.push(tag.name.clone());
            }
        }
    }

    /// Drop every inline HTML tag still open: a `<u>` nobody closed must not
    /// underline the rest of the page.
    fn close_html(&mut self) {
        while self.html.pop().is_some() {
            self.styles.pop();
        }
    }

    /// Inside a `<sup>` (`Some(true)`) or a `<sub>` (`Some(false)`)?
    fn script(&self) -> Option<bool> {
        self.html.iter().rev().find_map(|n| match n.as_str() {
            "sup" => Some(true),
            "sub" => Some(false),
            _ => None,
        })
    }

    /// Text inside a `<sub>` or `<sup>`: each char in its Unicode sub- or
    /// superscript form where there is one, the rest as written. One push
    /// per char, because a raised `2` is three bytes to the source's one and
    /// a single run would put every later cell at the wrong column.
    fn push_script(&mut self, text: &str, sup: bool, off: usize) {
        let style = self.style();
        let link = self.link;
        let mut at = off;
        for c in text.chars() {
            let shown = if sup {
                crate::md::sup_char(c)
            } else {
                crate::md::sub_char(c)
            };
            self.push_at(&shown.unwrap_or(c).to_string(), style, link, Some(at));
            at += c.len_utf8();
        }
    }

    /// A ```mermaid fence: the picture when catcher can draw one, and the
    /// source under a label saying what it is when it cannot. Both answers
    /// are honest — a diagram kind we have never heard of degrades to exactly
    /// what a fence looked like yesterday, with a word about why.
    fn emit_mermaid(&mut self, src: &str, off: usize) {
        match crate::mermaid::render(src, self.inner_width()) {
            Some(d) => self.emit_diagram(&d),
            None => self.emit_fence_label(src, off),
        }
    }

    /// Put a drawn diagram on the page, one row per row.
    ///
    /// Split out from `emit_mermaid` so it can be driven by a diagram built by
    /// hand: what the reading view owns here is the styling, the `wide` flag
    /// and the decoration `emit_line` adds, none of which care what drew the
    /// rows. A row wider than the page is marked `wide` and the page pans
    /// across it exactly as it pans a wide table.
    fn emit_diagram(&mut self, d: &crate::mermaid::Rendered) {
        for row in &d.rows {
            let mut cells: Vec<PCell> = Vec::new();
            for run in row {
                cells.extend(str_cells(&run.text, crate::md::mermaid_style(run.role)));
            }
            let wide = cells_width(&cells) > self.width;
            self.emit_line(PLine {
                cells,
                checkbox: None,
                image: None,
                src_line: self.src_line,
                wide,
                hang: 0,
            });
        }
    }

    /// The fallback: a label naming the diagram kind, then the fence's own
    /// source drawn exactly as a code block is — same indent, same colour and,
    /// above all, the same source offsets. Keeping the offsets is what leaves
    /// a click in a diagram catcher could not draw landing on the character it
    /// was aimed at.
    ///
    /// A label and not a box: the callout card is the app's one boxed
    /// construct, and a fence that could not be drawn has no business
    /// competing with it. The marker colour keeps it chrome — never the
    /// accent, which the note spends on its headings.
    fn emit_fence_label(&mut self, src: &str, off: usize) {
        let label = match crate::mermaid::kind_word(src) {
            Some(word) => format!("◇ mermaid · {word}"),
            None => "◇ mermaid".to_string(),
        };
        self.push(&label, theme::marker(), None);
        self.flush();
        let mut off = off;
        // split_inclusive, not lines(), for the same reason the code-block arm
        // uses it: the line ending is counted as it is in the file
        for raw in src.split_inclusive('\n') {
            let l = raw.trim_end_matches('\n').trim_end_matches('\r');
            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);
        }
    }

    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;
        }
        let fresh = std::mem::take(&mut self.item_fresh);
        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.close_html();
                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);
                }
                // the first paragraph of a footnote carries its number
                if let Some(mark) = self.footnote.take() {
                    self.push(&format!("{mark} "), theme::state(), None);
                }
                // a loose item's text starts inside its paragraph
                self.item_fresh = fresh;
            }
            Event::End(TagEnd::Paragraph) => {
                self.close_html();
                self.flush();
            }
            Event::Start(Tag::BlockQuote(_)) => {
                self.blank();
                self.src_line = Some(src_line);
                match callout_at(&self.src, range.start) {
                    Some((kind, title, marker, end)) => {
                        self.open_box(&kind, &title, marker);
                        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);
                    }
                    None => {
                        self.rails += 1;
                        self.quotes.push(Deco::Rail);
                    }
                }
                self.quote_fresh = true;
                self.styles.push(theme::quote());
            }
            Event::End(TagEnd::BlockQuote(_)) => {
                self.styles.pop();
                self.flush();
                match self.quotes.last() {
                    Some(Deco::Rail) => {
                        self.rails -= 1;
                        self.quotes.pop();
                    }
                    Some(Deco::Card { .. }) => {
                        // the flag first: the edge is drawn once the card is off
                        // the stack, and must not fall back to the outer box
                        self.boxed = self.quotes[..self.quotes.len() - 1]
                            .iter()
                            .any(|d| matches!(d, Deco::Card { .. }));
                        self.close_box();
                    }
                    None => {}
                }
                self.quote_fresh = false;
                self.quote_blank = false;
            }
            Event::Start(Tag::List(start)) => {
                if self.list_depth == 0 {
                    self.blank();
                }
                self.list_depth += 1;
                self.list_numbers.push(start);
            }
            Event::End(TagEnd::List(_)) => {
                self.list_depth = self.list_depth.saturating_sub(1);
                self.list_numbers.pop();
                self.flush();
            }
            Event::Start(Tag::Item) => {
                self.flush();
                self.src_line = Some(src_line);
                // an ordered list keeps its numbers, as the file wrote them
                let marker = match self.list_numbers.last_mut() {
                    Some(Some(n)) => {
                        let m = format!("{n}.");
                        *n += 1;
                        m
                    }
                    _ => theme::bullet(self.list_depth).to_string(),
                };
                let text = format!("{}{marker} ", self.indent());
                self.hang = crate::md::str_width(&text);
                self.push(&text, theme::marker(), None);
                self.item_fresh = true;
            }
            Event::End(TagEnd::Item) => {
                self.close_html();
                if self.done_item {
                    self.styles.pop();
                    self.done_item = false;
                }
                self.flush()
            }
            Event::TaskListMarker(done) => {
                let (mark, style) = if done {
                    (theme::CHECKED, theme::done())
                } else {
                    (theme::UNCHECKED, theme::marker())
                };
                self.task_box(mark, style, src_line, true);
            }
            Event::Start(Tag::CodeBlock(kind)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.in_code_block = true;
                if matches!(&kind, CodeBlockKind::Fenced(info) if crate::mermaid::is_mermaid(info))
                {
                    self.mermaid = Some((String::new(), 0));
                }
            }
            Event::End(TagEnd::CodeBlock) => {
                if let Some((src, off)) = self.mermaid.take() {
                    self.emit_mermaid(&src, off);
                }
                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. A relative `[x](other.md)` is a note, by
                // name, and goes to the resolver like a `[[wikilink]]`
                self.out
                    .urls
                    .push(crate::md::LinkTarget::from_href(&dest_url).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.emit_image(alt, url, None);
                }
            }
            // 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) => {
                self.close_html();
                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::inline_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::InlineMath(text) => {
                let style = self.style().patch(theme::math());
                let link = self.link;
                self.push_at(&text, style, link, Some(range.start + 1));
            }
            Event::DisplayMath(text) => {
                // a displayed formula sits on rows of its own, centred
                self.blank();
                self.src_line = Some(src_line);
                let width = self.rule_width();
                for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
                    let w = crate::md::str_width(line);
                    self.push(&" ".repeat(width.saturating_sub(w) / 2), theme::PLAIN, None);
                    self.push(line, theme::math(), None);
                    self.flush();
                }
            }
            Event::FootnoteReference(label) => {
                let mark = self.footnote_mark(&label);
                self.push(&mark, theme::state(), None);
            }
            Event::Start(Tag::FootnoteDefinition(label)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.footnote = Some(self.footnote_mark(&label));
            }
            Event::End(TagEnd::FootnoteDefinition) => {
                self.footnote = None;
                self.flush();
            }
            Event::Text(text) => {
                if let Some((alt, _)) = self.image_alt.as_mut() {
                    alt.push_str(&text);
                } else if let Some((buf, off)) = self.mermaid.as_mut() {
                    // held back, not drawn: the fence is a diagram until the
                    // close proves otherwise, and a diagram is drawn whole
                    if buf.is_empty() {
                        *off = range.start;
                    }
                    buf.push_str(&text);
                } else if let Some(sup) = self.script() {
                    // inside <sub> or <sup>: the glyphs change, not the style
                    self.push_script(&text, sup, range.start);
                } 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((glyph, style)) = fresh
                    .then(|| other_task(&self.src[range.start..]))
                    .flatten()
                {
                    // `- [/] text`, `- [-] text`…: pulldown only knows ` ` and
                    // `x` as task boxes, so the other states arrive as text —
                    // `[`, `/` and `]` a piece each. The box is drawn from the
                    // source the way `TaskListMarker` draws its two, the rest
                    // of the bracket is skipped, and the space after it is
                    // left to arrive as the text it is.
                    self.task_box(glyph, style, src_line, false);
                    self.wiki_until = range.start + 3;
                } else if let Some((alt, url, width, end)) = self.embed_here(range.start) {
                    // `![[picture.png]]` on a line of its own is a picture,
                    // the same as `![](picture.png)`; pulldown sees only text
                    self.emit_image(alt, url, width);
                    self.wiki_until = end;
                } else if let Some((name, label, end)) = self.attachment_embed_here(range.start) {
                    // `![[report.pdf]]` on a line of its own is a card naming
                    // the file, for the desktop to open
                    self.emit_attachment_card(&name, label.as_deref());
                    self.wiki_until = end;
                } else if let Some((embed, end)) = self.note_embed_here(range.start) {
                    // `![[note]]` on a line of its own is the note, as a card
                    self.emit_embed_card(&embed);
                    self.wiki_until = end;
                } else if let Some((end, target, ls, le, aliased)) =
                    self.note_link_here(range.start)
                {
                    // `![[note]]` in a sentence is the link it also is, the
                    // `!` swallowed with the brackets; a bare `Note#Heading`
                    // reads as `Note › Heading`
                    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);
                    let label = &self.src[ls..le];
                    match label.find('#').filter(|_| !aliased) {
                        Some(h) => {
                            let (note, heading) =
                                (label[..h].to_string(), label[h + 1..].to_string());
                            self.push_at(&note, style, Some(idx), Some(ls));
                            self.push("", style, Some(idx));
                            self.push_at(&heading, style, Some(idx), Some(ls + h + 1));
                        }
                        None => {
                            let label = label.to_string();
                            self.push_at(&label, style, Some(idx), Some(ls));
                        }
                    }
                    self.wiki_until = end;
                } 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);
                    // an unaliased `[[note#Heading]]` reads `note › Heading`,
                    // as it does in the editor; the chevron is ours and maps
                    // to no source column, the words either side keep theirs
                    let shown_hash = (crate::md::split_fragment(&target).1.is_some()
                        && ls == range.start + 2)
                        .then(|| label.find('#'))
                        .flatten();
                    match shown_hash {
                        Some(h) => {
                            self.push_at(&label[..h], style, Some(idx), Some(ls));
                            let sep = if h == 0 { "" } else { "" };
                            self.push(sep, style, Some(idx));
                            self.push_at(&label[h + 1..], style, Some(idx), Some(ls + h + 1));
                        }
                        None => 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::InlineHtml(html) => self.emit_html(&html, range.start),
            Event::Start(Tag::HtmlBlock) => {
                self.blank();
                self.src_line = Some(src_line);
            }
            Event::Html(html) => {
                if self.cells.is_empty() {
                    self.src_line = Some(src_line);
                }
                self.emit_html(&html, range.start);
            }
            Event::End(TagEnd::HtmlBlock) => {
                self.close_html();
                self.in_comment = false;
                self.flush();
            }
            Event::Rule => {
                self.blank();
                self.push(&"".repeat(self.rule_width()), 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;
        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);
            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,
                    hang: 0,
                });
            }
            // under the head, and between every pair of body rows
            let last = ri + 1 == t.rows.len();
            if ri == 0 || !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,
                    hang: 0,
                });
            }
        }
    }

    /// 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!("{} ", 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,
                hang: 0,
            });
        }
    }

    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 {
        return vec![cells.to_vec()];
    }
    wrap_hang(cells, width, width)
}

/// 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`, with the `-`/`+` fold marker after the type if
/// there is one. Returns (type, title, marker, 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, Option<char>, 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 chars: Vec<char> = line.trim_start_matches(['>', ' ', '\t']).chars().collect();
    // the editor's rule, so the two views never disagree about a title
    let (kind, after, title) = crate::md::callout_title(&chars, 0)?;
    let marker = chars.get(after).copied().filter(|c| matches!(c, '-' | '+'));
    let title: String = chars[title..].iter().collect();
    Some((kind, title.trim().to_string(), marker, start + line_end))
}

/// 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 n = crate::md::cut_at(cells.iter().map(|c| crate::md::char_width(c.ch)), width);
    let mut out = cells[..n].to_vec();
    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()
}

/// The head of a list item's source as a task box in one of the states
/// pulldown-cmark does not recognise — `[/] `, `[-] `, `[>] `, `[?] ` —
/// as the glyph and its style. `[ ]` and `[x]` never get here: pulldown
/// turns those into `TaskListMarker` events.
fn other_task(src: &str) -> Option<(&'static str, Style)> {
    let rest = src.strip_prefix('[')?;
    let c = rest.chars().next()?;
    if matches!(c, ' ' | 'x' | 'X') || !rest[c.len_utf8()..].starts_with("] ") {
        return None;
    }
    crate::md::task_state(c)
}

/// 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(_)
    )
}

/// The byte offset, from `base`, at which each char of `chars` starts, plus
/// one past the last — so a run over chars can name where it sat in the source.
fn byte_offsets(chars: &[char], base: usize) -> Vec<usize> {
    let mut v = Vec::with_capacity(chars.len() + 1);
    let mut b = base;
    for ch in chars {
        v.push(b);
        b += ch.len_utf8();
    }
    v.push(b);
    v
}

#[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})");
                    }
                }
            }
        }
    }

    /// The whole path, from a fence to a picture on the page.
    #[test]
    fn a_flowchart_fence_reaches_the_page_as_rows_and_not_as_code() {
        let md = "```mermaid\nflowchart LR\n  A[Start] --> B[End]\n```\n";
        let flat = flat(&render_wide(md, 60));
        assert!(!flat.contains("◇ mermaid"), "{flat}");
        assert!(flat.contains("Start") && flat.contains("End"), "{flat}");
        assert!(flat.contains(''), "{flat}");
    }

    /// A diagram built by hand, drawn onto a page of `width` columns.
    ///
    /// The flow and sequence builders are their own piece of work; the reading
    /// view's share is the styling, the `wide` flag and the decoration a quote
    /// or a callout puts around a row, and none of the three care what drew the
    /// rows. `boxed` puts the page inside a callout card.
    fn page_of(d: &crate::mermaid::Rendered, width: usize, boxed: bool) -> Rendered {
        let mut r = Ren::new("", 0, width, TableStyle::default());
        if boxed {
            r.boxed = true;
            r.box_w = width;
        }
        r.emit_diagram(d);
        r.finish()
    }

    #[test]
    fn a_mermaid_fence_is_drawn_as_a_picture_in_the_reading_view() {
        use crate::mermaid::{Rendered as Diagram, Role, Run};
        let d = Diagram::new(vec![
            vec![Run::new("╭───────╮", Role::Line)],
            vec![
                Run::new("", Role::Line),
                Run::new("Start", Role::Node),
                Run::new("", Role::Line),
            ],
        ]);
        let page = page_of(&d, 40, false);
        assert_eq!(flat(&page), "╭───────╮\n│ Start │");
        // the palette, through the one mapping both views share: the words the
        // author wrote in the body colour, the scaffolding in the marker one
        let start = page.lines[1].cells.iter().find(|c| c.ch == 'S').unwrap();
        assert_eq!(start.style, theme::PLAIN);
        assert_eq!(page.lines[0].cells[0].style, theme::marker());
        // and never the accent, which the note spends on its headings
        assert!(page
            .lines
            .iter()
            .all(|l| l.cells.iter().all(|c| c.style != theme::state())));
        assert!(page.lines.iter().all(|l| !l.wide));
    }

    #[test]
    fn a_mermaid_fence_catcher_cannot_draw_keeps_its_source_under_a_label() {
        let r = render_wide("```mermaid\ngantt\n  title Ship it\n```\n", 40);
        let flat = flat(&r);
        assert!(flat.contains("◇ mermaid"), "{flat}");
        // the source is still there, indented the way any code block is
        assert!(flat.contains("  gantt"), "{flat}");
        assert!(flat.contains("    title Ship it"), "{flat}");
        // a label, not a card: the callout box is the app's one boxed
        // construct, and the label is chrome rather than accent
        assert!(!flat.contains(''));
        let label = r.lines.iter().find(|l| l.text().contains('')).unwrap();
        assert!(label.cells.iter().all(|c| c.style == theme::marker()));
    }

    #[test]
    fn the_label_names_the_diagram_kind_and_not_just_mermaid() {
        assert!(flat(&render_wide("```mermaid\ngantt\n```\n", 40)).contains("◇ mermaid · gantt"));
        // a comment above the header does not hide what the diagram is
        let commented = "```mermaid\n%% mine\nclassDiagram\n```\n";
        assert!(flat(&render_wide(commented, 40)).contains("◇ mermaid · classDiagram"));
        // and a fence with nothing in it to name says only what it is
        let empty = flat(&render_wide("```mermaid\n\n```\n", 40));
        assert!(empty.contains("◇ mermaid"));
        assert!(!empty.contains('·'));
    }

    #[test]
    fn a_diagram_wider_than_the_page_is_marked_wide_so_the_page_pans() {
        use crate::mermaid::{Rendered as Diagram, Role, Run};
        let d = Diagram::new(vec![
            vec![Run::new("".repeat(60), Role::Line)],
            vec![Run::new("short", Role::Node)],
        ]);
        let page = page_of(&d, 20, false);
        // nothing is cut and nothing is wrapped: the row is left whole and the
        // page pans across it, exactly as it does for a wide table
        assert!(page.lines[0].wide);
        assert_eq!(cells_width(&page.lines[0].cells), 60);
        assert!(!page.lines[1].wide);
    }

    #[test]
    fn a_diagram_inside_a_callout_keeps_its_rail() {
        use crate::mermaid::{Rendered as Diagram, Role, Run};
        let d = Diagram::new(vec![vec![Run::new("A ─▶ B", Role::Line)]]);
        let page = page_of(&d, 20, true);
        assert_eq!(flat(&page), "│ A ─▶ B           │");
        // a wide row is left bare instead: its edges would pan off with it
        let wide = Diagram::new(vec![vec![Run::new("".repeat(40), Role::Line)]]);
        assert_eq!(flat(&page_of(&wide, 20, true)), "".repeat(40));
    }

    #[test]
    fn a_fence_that_only_looks_like_mermaid_is_still_code() {
        let flat = flat(&render_wide("```mermaidjs\ngraph TD\n```\n", 40));
        assert!(!flat.contains(''), "{flat}");
        assert!(flat.contains("  graph TD"), "{flat}");
    }

    #[test]
    fn an_undrawn_diagram_keeps_the_source_columns_a_click_needs() {
        let md = "# T\n\n```mermaid\ngantt\n  title Ship it\n```\n";
        let src_lines: Vec<&str> = md.lines().collect();
        for line in &render_wide(md, 40).lines {
            for c in &line.cells {
                // every mapped cell still points at its own character, so a
                // click in a diagram we did not draw lands where it was aimed
                if let Some((l, col)) = c.src {
                    assert_eq!(src_lines[l].chars().nth(col), Some(c.ch), "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 ordered_lists_keep_their_numbers() {
        let r = render("3. three\n4. four\n   - sub\n5. five\n\n- plain\n");
        let f = flat(&r);
        assert!(f.contains("3. three\n4. four\n  ◦ sub\n5. five"), "{f}");
        assert!(f.contains("• plain"), "{f}");
    }

    #[test]
    fn bullet_glyph_follows_nesting_depth() {
        let r = render("- one\n  - two\n    - three\n      - four\n  - two again\n- one again\n");
        let f = flat(&r);
        assert!(
            f.contains("• one\n  ◦ two\n    ▪ three\n      • four\n  ◦ two again\n• one again"),
            "{f}"
        );
    }

    #[test]
    fn nested_task_items_keep_their_boxes() {
        let r = render("- [ ] top\n  - [x] nested\n  - plain\n");
        let f = flat(&r);
        assert!(f.contains("☐ top\n  ✓ nested\n  ◦ plain"), "{f}");
    }

    #[test]
    fn wrapped_list_item_hangs_under_its_text() {
        let r = render_wide("1. alpha beta gamma delta epsilon zeta\n", 20);
        let item = r
            .lines
            .iter()
            .find(|l| l.text().starts_with("1. "))
            .unwrap();
        assert_eq!(item.hang, 3);
        let rows: Vec<String> = wrap_pline(item, 20)
            .iter()
            .map(|c| c.iter().map(|x| x.ch).collect())
            .collect();
        assert!(rows.len() > 1, "{rows:?}");
        assert!(rows[0].starts_with("1. alpha"), "{rows:?}");
        assert!(
            rows[1].starts_with("   ") && !rows[1].starts_with("    "),
            "{rows:?}"
        );
    }

    #[test]
    fn rule_spans_the_page() {
        let r = render_wide("a\n\n---\n\nb\n", 60);
        assert!(
            r.lines.iter().any(|l| l.text() == "".repeat(60)),
            "{}",
            flat(&r)
        );
    }

    #[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 footnotes_and_maths_render_on_the_page() {
        let r = render_wide(
            "Tea[^1] and $x$.\n\n$$\nE = mc^2\n$$\n\n[^1]: Tickles\n",
            20,
        );
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(rows.iter().any(|t| t == "Tea¹ and x."), "{rows:?}");
        assert!(
            rows.iter()
                .any(|t| t.trim() == "E = mc^2" && t.starts_with("     ")),
            "{rows:?}"
        );
        assert!(rows.iter().any(|t| t == "¹ Tickles"), "{rows:?}");
        assert!(
            rows.iter()
                .all(|t| !t.contains("[^1]") && !t.contains("$$")),
            "{rows:?}"
        );
    }

    #[test]
    fn inline_footnotes_render_numbered_with_their_definitions() {
        let md = "Tea[^1] and^[Milk too] then^[Sugar].\n\n[^1]: Black\n";
        let r = render_wide(md, 40);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(rows.iter().any(|t| t == "Tea¹ and² then³."), "{rows:?}");
        assert!(rows.iter().any(|t| t == "¹ Black"), "{rows:?}");
        assert!(rows.iter().any(|t| t == "² Milk too"), "{rows:?}");
        assert!(rows.iter().any(|t| t == "³ Sugar"), "{rows:?}");
        assert!(
            rows.iter().all(|t| !t.contains('~') && !t.contains("^[")),
            "{rows:?}"
        );
        // the definitions come after the reference footnotes, in order
        let at = |s: &str| rows.iter().position(|t| t == s).unwrap();
        assert!(at("¹ Black") < at("² Milk too") && at("² Milk too") < at("³ Sugar"));
    }

    #[test]
    fn an_inline_footnote_maps_back_to_the_line_it_was_written_on() {
        let md = "Tea[^1] and^[Milk too] then^[Sugar].\n\n[^1]: Black\n";
        let r = render_page_at(md, 5, 40, TableStyle::default());
        // text after the note keeps its true column: the rewrite is the same
        // length as what it replaced
        let first = r
            .lines
            .iter()
            .find(|l| l.text().starts_with("Tea"))
            .unwrap();
        let t = first.cells.iter().find(|c| c.ch == 't').unwrap();
        assert_eq!(t.src, Some((5, 23)));
        // the appended definition belongs to the line the `^[…]` is on, and
        // its text to the columns inside the brackets
        let milk = r.lines.iter().find(|l| l.text() == "² Milk too").unwrap();
        assert_eq!(milk.src_line, Some(5));
        let m = milk.cells.iter().find(|c| c.ch == 'M').unwrap();
        assert_eq!(m.src, Some((5, 13)));
        let sugar = r.lines.iter().find(|l| l.text() == "³ Sugar").unwrap();
        assert_eq!(sugar.src_line, Some(5));
        // the real definition still maps to its own line
        let black = r.lines.iter().find(|l| l.text() == "¹ Black").unwrap();
        assert_eq!(black.src_line, Some(7));
    }

    #[test]
    fn escaped_and_commented_footnotes_are_not_numbered() {
        let r = render("\\^[lit] B^[two]\n");
        assert_eq!(r.lines[0].text(), "^[lit] B¹");
        let r = render("%% ^[hidden] %%\nA^[one]\n");
        assert_eq!(r.lines[0].text(), "");
    }

    #[test]
    fn a_footnote_in_a_callout_title_is_a_superscript() {
        let r = render_wide("> [!note] T^[c1]\n> body\n", 40);
        let top = r.lines[0].text();
        assert!(top.contains(""), "{top:?}");
        assert!(!top.contains("[^"), "{top:?}");
    }

    #[test]
    fn inline_footnotes_count_with_word_labels_and_skip_fences() {
        // a word label stays a word; the inline note after it is number two,
        // and a note shorter than its label still renders
        let r = render("x[^note] y^[z]\n\n[^note]: def\n");
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(rows.iter().any(|t| t == "x^note y²"), "{rows:?}");
        assert!(rows.iter().any(|t| t == "² z"), "{rows:?}");
        assert!(rows.iter().any(|t| t == "^note def"), "{rows:?}");
        // fenced code is left as typed
        let r = render("```\n^[not a note]\n```\n");
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(rows.iter().any(|t| t.contains("^[not a note]")), "{rows:?}");
        assert!(rows.iter().all(|t| !t.contains('¹')), "{rows:?}");
        // a note with none is untouched by the rewrite
        let (out, notes) = inline_footnotes("plain [^1]\n\n[^1]: x\n");
        assert_eq!(out, "plain [^1]\n\n[^1]: x\n");
        assert!(notes.is_empty());
    }

    #[test]
    fn the_rewrite_keeps_the_line_and_names_the_text_it_moved() {
        let (out, notes) = inline_footnotes("a^[bc] d");
        assert_eq!(out, "a[^~1] d\n\n[^~1]: bc\n");
        assert_eq!(notes.len(), 1);
        let n = &notes[0];
        assert_eq!(
            (n.label.as_str(), n.ordinal, n.orig, n.len),
            ("~1", 1, 3, 2)
        );
        assert_eq!(&out[n.def..n.def + n.len], "bc");
        assert_eq!(n.tail_len, "\n[^~1]: bc\n".len());
        // a longer text pads the label to its own length
        let (out, _) = inline_footnotes("^[four] tail\n");
        assert_eq!(out, "[^~1~~] tail\n\n[^~1~~]: four\n");
    }

    #[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 a_callout_inside_a_callout_is_a_nested_card() {
        let md = "> [!note] Outer\n> a\n>\n> > [!tip] Inner\n> > b\n>\n> c\n";
        let w = 40;
        let r = render_wide(md, w);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let outer = rows
            .iter()
            .position(|t| t.starts_with("╭─ i note · Outer"))
            .expect("outer top");
        let inner = rows
            .iter()
            .position(|t| t.starts_with("│ ╭─ ✓ tip · Inner"))
            .expect("inner top");
        assert!(inner > outer);
        assert!(rows[inner].ends_with("╮ │"), "{:?}", rows[inner]);
        let b = rows.iter().find(|t| t.contains(" b ")).expect("inner body");
        assert!(b.starts_with("│ │ b") && b.ends_with("│ │"), "{b:?}");
        let inner_close = rows
            .iter()
            .position(|t| t.starts_with("│ ╰"))
            .expect("inner bottom");
        assert!(
            inner_close > inner && rows[inner_close].ends_with("╯ │"),
            "{:?}",
            rows[inner_close]
        );
        let c = rows
            .iter()
            .position(|t| t.starts_with("│ c"))
            .expect("outer body after");
        assert!(c > inner_close);
        let outer_close = rows.iter().rposition(|t| t.starts_with('')).unwrap();
        assert!(outer_close > c);
        for t in &rows[outer..=outer_close] {
            assert_eq!(crate::md::str_width(t), w, "{t:?}");
        }
        // the inner card's edges answer to its title line, the outer's to its own
        assert_eq!(r.lines[inner_close].src_line, Some(3));
        assert_eq!(r.lines[outer_close].src_line, Some(0));
    }

    #[test]
    fn a_foldable_callout_shows_its_state_in_the_reading_view() {
        let md = "> [!tip]- Go\n> a\n> b\n\nafter\n";
        // open, the marker says it can fold
        let open = folded(md, &[], 30);
        let rows: Vec<String> = open.lines.iter().map(|l| l.text()).collect();
        assert!(
            rows.iter().any(|t| t.starts_with("╭─ ▾ ✓ tip · Go")),
            "{rows:?}"
        );
        // folded, the body is gone and the edge sits right under the title
        let r = folded(md, &[0], 30);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let top = rows.iter().position(|t| t.starts_with('')).expect("top");
        assert_eq!(rows[top], "╭─ ▸ ✓ tip · Go ─── 2 lines ─╮");
        assert!(rows[top + 1].starts_with(''), "{rows:?}");
        assert!(
            rows.iter()
                .all(|t| !t.contains(" a ") && !t.contains(" b ")),
            "{rows:?}"
        );
        assert!(rows.iter().any(|t| t == "after"));
        // a callout with no marker folds too, and keeps its width doing so
        let r = folded("> [!tip] Go\n> a\n", &[0], 30);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let top = rows.iter().find(|t| t.starts_with('')).unwrap();
        assert_eq!(top, "╭─ ▸ ✓ tip · Go ──── 1 line ─╮");
    }

    #[test]
    fn a_folded_callout_with_a_paragraph_break_closes_right_under_its_title() {
        // the blank `>` line becomes a `│   │` spacer row with no source
        // line: the fold must take it too, and the bottom edge must not be
        // marked as a folded heading (`▸ ╰──╯`, two columns too wide)
        let md = "> [!note]- O\n> a\n>\n> b\n\nafter\n";
        let r = folded(md, &[0], 40);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let top = rows.iter().position(|t| t.starts_with('')).expect("top");
        assert!(rows[top + 1].starts_with(''), "{rows:?}");
        for t in &rows {
            assert!(crate::md::str_width(t) <= 40, "{t:?}");
        }
        // the same for an outer card whose fold takes a nested card with it
        let md = "> [!note] O\n> a\n>\n> > [!tip] I\n> > b\n>\n> d\n";
        let r = folded(md, &[0], 40);
        let rows: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(rows[1].starts_with(''), "{rows:?}");
        assert_eq!(rows.len(), 2, "{rows:?}");
    }

    #[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 kbd_reads_as_inline_code_and_its_tags_vanish() {
        let r = render("Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy.");
        assert_eq!(r.lines[0].text(), "Press Ctrl+C to copy.");
        let line = &r.lines[0];
        let t = line.cells.iter().find(|c| c.ch == 't').unwrap();
        assert_eq!(t.style.fg, theme::inline_code().fg);
        // the key cap's cells still know where they came from
        assert_eq!(t.src, Some((0, 12)));
        let plus = line.cells.iter().find(|c| c.ch == '+').unwrap();
        assert_eq!(plus.style.fg, None);
        // and a key cap in a table cell
        let r = render("| a | b |\n|---|---|\n| <kbd>x</kbd> | y |\n");
        let f = flat(&r);
        assert!(f.contains('x') && !f.contains('<'), "{f:?}");
    }

    #[test]
    fn sub_and_sup_take_their_unicode_forms() {
        let r = render("H<sub>2</sub>O is x<sup>2</sup> or x<sup>(n+1)</sup>");
        assert_eq!(r.lines[0].text(), "H₂O is x² or x⁽n⁺¹⁾");
        let two = r.lines[0].cells.iter().find(|c| c.ch == '').unwrap();
        assert_eq!(two.src, Some((0, 6)));
        // what follows the subscript sits at its true column, not three bytes off
        let o = r.lines[0].cells.iter().find(|c| c.ch == 'O').unwrap();
        assert_eq!(o.src, Some((0, 13)));
    }

    #[test]
    fn u_underlines_and_mark_highlights_in_the_page() {
        let r = render("<u>under</u> and <mark>lit</mark> and **<u>both</u>**");
        assert_eq!(r.lines[0].text(), "under and lit and both");
        let cells = &r.lines[0].cells;
        let u = cells.iter().find(|c| c.ch == 'r').unwrap();
        assert!(u.style.add_modifier.contains(Modifier::UNDERLINED));
        let m = cells.iter().find(|c| c.ch == 'l').unwrap();
        assert_eq!(m.style.bg, theme::highlight().bg);
        let b = cells.iter().find(|c| c.ch == 'h').unwrap();
        assert!(b.style.add_modifier.contains(Modifier::UNDERLINED));
        assert!(b.style.add_modifier.contains(Modifier::BOLD));
        // the plain prose between them is untouched
        let a = cells.iter().find(|c| c.ch == 'a').unwrap();
        assert_eq!(a.style, Style::default());
    }

    #[test]
    fn br_breaks_the_line_the_way_a_hard_break_does() {
        let r = render("one<br>two<br/>three");
        assert_eq!(texts(&r), vec!["one", "two", "three"]);
        // in a table cell it is a space, like a soft break
        let r = render("| a |\n|---|\n| x<br>y |\n");
        assert!(flat(&r).contains("x y"), "{:?}", flat(&r));
    }

    #[test]
    fn comments_are_dropped_inline_and_as_blocks() {
        let md =
            "a <!-- hush --> b\n\n<!-- block\nstill hidden -->\n\nafter <!-- multi\nline --> end\n";
        let r = render(md);
        let f = flat(&r);
        assert!(
            !f.contains("hush") && !f.contains("hidden") && !f.contains("line"),
            "{f:?}"
        );
        assert!(f.contains("a  b"), "{f:?}");
        assert!(f.contains("after  end"), "{f:?}");
        assert!(!f.contains("<!--") && !f.contains("-->"), "{f:?}");
    }

    #[test]
    fn unknown_tags_are_stripped_and_their_text_kept() {
        let r = render(
            "<div class=\"x\">\nhello <b>there</b>\n</div>\n\n<span>after</span> <i>x</i>\n",
        );
        let t = texts(&r);
        assert!(t.iter().any(|l| l == "hello there"), "{t:?}");
        assert!(t.iter().any(|l| l == "after x"), "{t:?}");
        assert!(t.iter().all(|l| !l.contains('<')), "{t:?}");
        // the block's text maps back to its source line
        let hello = r.lines.iter().find(|l| l.text() == "hello there").unwrap();
        assert_eq!(hello.src_line, Some(1));
        assert_eq!(hello.cells[0].src, Some((1, 0)));
    }

    #[test]
    fn an_unclosed_tag_does_not_leak_past_its_paragraph() {
        let r = render("<u>open\n\nnext\n\n- <mark>item\n- other\n");
        let next = r.lines.iter().find(|l| l.text() == "next").unwrap();
        assert!(!next.cells[0]
            .style
            .add_modifier
            .contains(Modifier::UNDERLINED));
        let other = r.lines.iter().find(|l| l.text().contains("other")).unwrap();
        let o = other.cells.iter().find(|c| c.ch == 'h').unwrap();
        assert_eq!(o.style.bg, None);
        let r = render("a < b and c > d");
        assert_eq!(r.lines[0].text(), "a < b and c > d");
    }

    #[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);
    }

    #[test]
    fn numbered_tasks_keep_their_number_in_front_of_the_box() {
        let r = render("1. [ ] todo\n2. [x] done\n");
        let todo = r.lines.iter().find(|l| l.text().contains("todo")).unwrap();
        assert_eq!(todo.text(), "1. ☐ todo");
        assert_eq!(todo.checkbox, Some(0));
        let done = r.lines.iter().find(|l| l.text().contains("done")).unwrap();
        assert_eq!(done.text(), "2. ✓ done");
        assert_eq!(done.checkbox, Some(1));
        let d = done.cells.iter().find(|c| c.ch == 'd').unwrap();
        assert!(d.style.add_modifier.contains(Modifier::CROSSED_OUT));
        // a wrapped numbered task hangs under its text, past number and box
        assert_eq!(todo.hang, 5);
        let plain = render("- [ ] todo\n");
        assert_eq!(plain.lines[0].hang, 2);
    }

    #[test]
    fn the_other_task_states_render_as_glyphs_with_a_clickable_box() {
        let r = render(
            "- [/] going\n- [-] dropped\n- [>] later\n- [?] maybe **x**\n- [z] plain\n1. [/] first\n\n- [/] loose\n\n- b\n",
        );
        let line = |s: &str| r.lines.iter().find(|l| l.text().contains(s)).unwrap();
        let going = line("going");
        assert_eq!(going.text(), format!("{} going", theme::IN_PROGRESS));
        assert_eq!(going.checkbox, Some(0));
        assert_eq!(going.cells[0].style.fg, theme::done().fg);
        // the text keeps its own source columns, so a click lands in it
        assert_eq!(going.cells[2].src, Some((0, 6)));
        let dropped = line("dropped");
        assert_eq!(dropped.text(), format!("{} dropped", theme::CANCELLED));
        assert_eq!(dropped.checkbox, Some(1));
        assert_eq!(dropped.cells[0].style.fg, theme::marker().fg);
        let d = dropped.cells.iter().find(|c| c.ch == 'd').unwrap();
        assert!(d.style.add_modifier.contains(Modifier::CROSSED_OUT));
        // the struck style ends with the item
        let later = line("later");
        assert_eq!(later.text(), format!("{} later", theme::FORWARDED));
        assert_eq!(later.cells[0].style.fg, theme::forwarded().fg);
        let struck = |l: &PLine| {
            l.cells
                .iter()
                .any(|c| c.style.add_modifier.contains(Modifier::CROSSED_OUT))
        };
        assert!(!struck(later));
        let maybe = line("maybe");
        assert_eq!(maybe.text(), format!("{} maybe x", theme::QUESTION));
        let x = maybe.cells.last().unwrap();
        assert!(x.style.add_modifier.contains(Modifier::BOLD));
        // an unknown state is text, and not a box to click
        let plain = line("plain");
        assert_eq!(plain.text(), format!("{} [z] plain", theme::BULLET));
        assert_eq!(plain.checkbox, None);
        // numbered and loose items take the states too
        let first = line("first");
        assert_eq!(first.text(), format!("1. {} first", theme::IN_PROGRESS));
        assert_eq!(first.checkbox, Some(5));
        let loose = line("loose");
        assert_eq!(loose.text(), format!("{} loose", theme::IN_PROGRESS));
        assert_eq!(loose.checkbox, Some(7));
        let bullet = format!("{} b", theme::BULLET);
        assert!(r.lines.iter().any(|l| l.text() == bullet));
        assert_eq!(loose.hang, 2);
    }

    /// 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 the_properties_box_folds_to_a_line_or_to_nothing() {
        use crate::config::Properties;
        let content = "---\ntitle: Launch\ndue: 2026-10-10\ntags: [work]\n---\n# Title\n";
        // the box's top edge says `hide` and answers a click
        let mut r = body_of(content);
        prepend_properties(&mut r, content, 40, (2026, 9, 5), Properties::Box);
        let top = &r.lines[0];
        assert!(top.text().ends_with(" hide ┐"), "{:?}", top.text());
        assert_eq!(top.text().chars().count(), 40);
        let link = top.cells[0].link.expect("edge is clickable");
        assert_eq!(r.url(link), Some(PROPERTIES_HREF));
        assert!(top.cells.iter().all(|c| c.link == Some(link)));
        // the line: a fold glyph, a count, no tags, one click back
        let mut r = body_of(content);
        prepend_properties(&mut r, content, 40, (2026, 9, 5), Properties::Line);
        assert_eq!(r.lines[0].text(), "▸ 3 properties");
        assert_eq!(r.lines[1].text(), "");
        assert_eq!(r.lines[2].text(), "Title");
        let link = r.lines[0].cells[0].link.expect("line is clickable");
        assert_eq!(r.url(link), Some(PROPERTIES_HREF));
        // hide: nothing at all
        let mut r = body_of(content);
        let before = r.lines.len();
        prepend_properties(&mut r, content, 40, (2026, 9, 5), Properties::Hide);
        assert_eq!(r.lines.len(), before);
        assert_eq!(r.lines[0].text(), "Title");
    }

    #[test]
    fn front_matter_is_drawn_as_a_box_of_properties_above_the_body() {
        let content = "---\ntitle: Launch\ndue: 2026-10-10\ntags: [work, q3]\naliases:\n  - launch\n  - go live\n---\n# Title\n";
        let mut r = body_of(content);
        prepend_properties(
            &mut r,
            content,
            60,
            (2026, 9, 5),
            crate::config::Properties::Box,
        );
        let page: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(page[0].starts_with("┌ properties ─"));
        assert!(page[0].ends_with(''));
        assert_eq!(page[0].chars().count(), 60);
        assert!(page[1].starts_with("│ title    Launch"));
        assert!(page[1].ends_with(''));
        assert!(page[2].contains("due      2026-10-10  in 5 weeks"));
        assert!(page[3].contains("tags     #work #q3"));
        assert!(page[4].contains("aliases  launch · go live"));
        assert!(page[5].starts_with('') && page[5].ends_with(''));
        assert_eq!(page[6], "");
        assert!(page[7].contains("Title"));
        // each row knows the line its key is on; the frame knows none
        assert_eq!(r.lines[0].src_line, None);
        assert_eq!(r.lines[1].src_line, Some(1));
        assert_eq!(r.lines[4].src_line, Some(4));
        // a tag is a click away from the notes that carry it
        let tag = r.lines[3].cells.iter().find(|c| c.ch == '#').unwrap();
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(tag.link.unwrap()).unwrap()),
            crate::md::LinkTarget::Tag("work".to_string())
        );
        assert_eq!(tag.style.fg, theme::tag().fg);
        // and a note without front matter is left exactly as it was
        let mut plain = body_of("# Title\n");
        prepend_properties(
            &mut plain,
            "# Title\n",
            60,
            (2026, 9, 5),
            crate::config::Properties::Box,
        );
        assert!(plain.lines[0].text().contains("Title"));
    }

    #[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_tag_is_drawn_in_the_accent_and_records_a_tag_target() {
        crate::md::tags::set_enabled(true);
        let r = render("see #work now\n");
        assert_eq!(flat(&r).trim(), "see #work now");
        let cell = r.lines[0].cells.iter().find(|c| c.link.is_some()).unwrap();
        assert_eq!(cell.ch, '#');
        assert_eq!(cell.style.fg, theme::tag().fg);
        assert_eq!(r.url(cell.link.unwrap()), Some("tag:work"));
    }

    #[test]
    fn a_tag_in_code_a_heading_marker_or_a_url_is_not_recorded() {
        crate::md::tags::set_enabled(true);
        let r = render("# Title\n\n`#code` and https://x.y/#frag and x#y\n\n```\n#fence\n```\n");
        assert!(
            r.urls.iter().all(|u| !u.starts_with("tag:")),
            "{:?}",
            r.urls
        );
        // and the one right after a code span is not one either: the char
        // before it is a backtick, whatever pulldown split the events on
        let r = render("`x`#glued\n");
        assert!(r.urls.is_empty());
        let r = render("`x` #free\n");
        assert_eq!(r.urls, vec!["tag:free"]);
    }

    #[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; the heading travels with the
        // target so the follower can land on it
        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#Method"));
    }

    #[test]
    fn a_heading_link_reads_note_chevron_heading_and_keeps_its_source_columns() {
        let r = render("see [[note#Method]] now\n");
        assert_eq!(flat(&r).trim(), "see note › Method now");
        assert_eq!(r.url(0), Some("wikilink:note#Method"));
        let cells = &r.lines[0].cells;
        // the chevron is the page's, mapping to no source; the words either
        // side keep their true columns, so a click lands inside the link
        let n = cells
            .iter()
            .position(|c| c.ch == 'n' && c.link.is_some())
            .unwrap();
        assert_eq!(cells[n].src, Some((0, 6)));
        let chevron = cells.iter().find(|c| c.ch == '').unwrap();
        assert_eq!(chevron.src, None);
        assert!(chevron.link.is_some());
        let m = cells.iter().position(|c| c.ch == 'M').unwrap();
        assert_eq!(cells[m].src, Some((0, 11)));
        // a block reference, and a link to a heading in this note
        assert_eq!(flat(&render("[[note#^abc]]\n")).trim(), "note › ^abc");
        let r = render("[[#Method]]\n");
        assert_eq!(flat(&r).trim(), "› Method");
        assert_eq!(r.url(0), Some("wikilink:#Method"));
    }

    #[test]
    fn a_trailing_block_id_is_not_drawn_on_the_page() {
        let r = render("a paragraph ^abc\n\n- item ^def-1\n\n# Title ^h1\n");
        let text = flat(&r);
        assert!(!text.contains('^'), "{text}");
        assert!(text.contains("a paragraph"));
        assert!(text.contains("Title"));
        // blanked, not cut: what follows keeps its line
        assert_eq!(blank_block_ids("x ^abc\ny\n"), "x     \ny\n");
        assert_eq!(blank_block_ids("^abc\n"), "    \n");
        // a caret inside a fence is code and stays
        assert_eq!(blank_block_ids("```\nx ^abc\n```\n"), "```\nx ^abc\n```\n");
        let r = render("```\ncode ^abc\n```\n");
        assert!(flat(&r).contains("code ^abc"));
        // and a paragraph carrying one still maps its cells to its own line
        let r = render("first\n\nsecond ^abc\n");
        let line = r
            .lines
            .iter()
            .find(|l| l.text().contains("second"))
            .unwrap();
        assert_eq!(line.src_line, Some(2));
    }

    #[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 an_attachment_embed_is_a_card_for_the_desktop() {
        let r = render("![[report.pdf|the report]]\n");
        let line = r.lines.iter().find(|l| l.text().contains("📎")).unwrap();
        assert_eq!(line.text(), "▌ 📎 the report (no such file)");
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(0).unwrap()),
            crate::md::LinkTarget::File("report.pdf".into())
        );
        // in a sentence, an attachment link is still a link — to the file
        let r = render("see [[board.canvas]] now\n");
        assert_eq!(
            crate::md::LinkTarget::parse(r.url(0).unwrap()),
            crate::md::LinkTarget::File("board.canvas".into())
        );
    }

    #[test]
    fn an_obsidian_embed_is_an_image_in_the_reading_view() {
        let r = render("before\n\n![[attachments/hero.jpg|the hero]]\n\nafter\n");
        let line = r.lines.iter().find(|l| l.image.is_some()).unwrap();
        assert_eq!(
            r.images[line.image.unwrap()],
            ImageSpec {
                alt: "the hero".into(),
                url: "attachments/hero.jpg".into(),
                width: None,
            }
        );
        assert_eq!(line.text(), "🖼 the hero (attachments/hero.jpg)");
        // nothing of the source syntax leaks out after the picture
        let all: String = r
            .lines
            .iter()
            .map(|l| l.text())
            .collect::<Vec<_>>()
            .join("|");
        assert!(!all.contains("]]") && !all.contains("![["), "{all}");
        assert!(all.contains("after"));
        // a note embed is not a picture: it is a card (see the embed tests)
        let r = render("![[plan]]\n");
        assert!(r.lines.iter().all(|l| l.image.is_none()));
        assert!(r
            .lines
            .iter()
            .any(|l| l.text().to_lowercase().contains("▌ plan")));
    }

    #[test]
    fn a_note_embed_is_a_card_in_the_reading_view() {
        let _turn = crate::md::embeds::turn();
        let dir = crate::testutil::tmpdir("render", "embed-card");
        crate::testutil::write(
            &dir,
            "plan.md",
            "# Plan\n\nFirst **line**.\n\n## Goals\n- ship it\n- test it\n- doc it\n- more\n\n## Later\nNothing.\n",
        );
        crate::md::embeds::install_dir(&dir);

        let r = render("before\n\n![[plan#Goals]]\n\nafter\n");
        let texts: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        let at = texts
            .iter()
            .position(|t| t == "▌ Plan › Goals")
            .expect("a title row");
        assert_eq!(
            &texts[at..at + 5],
            &[
                "▌ Plan › Goals",
                "▌ - ship it",
                "▌ - test it",
                "▌ - doc it",
                "▌ 1 more line"
            ]
        );
        // the title is a link to the note, in the callout colour
        let title = &r.lines[at];
        assert_eq!(title.cells[0].style.fg, theme::callout("note").fg);
        let linked = title.cells.iter().find(|c| c.link.is_some()).unwrap();
        assert_eq!(r.url(linked.link.unwrap()), Some("wikilink:plan"));
        assert!(linked.style.add_modifier.contains(Modifier::BOLD));
        // the body reads in normal text, inline markup drawn
        let r = render("![[plan]]\n");
        let texts: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert_eq!(texts[0], "▌ Plan");
        assert_eq!(texts[1], "▌ First line.");
        assert!(r.lines[1].cells[8]
            .style
            .add_modifier
            .contains(Modifier::BOLD));
        assert!(texts.iter().all(|t| !t.contains("]]")), "{texts:?}");
        assert_eq!(texts.last().unwrap(), "▌ 5 more lines");

        // no such note
        let r = render("![[gone]]\n");
        assert_eq!(r.lines[0].text(), "▌ gone (no such note)");
        assert_eq!(r.lines[0].cells[2].style.fg, theme::grey().fg);
        assert_eq!(r.lines.len(), 1);
        crate::md::embeds::forget();
    }

    #[test]
    fn an_embedded_note_in_a_sentence_is_a_link_in_the_reading_view() {
        let r = render("see ![[plan#Goals]] and ![[plan|the plan]] now\n");
        assert_eq!(flat(&r).trim(), "see plan › Goals and the plan now");
        assert_eq!(r.urls, vec!["wikilink:plan", "wikilink:plan"]);
        // the label's cells keep their source columns: the "p" of plan
        let cell = r.lines[0].cells.iter().find(|c| c.link.is_some()).unwrap();
        assert_eq!(cell.ch, 'p');
        assert_eq!(cell.src, Some((0, "see ![[".len())));
        // a picture in a sentence is still text
        let r = render("see ![[y.png]] now\n");
        assert!(flat(&r).contains("![[y.png]]"));
        assert!(r.urls.is_empty());
    }

    #[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(),
                width: None,
            }
        );
    }

    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,
            linked: true,
        }
    }

    /// An unlinked mention: `word` is where the title was said in `excerpt`.
    fn unlinked(name: &str, excerpt: &str, word: &str) -> crate::mentions::Mention {
        let at = excerpt
            .find(word)
            .map(|b| excerpt[..b].chars().count())
            .unwrap_or(0);
        let mut m = mention(name, excerpt, 1);
        m.link = (at, at + word.chars().count());
        m.linked = false;
        m
    }

    #[test]
    fn unlinked_mentions_are_a_second_section_with_the_matched_words_undimmed() {
        let mut r = render("# Spec\n");
        append_mentions(
            &mut r,
            &[
                mention("meta", "about [[spec]]", 1),
                unlinked("plan", "the spec says so", "spec"),
            ],
            60,
        );
        let text: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(text.iter().any(|t| t == "1 note links here"));
        assert!(text.iter().any(|t| t == "mentioned in 1 note"), "{text:?}");
        let row = footer_row(&r, "plan");
        // the name is a link to the exact file, as in the linked section
        let p = row.cells.iter().find(|c| c.ch == 'p').unwrap();
        assert_eq!(r.url(p.link.unwrap()), Some("note:/vault/plan.md"));
        // "the " is dim, "spec" is not
        let t = row.cells.iter().find(|c| c.ch == 't').unwrap();
        assert_eq!(t.style, theme::marker());
        let s = row
            .cells
            .iter()
            .find(|c| c.ch == 's' && c.link.is_none())
            .unwrap();
        assert_eq!(s.style, theme::PLAIN);
        // with nothing linking here, only the second section is drawn
        let mut r = render("# Spec\n");
        append_mentions(&mut r, &[unlinked("plan", "the spec says so", "spec")], 60);
        let text: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(!text.iter().any(|t| t.contains("link here")));
        assert!(text.iter().any(|t| t == "mentioned in 1 note"));
    }

    #[test]
    fn the_unlinked_section_stops_at_twenty_rows_and_counts_the_rest() {
        let mut r = render("# Spec\n");
        let rows: Vec<_> = (0..25)
            .map(|i| unlinked(&format!("n{i:02}"), "the spec", "spec"))
            .collect();
        append_mentions(&mut r, &rows, 60);
        let text: Vec<String> = r.lines.iter().map(|l| l.text()).collect();
        assert!(text.iter().any(|t| t == "mentioned in 25 notes"));
        assert!(text.iter().any(|t| t.starts_with("  n19")));
        assert!(!text.iter().any(|t| t.starts_with("  n20")));
        assert_eq!(text.last().unwrap(), "  5 more");
    }

    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)));
    }

    fn folded(md: &str, heads: &[usize], width: usize) -> Rendered {
        let lines: Vec<String> = md.lines().map(String::from).collect();
        let blocks = crate::md::blocks(&lines);
        let visible = crate::fold::Visible::new(&lines, &blocks, heads);
        let mut r = render_wide(md, width);
        apply_folds(&mut r, &visible, heads, width);
        r
    }

    fn texts(r: &Rendered) -> Vec<String> {
        r.lines.iter().map(PLine::text).collect()
    }

    #[test]
    fn a_folded_section_loses_its_rows_and_the_heading_says_how_many() {
        let md = "# Title\nintro\n## One\na\nb\n## Two\nc\n";
        let r = folded(md, &[2], 40);
        let t = texts(&r);
        assert!(t.iter().all(|l| l != "a" && l != "b"), "{t:?}");
        let head = r.lines.iter().find(|l| l.src_line == Some(2)).unwrap();
        let text = head.text();
        assert!(text.starts_with("▸ One"), "{text:?}");
        assert!(text.ends_with("2 lines folded"), "{text:?}");
        assert_eq!(cells_width(&head.cells), 40);
        // the marker stands for the first `#`, the way it does in the editor
        assert_eq!(head.cells[0].src, Some((2, 0)));
        assert_eq!(head.cells[0].style, theme::fold());
        // Two follows One after one blank row, not the two either side of
        // the section that went
        let one = r.lines.iter().position(|l| l.src_line == Some(2)).unwrap();
        assert!(r.lines[one + 1].cells.is_empty());
        assert_eq!(r.lines[one + 2].src_line, Some(5));
        assert!(!r.lines[one + 2].text().starts_with(''));
        // the plain page is what it was
        let plain = folded(md, &[], 40);
        assert_eq!(texts(&plain), texts(&render_wide(md, 40)));
    }

    #[test]
    fn a_fold_at_the_end_of_the_page_leaves_no_blank_behind() {
        let md = "# Title\n## Last\nx\ny\n";
        let r = folded(md, &[1], 40);
        assert!(!r.lines.last().unwrap().cells.is_empty());
        assert_eq!(r.lines.last().unwrap().src_line, Some(1));
        // one hidden line reads in the singular, and a page too narrow for
        // the count keeps the heading text and the marker
        assert!(folded("# T\n## L\nx\n", &[1], 40).lines[2]
            .text()
            .ends_with("1 line folded"));
        let tight = folded("# T\n## Last\nx\n", &[1], 12);
        assert_eq!(tight.lines[2].text(), "▸ Last");
    }

    #[test]
    fn everything_a_section_holds_goes_with_it() {
        let md = "# T\n## One\n- [ ] task\n```rust\nlet x = 1;\n```\n| a | b |\n| - | - |\n| 1 | 2 |\n> quoted\n![pic](p.png)\n```mermaid\ngraph LR\nA-->B\n```\n## Two\nend\n";
        let r = folded(md, &[1], 40);
        for l in &r.lines {
            assert!(
                l.src_line.is_none_or(|s| s == 0 || s == 1 || s >= 15),
                "row from a hidden line: {:?} {:?}",
                l.src_line,
                l.text()
            );
        }
        let all = texts(&r).join("\n");
        for gone in ["task", "let x", "", "quoted", "pic", "A", "-->"] {
            assert!(!all.contains(gone), "{gone:?} in {all:?}");
        }
        assert!(all.contains("end"));
        assert!(r.lines.iter().all(|l| l.image.is_none()));
        // the checkbox under the fold is not there to click
        assert!(r.lines.iter().all(|l| l.checkbox.is_none()));
    }

    #[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"));
    }

    #[test]
    fn inline_comments_vanish_from_the_page_and_offsets_still_point_home() {
        let md = "see %% not this %% [[spec]] and `%% code %%` here\n";
        let r = render(md);
        let t = flat(&r);
        assert!(!t.contains("not this"), "{t}");
        assert!(t.contains("see spec and %% code %% here"), "{t}");
        // every mapped cell still points at its own character in the file
        let src_lines: Vec<&str> = md.lines().collect();
        for line in &r.lines {
            for c in &line.cells {
                if let Some((l, col)) = c.src {
                    assert_eq!(src_lines[l].chars().nth(col), Some(c.ch), "({l},{col})");
                }
            }
        }
    }

    #[test]
    fn a_block_comment_leaves_no_trace_and_the_lines_below_keep_their_numbers() {
        let md = "a\n\n%%\n# hidden\n\n- [ ] not a task\n%%\nb\n\n- [ ] task\n";
        let r = render(md);
        let t = texts(&r);
        assert!(
            t.iter()
                .all(|l| !l.contains("hidden") && !l.contains("not a")),
            "{t:?}"
        );
        // the page reads exactly as it would with the comment never typed
        assert_eq!(t, texts(&render("a\n\nb\n\n- [ ] task\n")));
        let b = r.lines.iter().find(|l| l.text() == "b").unwrap();
        assert_eq!(b.src_line, Some(7));
        let task = r.lines.iter().find(|l| l.text().contains("task")).unwrap();
        assert_eq!(task.src_line, Some(9));
        assert_eq!(task.checkbox, Some(9));
    }

    #[test]
    fn a_line_that_is_only_a_comment_does_not_split_its_paragraph() {
        let r = render("a\n%% note %%\nb\n");
        assert_eq!(texts(&r), texts(&render("a\nb\n")));
        assert_eq!(texts(&r), ["a", "b"]);
        let b = r.lines.iter().find(|l| l.text() == "b").unwrap();
        assert_eq!(b.src_line, Some(2));
    }

    #[test]
    fn an_unclosed_comment_marker_and_a_commented_code_line_are_literal() {
        let r = render("a %% b\n\n```\n%%\nx\n%%\n```\n");
        let t = flat(&r);
        assert!(t.contains("a %% b"), "{t}");
        assert!(t.contains("x"), "{t}");
    }
}