leaf-core 0.1.1

Frontend-neutral core of leaf: a byte-offset caret/selection model over twig, plus an AST→glyph map, styled with a toolkit-agnostic Style.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
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
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
//! The document model: a `twig::Editor` plus a byte-offset caret and selection.
//!
//! Where bough moves a selection through the *tree*, leaf moves a *caret*
//! through the *characters* — a normal text editor's model — and expresses
//! every mutation as one of twig's offset-addressed ops:
//!
//!   - typing / delete  → `edit_range(start, end, text)`   (P0)
//!   - re-anchoring      → the returned `Change`            (P1)
//!   - cursor context    → `node_at` / `ancestors_at`       (P3)
//!   - the toolbar       → `wrap_range`/`toggle_inline`/`set_block`,
//!                         `toggle_block_container`/`insert_link`   (P5)
//!
//! twig reparses after every edit and leaves everything outside the splice
//! byte-for-byte untouched, so the document stays a live, navigable AST while
//! you type into it.

// `PathBuf` names the `path` field and the untitled marker on every build;
// `Path` is only touched by the filesystem I/O gated behind the `fs` feature.
// The docs in this file lay their `- key → meaning` lists out in aligned
// columns, which puts a continuation line further right than clippy's
// list-indent rule likes. A lazy continuation renders as the same paragraph
// either way, and the alignment is what makes those tables readable, so the
// layout wins over the lint.
#![allow(clippy::doc_overindented_list_items)]

use std::collections::HashMap;
use std::ops::Range;
#[cfg(feature = "fs")]
use std::path::Path;
use std::path::PathBuf;

#[cfg(feature = "fs")]
use anyhow::Context;
use anyhow::{Result, anyhow};
use twig::{
    Alignment, BlockContainerKind, BlockKind, Change, Editor, FlatNode, Format, Gesture,
    InlineKind, Kind, MarkdownExtensions, NodeId, QueryMatch,
};
use unicode_segmentation::GraphemeCursor;

use crate::html;
use crate::wysiwyg::{self, MediaKind, MediaStop, VisualMap};

/// Which view the body shows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum View {
    /// The raw document with a caret in source bytes.
    Source,
    /// Markup resolved to real styles, caret riding the rendered glyphs.
    Wysiwyg,
}

/// How much of the source markup the WYSIWYG view exposes — a per-editor
/// preference, orthogonal to [`View`]. Named for markup rather than for Markdown
/// because leaf is grammar-agnostic: twig hands it Djot, HTML and XML on the same
/// terms, and every rung below is about *delimiters*, whatever grammar spells
/// them. The examples are Markdown only because that is what most documents are.
///
/// A single ladder over two underlying axes, because only three of their four
/// combinations are coherent:
///
/// | | authoring off | authoring on |
/// |---|---|---|
/// | delimiters hidden | [`None`](Self::None) | [`Shortcuts`](Self::Shortcuts) |
/// | caret line revealed | *incoherent* | [`Full`](Self::Full) |
///
/// The empty quadrant would show delimiters on the caret's line and then escape
/// the ones you type — a surface that displays a syntax it refuses to accept.
/// Someone who wants to read raw markup without authoring it has
/// [`View::Source`], which is the better tool for it.
///
/// The two axes are read separately by the code that cares — see
/// [`reveals_caret_line`](Self::reveals_caret_line) and
/// [`authors`](Self::authors) — so neither behaviour has to know it's spelled
/// as a ladder.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum MarkupMode {
    /// Delimiters stay hidden even on the caret's line, and typed syntax stays
    /// literal — twig escapes anything that would open markup, so formatting
    /// comes from commands (⌘b, the toolbar) instead of from spelling. The clean
    /// reading surface for people who don't write markup by hand; the default,
    /// and what Diaryx ships.
    #[default]
    None,
    /// Delimiters stay hidden, but typing them authors real markup: `*x*`
    /// becomes italic and the asterisks disappear into the styling
    /// (Typora/Bear-shaped). For someone who knows the syntax but wants the
    /// clean surface back once it has been applied.
    Shortcuts,
    /// The caret's line shows its raw markup while every other line renders
    /// resolved (Obsidian live-preview-shaped), and typed syntax authors markup
    /// — for people fluent in the document's grammar who want to see and edit
    /// the delimiters they type.
    Full,
}

impl MarkupMode {
    /// Whether the rich view shows raw delimiters on the line holding the caret.
    /// The rendering axis — read by [`Doc::reveal_line`] and threaded into the
    /// WYSIWYG builder.
    pub fn reveals_caret_line(self) -> bool {
        matches!(self, MarkupMode::Full)
    }

    /// Whether typed markup characters author real formatting. The editing axis
    /// — read by [`Doc::insert`], which escapes typed syntax when this is false.
    pub fn authors(self) -> bool {
        !matches!(self, MarkupMode::None)
    }
}

/// How the WYSIWYG view treats a *soft break* — a bare newline inside a
/// paragraph. An axis of its own, orthogonal to [`MarkupMode`] (which governs
/// inline-markup delimiters) and to [`View`]: any reveal preference pairs with
/// either flow. The renderer consults it when it lays a block's inline content
/// into visual rows.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum LineFlow {
    /// A soft break folds into a space and the paragraph reflows to the
    /// viewport width — flowing prose, where the source's line wrapping is
    /// insignificant. The default, and what Diaryx ships.
    #[default]
    Fold,
    /// A soft break renders as a line break exactly where it was written, so
    /// the author's source line structure shows on screen unchanged — the mode
    /// for people who lay out their prose deliberately (one sentence or clause
    /// per line, semantic line breaks). The break is still a soft break in the
    /// source; only its rendering changes.
    Preserve,
}

/// What the file behind a document looks like right now, against the bytes leaf
/// last read from it or wrote to it — the question a frontend asks before it
/// saves (a `Changed` file plus a `dirty` document is an overwrite about to
/// happen) or when its window regains focus. See [`Doc::disk_state`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiskState {
    /// The file holds exactly the bytes leaf last read or wrote.
    Unchanged,
    /// Someone else wrote the file since. Saving overwrites their work; see
    /// [`Doc::reload`] for the other direction.
    Changed,
    /// The file is gone — deleted or renamed away. A save recreates it.
    Missing,
    /// There is a path, but the file couldn't be read (permissions, a directory
    /// in the way): leaf can't tell, and won't guess.
    Unreadable,
    /// No file behind this document yet — see [`Doc::blank`]. Nothing can have
    /// changed under a document that was never on disk.
    Untitled,
}

/// The inline marks in force at a point in the document — what a toolbar
/// lights up. A `Copy` bitset rather than a `HashSet`, because
/// [`Doc::active_inline_marks`] is called on every frame that draws a toolbar
/// and a set that allocates to answer "is Bold on?" is a set that shouldn't.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct InlineMarks(u8);

impl InlineMarks {
    /// Every kind, in the order [`InlineMarks::iter`] yields them.
    const ALL: [InlineKind; 8] = [
        InlineKind::Strong,
        InlineKind::Emph,
        InlineKind::Verbatim,
        InlineKind::Mark,
        InlineKind::Superscript,
        InlineKind::Subscript,
        InlineKind::Insert,
        InlineKind::Delete,
    ];

    pub const fn empty() -> Self {
        InlineMarks(0)
    }

    /// Private: the set is an *answer*, and adding a mark to it doesn't mark
    /// anything ([`Doc::toggle`] does that). `FromIterator` is the way in.
    fn insert(&mut self, kind: InlineKind) {
        self.0 |= Self::bit(kind);
    }

    /// Flip `kind` in the set — the sticky-marks toggle at a collapsed caret.
    fn flip(&mut self, kind: InlineKind) {
        self.0 ^= Self::bit(kind);
    }

    /// The symmetric difference: which marks differ between the two sets. Used
    /// to resolve the marks already in force at the caret against the pending
    /// delta — a bit set in the delta flips the base mark for the next keystroke.
    fn xor(self, other: InlineMarks) -> InlineMarks {
        InlineMarks(self.0 ^ other.0)
    }

    /// Whether `kind` is in force — the toolbar's "is Bold active?".
    pub fn contains(self, kind: InlineKind) -> bool {
        self.0 & Self::bit(kind) != 0
    }

    pub fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// The marks in force, for a frontend that renders whatever is on rather
    /// than asking after a fixed list.
    pub fn iter(self) -> impl Iterator<Item = InlineKind> {
        Self::ALL.into_iter().filter(move |&k| self.contains(k))
    }

    fn bit(kind: InlineKind) -> u8 {
        1 << match kind {
            InlineKind::Strong => 0,
            InlineKind::Emph => 1,
            InlineKind::Verbatim => 2,
            InlineKind::Mark => 3,
            InlineKind::Superscript => 4,
            InlineKind::Subscript => 5,
            InlineKind::Insert => 6,
            InlineKind::Delete => 7,
        }
    }
}

impl FromIterator<InlineKind> for InlineMarks {
    fn from_iter<I: IntoIterator<Item = InlineKind>>(iter: I) -> Self {
        let mut m = InlineMarks::empty();
        for k in iter {
            m.insert(k);
        }
        m
    }
}

/// What kind of edit produced an undo group. Same-kind edits in a row coalesce
/// into one undo step (a run of typed characters undoes together); `Other` never
/// coalesces, so a paste, format toggle, or block change is always its own step.
#[derive(Clone, Copy, PartialEq, Eq)]
enum EditKind {
    Insert,
    Delete,
    /// One step of an IME composition — see [`Doc::edit_composing`]. Its own kind
    /// rather than `Insert`'s because a composition is not typing: each step
    /// *replaces* the last (`か` → `かん` → `感`), so the run has to coalesce even
    /// though no two steps insert the same bytes, and it must not fold into the
    /// typed characters on either side of it.
    Compose,
    Other,
}

/// Which side of the caret a delete looks for an in-cell `<br>` break to swallow
/// whole — see [`Doc::cell_break_at`]. `Backward` is Backspace (a break ending at
/// the caret), `Forward` is Delete (one starting at it).
#[derive(Clone, Copy)]
enum BreakEdge {
    Backward,
    Forward,
}

/// A re-spelling of one inline mark run, held ready in case the edit about to
/// happen breaks it — see [`Doc::mark_edge_fix`] and [`Doc::repair_mark_edges`].
/// Every offset in it is in the coordinates the document will have *after* the
/// plain edit, since that is when it may be applied.
struct MarkEdgeFix {
    /// The run's kind, and an offset inside what was its content: together they
    /// answer "did the plain edit actually break this mark?" — the question that
    /// decides whether any of this is applied at all.
    kind: InlineKind,
    probe: usize,
    /// The byte range to re-spell (the run's delimiters included) and its new
    /// spelling, with the edge whitespace moved outside the delimiters.
    start: usize,
    end: usize,
    text: String,
    /// Where the caret belongs afterwards — the same place on screen it would
    /// have had, which is now on the other side of a delimiter.
    caret: usize,
    /// The marks in force for text typed at that caret. The caret can land
    /// outside a run it was inside, and the marks have to survive the move or
    /// the toolbar goes dark mid-word.
    want: InlineMarks,
}

/// The caret and selection at one moment — the part of a history step twig's
/// `Change` cannot carry, because the caret is leaf's state and twig only knows
/// about bytes. leaf serializes it into the opaque per-state blob twig now
/// stores in its own undo history (see `record_caret`), so undo and redo hand
/// back the caret that matches the source they restore.
#[derive(Clone, Copy)]
struct CaretState {
    caret: usize,
    anchor: Option<usize>,
}

impl CaretState {
    /// Pack into the fixed 17-byte blob leaf hands twig: the caret as a u64,
    /// then an anchor-present flag and the anchor. twig copies these bytes and
    /// never reads them.
    fn to_blob(self) -> [u8; 17] {
        let mut b = [0u8; 17];
        b[..8].copy_from_slice(&(self.caret as u64).to_le_bytes());
        if let Some(a) = self.anchor {
            b[8] = 1;
            b[9..].copy_from_slice(&(a as u64).to_le_bytes());
        }
        b
    }

    /// Recover a state from twig's blob, or `None` when it is empty or the wrong
    /// length — a state twig restored that never had a caret set on it, which
    /// leaves the caller to fall back to the edit site.
    fn from_blob(b: &[u8]) -> Option<Self> {
        let b: &[u8; 17] = b.try_into().ok()?;
        let caret = u64::from_le_bytes(b[..8].try_into().unwrap()) as usize;
        let anchor = (b[8] != 0).then(|| u64::from_le_bytes(b[9..].try_into().unwrap()) as usize);
        Some(CaretState { caret, anchor })
    }
}

/// A footnote reference and the note it names — the answer to
/// [`Doc::footnote_at`].
///
/// The two `Option`s move together: a reference whose definition is missing has
/// neither a body to show nor a place to jump to, and one that resolved has
/// both.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FootnoteRef {
    /// The reference's label — the `1` of `[^1]`, with neither the `^` that
    /// spells it a footnote nor the brackets around it.
    pub label: String,
    /// The note's body as source bytes (see
    /// [`wysiwyg::footnote_body_span`](crate::wysiwyg)), or `None` when the
    /// document defines no `[^label]:` to read one from.
    pub text: Option<String>,
    /// Where the note's *body* starts, for a "go to note" that moves the caret
    /// there. `None` alongside a `None` `text`.
    ///
    /// The body rather than the definition, because this is an offset to put a
    /// caret on and the `[^1]:` marker is decoration the caret can't occupy —
    /// aiming at the definition's first byte snaps to the nearest real stop,
    /// which is up in the paragraph above the note. It is also simply where a
    /// reader following a reference wants to land: at the note's first word,
    /// ready to read or amend it.
    pub offset: Option<usize>,
    /// Where the note's body ends, exclusive — so a frontend can ask which
    /// *rendered rows* the note occupies and draw those instead of [`text`](Self::text).
    ///
    /// The rows are the note with its markup resolved: `see *later*` reaches a
    /// frontend as an italic run, not as asterisks. `text` is the source bytes
    /// and stays the honest answer for anything that wants the note as written
    /// (a search index, a copy); this pair of offsets is for anything that wants
    /// it as *read*. `None` alongside a `None` `offset`.
    pub end: Option<usize>,
}

/// A footnote definition and the reference that sends a reader to it — the
/// answer to [`Doc::footnote_definition_at`], and the other half of the round
/// trip [`FootnoteRef`] starts.
///
/// A note is a place a reader *arrives*, so the useful thing to know while
/// standing in one is the way back. Without this the jump to a note is a
/// one-way door: the definitions sit at the foot of the document, so returning
/// by hand means scrolling back up and finding the sentence again.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FootnoteDef {
    /// The definition's label — the `1` of `[^1]: …`, marker and colon stripped,
    /// spelled exactly as [`FootnoteRef::label`] spells the same footnote's.
    pub label: String,
    /// Where the reference's *label* is, for a "back to reference" that moves
    /// the caret there. `None` for a note nothing refers to — an orphan, which
    /// is worth being able to say rather than silently doing nothing.
    ///
    /// The label rather than the reference's first byte, for
    /// [`FootnoteRef::offset`]'s reason: a reference's brackets are decoration
    /// and its label is the only part of it the caret can rest on.
    ///
    /// The *first* reference, when a label is cited more than once: a repeated
    /// citation has no one true home, and the first is both the one a reader
    /// most likely came from and the only choice that doesn't depend on how
    /// they got here.
    pub offset: Option<usize>,
}

/// Where a locator lands — the answer to [`Doc::locate`].
///
/// A locator (the `v2` of a `chapter.dj#v2`) names a *place* rather than a
/// document, and a place is a span rather than a point: a reader following one
/// wants the caret at its first byte, and a reader merely *peeking* at one wants
/// the block it covers drawn. Both are served by carrying the whole span, and
/// only one of the two can be recovered from an offset alone.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Landing {
    /// The first byte of the block the locator names — where a caret goes.
    pub start: usize,
    /// One past its last byte, so a frontend can map the pair through
    /// [`Doc::pos_for_offset`] to the rendered rows the block occupies and draw
    /// those, the way a footnote peek draws a note ([`FootnoteRef::end`]).
    pub end: usize,
}

pub struct Doc {
    editor: Editor,
    pub format: Format,
    pub path: PathBuf,
    /// Current source, refreshed from the editor after every successful edit.
    pub source: String,
    /// The caret, as a byte offset into `source` (always on a char boundary).
    pub caret: usize,
    /// The selection's fixed end, if a selection is active; the moving end is
    /// the caret. `None` means no selection.
    pub anchor: Option<usize>,
    pub dirty: bool,
    pub status: Option<String>,
    pub view: View,
    /// How much of the source markup the rich view exposes — a frontend preference (see
    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
    /// [`reveal_line`](Self::reveal_line), the editing one by
    /// [`insert`](Self::insert).
    markup_mode: MarkupMode,
    /// Whether soft breaks fold into the reflowed paragraph or render where
    /// they were written (see [`LineFlow`]) — an independent frontend
    /// preference the WYSIWYG builder consults when it lays out a block.
    line_flow: LineFlow,
    /// The kind of the last edit, for coalescing: twig owns the undo *history*
    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
    /// call, so leaf decides when a run continues and tells twig to coalesce.
    last_edit_kind: Option<EditKind>,
    /// The inline marks the user has toggled *at a collapsed caret* with no
    /// selection — "start typing bold here". Held as the XOR delta from the marks
    /// already in force at [`pending_at`](Self::pending_at): a set bit means
    /// "flip this kind for the next typed text", so it both turns a mark on where
    /// none is (type into bold) and off where one already covers the caret (type
    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
    /// freshly typed text and then clears it — a mark once realised is carried by
    /// the caret sitting inside the run, not by this delta.
    pending_marks: InlineMarks,
    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
    /// delta is live only while the caret still stands here with no selection;
    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
    pending_at: Option<usize>,
    /// The source as of the last open/save — `dirty` is `source != clean_source`,
    /// so undoing back to the saved state correctly clears the modified flag.
    clean_source: String,
    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
    /// while the document has no file behind it. [`Doc::disk_state`] compares
    /// the file against this to catch an edit made *outside* leaf before a save
    /// silently overwrites it — `clean_source` only knows what leaf itself did.
    ///
    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
    /// writes inside one filesystem timestamp tick are indistinguishable, a
    /// clock that steps backwards (or a writer that restores an mtime) hides a
    /// real change, and a `touch` invents one. The whole point of the watermark
    /// is to not clobber someone's work, so it reads the bytes and compares what
    /// is actually there. That costs a file read per question, which is why the
    /// question is asked on a user event (focus, save) and not every frame.
    disk_hash: Option<u64>,
    /// The "sticky" display column vertical motion aims for, in the active
    /// view's grid. Set on the first `move_up`/`move_down` of a run and
    /// reused by every subsequent one in that run, so passing through a
    /// shorter line doesn't permanently forget the original column. Any
    /// horizontal motion or edit clears it.
    ///
    /// A column, not a character index: dropping down a line of `你好` onto one
    /// of ASCII has to land under the glyph the caret was drawn beneath, which
    /// is the only thing the user can see to aim by. Where the goal falls inside
    /// a wide character on the target line, the mapping resolves it to that
    /// character — the caret lands on it rather than between its cells.
    goal_col: Option<usize>,
    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
    /// and clicks read it to stay in visible space.
    pub vmap: VisualMap,
    /// Everything the map is built from, as one number: bumped whenever the
    /// document's text changes, and never by a motion, a selection, or a save.
    /// A frontend can hold work against it — see [`Doc::revision`].
    revision: u64,
    /// What `vmap` was built from, or `None` before the first build. The map is
    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
    /// moved, rebuilding it produces the identical map — see
    /// [`Doc::build_visual`].
    ///
    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
    /// text and width alone, and a caret motion still rebuilds nothing.
    vmap_key: Option<(u64, Option<usize>, Option<Range<usize>>)>,
    /// Per-block row cache backing the incremental rebuild: when the text
    /// changes, only the top-level blocks whose bytes moved are re-rendered and
    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
    /// builds; a pure accelerator, so it's never read for correctness.
    block_cache: wysiwyg::BlockCache,
    /// How many visual rows each block image reserves, keyed by its destination —
    /// set by the frontend through [`Doc::set_media_rows`] once it has decoded and
    /// measured the pictures. Core does no image I/O, so this is the only way it
    /// learns a picture's height; a destination not in the map reserves the bare
    /// one-row placeholder. Threaded into the builder so [`wysiwyg::build_cached`]
    /// sizes each placeholder, and folded into `vmap_key` so a height change
    /// rebuilds the map.
    media_rows: HashMap<String, usize>,

    // View geometry the renderer stamps each frame, so mouse events can map a
    // screen cell back to a byte offset.
    pub scroll: usize,
    pub body_origin: (u16, u16),
    pub body_height: u16,
    /// The caret as of the last frame drawn, or `None` before the first.
    ///
    /// Scrolling is the viewport's business, not the caret's: the view follows
    /// the caret when the caret *moves*, but a wheel that doesn't touch the
    /// caret has to be free to scroll away from it — otherwise the view is
    /// pinned to the caret and stops dead at the edge of the document you can
    /// see. Comparing against this is what tells the two apart, and it catches a
    /// caret set by any route, including a frontend assigning the field itself.
    pub drawn_caret: Option<usize>,
}

/// The Markdown extensions every leaf document is parsed with. `html_elements`
/// and `directives` depart from twig's defaults. `html_elements` promotes
/// embedded raw HTML (`<img>`, `<picture>`, `<source>`, …) into semantic AST
/// nodes, so a picture becomes a real `image` node the frontends can frame and
/// rasterize instead of opaque `raw_block` text. `directives` turns on generic
/// `:::name{.class}` fenced-div containers (`directive` nodes), which a host
/// app uses for its own semantics (diaryx's `:::vis{.audience}` visibility
/// blocks) — core renders any directive as a plain tinted container, agnostic
/// of `name`. Both flags are inert for non-Markdown formats, so it's safe to
/// pass them unconditionally. Threading this through every constructor (not
/// just `open`) keeps `from_source`, `blank`, and `reload` parsing the same
/// document the same way — twig reparses with these same flags after each edit.
fn parse_extensions() -> MarkdownExtensions {
    MarkdownExtensions {
        html_elements: true,
        directives: true,
        ..Default::default()
    }
}

/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
/// mapping twig's error into the `anyhow` context every constructor shares.
fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
}

/// Does `format` spell a table as a **pipe table** — the one grid twig's table
/// editor knows how to emit?
///
/// This is the single capability leaf still has to answer for itself, and the
/// only hand-maintained format list left in this file. Every other gesture is
/// [`Format::supports`], which is twig's own answer read across the C ABI — but
/// twig deliberately leaves the table ops out of that query, because they read
/// no `Syntax` table at all. They rewrite a grid that is already in the source
/// and refuse on *position*, never on format. Handed a caret inside an HTML
/// `<table>`, `table_insert_row` therefore re-emits the whole element as
/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
/// `dirty` flag, and nothing downstream able to tell it from a good edit.
///
/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
/// wildcard answers "no" for a format leaf has never heard of: a new twig
/// language that *does* spell pipe tables loses its grid controls until this
/// line is updated, which shows up as a missing button. The other default hands
/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
fn spells_pipe_tables(format: Format) -> bool {
    matches!(format, Format::Markdown | Format::Djot)
}

/// Which of leaf's authoring controls this document's format can actually
/// spell — one flag per toolbar button, resolved once so a frontend can build
/// its chrome instead of discovering each refusal on a click.
///
/// Every field but [`table`](Self::table) is `Format::supports` on the gesture
/// the matching [`Doc`] method calls, so this record cannot drift from what the
/// ops do; `table` is [`spells_pipe_tables`], the one answer twig doesn't
/// export.
///
/// **The formats are ragged, and that is the point.** A single per-document
/// boolean was enough while the two authorable formats were Markdown and djot
/// and everything else spelled nothing. HTML is neither: it writes seven of the
/// eight inline marks as a tag pair, plus `<code>`, `<hr>` and an in-cell
/// `<br>`, and spells no heading marker, no line prefix, no fence, no task box,
/// no link — because its versions of those have a different *shape*, not a
/// different alphabet. So ⌘B works in an HTML document and ⌘1 does not, and no
/// one flag can say that. Markdown and djot differ from each other too:
/// `==mark==` is djot-only, and an in-cell `<br>` is Markdown-only.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Capabilities {
    /// ⌘B — `InlineKind::Strong`.
    pub bold: bool,
    /// ⌘I — `InlineKind::Emph`.
    pub italic: bool,
    /// Inline code — `InlineKind::Verbatim`.
    pub code: bool,
    /// Highlight — `InlineKind::Mark`. Djot spells it; Markdown does not.
    pub mark: bool,
    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
    pub underline: bool,
    /// Strikethrough — `InlineKind::Delete`.
    pub strike: bool,
    pub superscript: bool,
    pub subscript: bool,
    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
    pub heading: bool,
    pub blockquote: bool,
    pub bullet_list: bool,
    pub ordered_list: bool,
    /// The checkbox controls: giving an item a box, and ticking one.
    pub task: bool,
    pub link: bool,
    /// Covers [`Doc::insert_media`] too — see the note there on why the three
    /// media kinds stand or fall together.
    pub image: bool,
    /// The horizontal-rule button. HTML spells this one (`<hr>`).
    pub thematic_break: bool,
    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
    /// the pair; HTML has no footnote of its own, so the button goes away rather
    /// than writing brackets that would render as brackets.
    pub footnote: bool,
    /// Setting a fenced block's language — a control only ever offered with the
    /// caret already in a fence.
    pub code_language: bool,
    /// The grid controls: insert/delete/move a row or column, set a column's
    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
    /// question — an HTML `<table>` holds the caret and still can't be edited.
    pub table: bool,
    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
    /// idiomatic in-cell break.
    pub cell_line_break: bool,
}

impl Capabilities {
    /// Resolve every flag for `format`. Pure and cheap — twig computes each from
    /// a static table — but a frontend that wants to hold them can.
    pub fn of(format: Format) -> Self {
        let inline = |k| format.supports(Gesture::ToggleInline(k));
        let container = |k| format.supports(Gesture::ToggleBlockContainer(k));
        Self {
            bold: inline(InlineKind::Strong),
            italic: inline(InlineKind::Emph),
            code: inline(InlineKind::Verbatim),
            mark: inline(InlineKind::Mark),
            underline: inline(InlineKind::Insert),
            strike: inline(InlineKind::Delete),
            superscript: inline(InlineKind::Superscript),
            subscript: inline(InlineKind::Subscript),
            heading: format.supports(Gesture::SetBlock),
            blockquote: container(BlockContainerKind::BlockQuote),
            bullet_list: container(BlockContainerKind::BulletList),
            ordered_list: container(BlockContainerKind::OrderedList),
            // Both halves of the checkbox story, and leaf offers no control that
            // needs only one: the item gesture mints the box, the checked one
            // ticks it, and a format spelling a `task_marker` spells both.
            task: format.supports(Gesture::ToggleTaskItem)
                && format.supports(Gesture::ToggleTaskChecked),
            link: format.supports(Gesture::InsertLink),
            image: format.supports(Gesture::InsertImage),
            thematic_break: format.supports(Gesture::InsertThematicBreak),
            footnote: format.supports(Gesture::InsertFootnote),
            code_language: format.supports(Gesture::SetCodeLanguage),
            table: spells_pipe_tables(format),
            cell_line_break: format.supports(Gesture::InsertLineBreak),
        }
    }
}

impl Doc {
    #[cfg(feature = "fs")]
    pub fn open(path: PathBuf) -> Result<Self> {
        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
        let format = detect_format(&path)?;
        let editor = new_editor(&bytes, format)?;
        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
        let disk_hash = Some(hash_bytes(source.as_bytes()));
        // Store the document's *absolute* path. A relative one (`leaf README.md`)
        // has an empty parent, so a frontend can't resolve a relative image
        // destination (`![](pic.png)`) against the document's directory and the
        // picture silently falls back to its text placeholder. `absolute` is
        // purely lexical — it prefixes the current directory and normalizes, but
        // reads nothing and resolves no symlinks — so `file_name` and save are
        // unchanged; it only gives `path.parent()` something to join against.
        let path = std::path::absolute(&path).unwrap_or(path);
        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
    }

    /// Build a document from an in-memory string, the format named explicitly —
    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
    /// path and sniffs the format from its extension). A wasm or FFI host, which
    /// has no path to read, uses this: it hands over bytes it fetched however it
    /// could, and later persists [`Doc::source`] however it can (a browser
    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
    ///
    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
    /// true) exactly like a [`Doc::blank`] that has been given content.
    pub fn from_source(source: String, format: Format) -> Result<Self> {
        let editor = new_editor(source.as_bytes(), format)?;
        Ok(Doc::from_parts(
            editor,
            format,
            PathBuf::new(),
            source,
            None,
        ))
    }

    /// An untitled, empty document — the `+` button and a `leaf` launched with
    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
    ///
    /// It is Markdown, because a format has to be chosen before a name exists to
    /// read one from: `detect_format` reads the extension and an untitled
    /// document has neither. Markdown is what leaf's own files are, what its
    /// block markers are already written for (`insert_block_prefix`), and the
    /// extension a Save As will overwhelmingly pick — a wrong guess here would
    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
    /// *doesn't* revisit this: see [`Doc::save_as`].
    pub fn blank() -> Result<Self> {
        let format = Format::Markdown;
        let editor = new_editor(b"", format)?;
        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
        // field two frontends already read; making it an `Option` to say this
        // would break both). `is_untitled` is the question to ask, not the
        // representation to copy.
        Ok(Doc::from_parts(
            editor,
            format,
            PathBuf::new(),
            String::new(),
            None,
        ))
    }

    /// The fields every constructor agrees on, so `open` and `blank` can't drift
    /// apart in the ones neither of them has an opinion about.
    fn from_parts(
        editor: Editor,
        format: Format,
        path: PathBuf,
        source: String,
        disk_hash: Option<u64>,
    ) -> Self {
        Doc {
            editor,
            format,
            path,
            disk_hash,
            clean_source: source.clone(),
            source,
            caret: 0,
            anchor: None,
            dirty: false,
            status: None,
            // leaf opens in the rich-text (WYSIWYG) view by default — the
            // markup-resolved surface is leaf's differentiator. Frontends can
            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
            // toggles at runtime.
            view: View::Wysiwyg,
            // `None` by default — the clean surface Diaryx ships, with typed
            // syntax kept literal; a markup-fluent frontend can climb the
            // ladder to `Shortcuts` or `Full`.
            markup_mode: MarkupMode::default(),
            // Fold by default — flowing prose that reflows to the viewport, the
            // behaviour every frontend had before this preference existed.
            line_flow: LineFlow::default(),
            last_edit_kind: None,
            pending_marks: InlineMarks::empty(),
            pending_at: None,
            goal_col: None,
            vmap: VisualMap::default(),
            revision: 0,
            // No map yet — the first `build_visual` always builds.
            vmap_key: None,
            block_cache: wysiwyg::BlockCache::default(),
            media_rows: HashMap::new(),
            scroll: 0,
            body_origin: (0, 0),
            body_height: 0,
            drawn_caret: None,
        }
    }

    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
    /// has never been saved. The question a ⌘S handler asks to know it should
    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
    /// header asks to know the name it shows is a placeholder.
    pub fn is_untitled(&self) -> bool {
        self.path.as_os_str().is_empty()
    }

    pub fn toggle_view(&mut self) {
        self.view = match self.view {
            View::Source => View::Wysiwyg,
            View::Wysiwyg => View::Source,
        };
        self.scroll = 0;
        self.status = None;
        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
        // lift it to the first rendered offset.
        self.clamp_caret();
    }

    /// The current markup-exposure preference (see [`MarkupMode`]).
    pub fn markup_mode(&self) -> MarkupMode {
        self.markup_mode
    }

    /// Set the markup-exposure preference. Both of its axes take effect at
    /// once: the editing one on the next [`insert`](Self::insert), and the
    /// rendering one on the next build — which is why this drops the cached
    /// visual map and the per-block render cache, exactly as
    /// [`set_line_flow`](Self::set_line_flow) does.
    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
        if self.markup_mode == mode {
            return;
        }
        self.markup_mode = mode;
        // Neither cache is keyed on the mode, and moving between `Full` and the
        // hidden modes changes every row the caret's line renders to — so
        // invalidate both explicitly.
        self.vmap_key = None;
        self.block_cache = wysiwyg::BlockCache::default();
    }

    /// The source byte range of the line the caret sits on, when that line
    /// should render its raw delimiters — `None` in every mode and view that
    /// hides them, which is what the builder reads as "reveal nothing".
    ///
    /// A *source* line (newline to newline), not a visual row: a wrapped
    /// paragraph and a `LineFlow::Preserve` soft break both split one source
    /// line across several rows, and revealing half a delimiter pair because the
    /// other half wrapped would be worse than revealing neither. The range
    /// excludes the terminating newline and is empty-but-present on a blank
    /// line, which reveals nothing but still keys the caches correctly.
    ///
    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
    /// there is nothing there to reveal.
    pub(crate) fn reveal_line(&self) -> Option<Range<usize>> {
        if !self.markup_mode.reveals_caret_line() || self.view != View::Wysiwyg {
            return None;
        }
        Some(source_line_range(&self.source, self.caret))
    }

    /// The current soft-break flow preference (see [`LineFlow`]).
    pub fn line_flow(&self) -> LineFlow {
        self.line_flow
    }

    /// Set the soft-break flow preference. The mode changes how every block lays
    /// out, so a change drops the cached visual map and the per-block render
    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
    ///
    /// [`build_visual`]: Self::build_visual
    pub fn set_line_flow(&mut self, mode: LineFlow) {
        if self.line_flow == mode {
            return;
        }
        self.line_flow = mode;
        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
        // so invalidate them explicitly, or the next build would reuse rows laid
        // out under the old flow.
        self.vmap_key = None;
        self.block_cache = wysiwyg::BlockCache::default();
    }

    pub fn view_name(&self) -> &'static str {
        match self.view {
            View::Source => "source",
            View::Wysiwyg => "wysiwyg",
        }
    }

    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
    /// (called by the renderer each frame it's in the WYSIWYG view).
    /// Build the WYSIWYG map, wrapped at `width` display columns.
    ///
    /// Cheap to call every frame, which is what both frontends do: the map is a
    /// pure function of the document and the wrap width, so a call that would
    /// rebuild the same map returns the one already built. Only an edit (or a
    /// resize) pays.
    ///
    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
    pub fn build_visual(&mut self, width: usize) {
        self.build_map(Some(width));
    }

    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
    /// frontend (the GUI) that wraps at its own proportional pixel width rather
    /// than a fixed character column.
    pub fn build_visual_unwrapped(&mut self) {
        self.build_map(None);
    }

    /// Tell the model how many visual rows each block image should reserve, keyed
    /// by the image's destination. A terminal frontend calls this once it has
    /// decoded and measured its pictures — core does no image I/O, so this is the
    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
    /// placeholder out that tall (the label row plus blank filler rows the
    /// frontend paints the raster over). A destination left out of the map falls
    /// back to the bare one-row placeholder, which is also what a frontend that
    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
    /// by never calling this.
    ///
    /// Cheap to call every frame with the same map: only a *change* invalidates
    /// the built map (and the block-row cache, since a height isn't part of a
    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
    /// no-op, so a frontend can just hand over its current measurements each frame.
    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
        if self.media_rows == rows {
            return;
        }
        self.media_rows = rows;
        // A height lives outside the block's source bytes, so the content-keyed
        // block cache would hand back the old-height rows on a hit. Drop it (and
        // the splice layout it carries) so the next build re-renders every block
        // at the new heights, and force that build by clearing the map key.
        self.block_cache = wysiwyg::BlockCache::default();
        self.vmap_key = None;
    }

    /// The revision the document's text is at — bumped by every edit, undo,
    /// redo, and reload, and by nothing else. A frontend caches against this to
    /// tell a repaint that needs new work from one that doesn't.
    ///
    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
    /// lands on the same text two revisions later. Work is only ever rebuilt
    /// needlessly, never wrongly reused.
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
    /// runs on every call: the caret moves without the document changing, and
    /// keeping it on a legal stop is this function's job either way.
    fn build_map(&mut self, wrap: Option<usize>) {
        // Under `MarkupMode::Full` the map is a function of the caret's *line*
        // as well as the text, so the line joins the key: moving within a line
        // still reuses the map, and crossing into another one rebuilds it. In
        // every other mode `reveal_line` is `None` and the key is what it was,
        // so caret motion goes on costing nothing.
        let reveal = self.reveal_line();
        let key = (self.revision, wrap, reveal.clone());
        if self.vmap_key.as_ref() != Some(&key) {
            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
            // A subtree is pulled only for the block(s) that actually changed, so
            // the FFI marshal shrinks from O(document) to O(edited block).
            let top = self.top_blocks();

            // Fast path: when twig reports a dirty byte range, try to patch the
            // previous map in place — a single-block edit moves the prefix,
            // shifts the suffix, and re-renders only one block. `build_spliced`
            // returns `None` (and we fall back to the always-correct full rebuild)
            // whenever the edit reshaped the block structure, hit a table, or
            // there's no previous map to patch.
            // Preserve soft breaks as written when the flow preference asks for
            // it — the builder renders each as its own visual row instead of
            // folding it into the reflowed paragraph.
            let preserve_soft = self.line_flow == LineFlow::Preserve;
            let spliced = match self.editor.dirty_range() {
                Some(dirty) => {
                    let prev = std::mem::take(&mut self.vmap);
                    let source = &self.source;
                    let cache = &mut self.block_cache;
                    let media_rows = &self.media_rows;
                    let editor = &mut self.editor;
                    wysiwyg::build_spliced(
                        prev,
                        source,
                        wrap,
                        preserve_soft,
                        &top,
                        dirty,
                        media_rows,
                        reveal.clone(),
                        cache,
                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
                    )
                }
                None => None,
            };
            self.vmap = spliced.unwrap_or_else(|| {
                let source = &self.source;
                let cache = &mut self.block_cache;
                let media_rows = &self.media_rows;
                let editor = &mut self.editor;
                wysiwyg::build_cached(
                    &top,
                    source,
                    wrap,
                    preserve_soft,
                    media_rows,
                    reveal,
                    cache,
                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
                )
            });
            // Acknowledge the dirty range so the next edit's range starts fresh.
            self.editor.clear_dirty();
            self.vmap_key = Some(key);
        }
        self.clamp_caret();
    }

    fn nodes(&mut self) -> Vec<FlatNode> {
        self.editor.nodes().unwrap_or_default()
    }

    /// The document's top-level blocks for the incremental render. See
    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
    fn top_blocks(&mut self) -> Vec<QueryMatch> {
        wysiwyg::top_blocks(&mut self.editor)
    }

    pub fn format_name(&self) -> &'static str {
        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
        // required. It also covers `Asciidoc`, which twig parses but cannot
        // serialize — leaf never opens a document in it (see `Doc::open`).
        match self.format {
            Format::Djot => "djot",
            Format::Markdown => "markdown",
            Format::Xml => "xml",
            Format::Html => "html",
            _ => "unknown",
        }
    }

    /// Whether this document's format offers *any* door in — `false` only for a
    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
    /// a frontend may as well open the file read-only.
    ///
    /// This is a much weaker claim than the name suggests, and driving per-button
    /// state from it is exactly the mistake to avoid: HTML answers `true` because
    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
    /// while a heading, a quote, a list, a task box, a link and a code fence all
    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
    /// [`supports`](Self::supports) — per control.
    pub fn authorable(&self) -> bool {
        self.format.is_authorable()
    }

    /// Whether this document's format can spell `gesture`, which is twig's own
    /// answer rather than a copy of it: `Format::supports` reads the same
    /// `Syntax` table the `Editor` method consults before refusing.
    ///
    /// It is a fact about the *format*, not about the caret. `true` does not
    /// promise the gesture succeeds where it is standing — a link over a table
    /// border still fails — only that it will not fail with
    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
    /// will work here".
    pub fn supports(&self, gesture: Gesture) -> bool {
        self.format.supports(gesture)
    }

    /// Every control's enabled state in one read — what a toolbar builds itself
    /// from when a document opens or its format changes. See [`Capabilities`].
    pub fn capabilities(&self) -> Capabilities {
        Capabilities::of(self.format)
    }

    /// Refuse a gesture this document's format cannot spell, saying so in the
    /// status line. `true` means the caller must return without calling twig.
    ///
    /// Most of these refusals duplicate one twig would make anyway, and they are
    /// made here regardless because a message naming the *document's* format
    /// reads better than one naming twig's internals. Two of them are not
    /// duplicates and are the reason this is a guard rather than an error
    /// translation:
    ///
    /// - The table family (see [`table_op`](Self::table_op)) consults no
    ///   `Syntax` table, so twig does not refuse it at all.
    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
    ///   could not keep.
    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
        self.refuse_unless(what, self.supports(gesture))
    }

    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
    /// answers itself — today only [`spells_pipe_tables`].
    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
        if supported {
            return false;
        }
        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
        true
    }

    /// The name to show for this document. An untitled one has no file to name
    /// it, and both frontends put this straight on screen — an empty path
    /// renders as an empty header, so it says so instead.
    pub fn file_name(&self) -> String {
        if self.is_untitled() {
            return "untitled".into();
        }
        self.path
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| self.path.display().to_string())
    }

    /// The selection as an ordered `[start, end)` byte range, or `None` when the
    /// caret and anchor coincide (an empty selection is no selection).
    pub fn selection(&self) -> Option<(usize, usize)> {
        self.anchor
            .map(|a| (a.min(self.caret), a.max(self.caret)))
            .filter(|(s, e)| s != e)
    }

    /// The selected text, or `None` when there's no selection — the source
    /// slice a copy/cut hands to the system clipboard.
    pub fn selected_text(&self) -> Option<&str> {
        self.selection().map(|(s, e)| &self.source[s..e])
    }

    /// The AST breadcrumb at the caret (root → deepest), e.g.
    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
    pub fn breadcrumb(&mut self) -> String {
        match self.editor.ancestors_at(self.caret) {
            Ok(chain) => chain
                .iter()
                .map(|m| m.kind.as_str())
                .collect::<Vec<_>>()
                .join(""),
            Err(_) => String::new(),
        }
    }

    // ── editing ──────────────────────────────────────────────────────────────

    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
    /// after it. The public form of the internal splice — a pixel frontend that
    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
    /// edits through this, the same twig `edit_range` the caret ops use.
    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
        self.splice(start, end, text, EditKind::Other);
    }

    /// Insert typed `text` at the caret, replacing the selection if there is one.
    /// A single typed character coalesces with the run of typing before it; a
    /// newline or a multi-character insert is its own undo step.
    ///
    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
    pub fn insert(&mut self, text: &str) {
        // Typing against a block picture would dissolve it — see
        // `open_paragraph_at_block_media`. Give the text a paragraph first, so
        // what the caret was standing beside stays a picture.
        self.open_paragraph_at_block_media(text);
        // Armed sticky marks (⌘b with no selection) turn the next typed text
        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
        // the exception: it takes no mark of its own and keeps the delta armed
        // for the character behind it — see `insert_space_with_marks`.
        let pending = self.pending_here();
        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
            if text.trim().is_empty() {
                self.insert_space_with_marks(self.caret, text, pending);
            } else {
                self.insert_with_marks(self.caret, text, pending);
            }
            return;
        }
        // `MarkupMode::None`: typed syntax stays literal — twig escapes
        // anything that would open markup, so a Diaryx user never mints
        // formatting by keyboard (it comes from commands instead). The other two
        // rungs of the ladder author markup from what you type, which is the
        // whole difference between them and this one. Only in the rendered view
        // (source view is for typing raw markup) and only where the format has a
        // literal spelling at all: escaping is a backslash before a byte from the
        // format's own alphabet, and a format with no such alphabet (HTML escapes
        // with entities, XML spells nothing) would have `\&` written into it,
        // which is two literal characters and not an escape. Marks (⌘b) still
        // format — that path returned above; and leaf's own structural inserts go
        // through `insert_raw`, never here, so a list marker or quote gutter is
        // written as the markup it is.
        if !self.markup_mode.authors()
            && self.view == View::Wysiwyg
            && !text.is_empty()
            && self.supports(Gesture::InsertLiteral)
        {
            self.insert_literal_typed(text);
            return;
        }
        self.insert_raw(text);
    }

    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
    /// markup by design and must not be escaped.
    fn insert_raw(&mut self, text: &str) {
        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
        self.splice(s, e, text, typed_edit_kind(text));
    }

    /// Open a paragraph for text about to be inserted at one of a block media's
    /// two caret stops, and leave the caret standing in it.
    ///
    /// A block image is a paragraph whose entire content is the picture, and the
    /// caret's only homes on it are in front of it and just past it (see
    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
    /// *that* paragraph — and a paragraph holding anything besides the image is
    /// no longer a block image but a line of text with an inline one in it. The
    /// frontend that was painting a photo there paints a text run instead; the
    /// picture is still in the file, and nothing said a word. Those two offsets
    /// are also exactly where a click on the picture lands, so the whole accident
    /// is one tap and one keystroke.
    ///
    /// So the break goes in first and the text lands in the new empty paragraph —
    /// what pressing Return before typing would have done, which is a habit no
    /// one should have to learn from losing a photo. A no-op everywhere else, and
    /// over a selection (which is replaced, not joined into).
    ///
    /// A picture inside a quote or a list leaves its container, because `\n\n`
    /// ends the block. The alternative is worse: the `\n> ` / next-item
    /// continuation [`newline`](Self::newline) writes stays in the same
    /// *paragraph*, which is the thing being prevented.
    ///
    /// Only in the rendered view. Source view is for typing raw markup, where
    /// putting a character against an image is exactly what it looks like.
    fn open_paragraph_at_block_media(&mut self, text: &str) {
        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
            return;
        }
        if self.selection().is_some() {
            return;
        }
        // The map may be a revision behind (nothing has drawn since the last
        // edit), and this asks it about offsets — a stale answer would splice a
        // break into the wrong place. Free when it is already current, which it
        // is whenever a frontend drew a frame between keystrokes.
        self.rebuild_map();
        let at = self.caret;
        let Some((side, _)) = self.vmap.block_media_stop(at) else {
            return;
        };
        if !self.splice(at, at, "\n\n", EditKind::Other) {
            return;
        }
        // The break is part of the keystroke, not an edit of its own: leave the
        // run marked as typing so the character about to arrive folds into it and
        // one undo puts the document back the way it was found. (A paste, or a
        // multi-character insert, is `EditKind::Other` and stays its own step —
        // as it would have been anywhere else in the document.)
        self.last_edit_kind = Some(EditKind::Insert);
        if side == MediaStop::Before {
            // The break went in above the picture and the caret rode to the end
            // of it — which is still hard against the picture. Step back onto the
            // blank line it opened, so the text lands above rather than in front.
            self.caret = at;
        }
    }

    /// A delete key pressed at one of a block picture's two caret stops, handled
    /// as the picture being an *atom* rather than a run of bytes. Returns whether
    /// the key was consumed.
    ///
    /// The caret rests in front of a block image and just past it, never inside
    /// its markup — which the rendered view doesn't show. So the byte a delete
    /// key nominally takes there is one the writer cannot see, and taking it
    /// leaves the picture as broken markup rather than as anything anyone asked
    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
    /// missing from a document with nobody having touched it — the same
    /// dissolution [`open_paragraph_at_block_media`](Self::open_paragraph_at_block_media)
    /// prevents from the typing side, and it cost this repository's own test vault
    /// a photo before it was found.
    ///
    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
    /// when it is behind the caret, Delete when it is in front — which is what
    /// every editor does with an embed, and one undo away. The key aimed *away*
    /// from it would otherwise delete the paragraph break and merge a neighbour
    /// into the picture's own paragraph, which dissolves it just as surely; it
    /// steps the caret over the boundary instead and leaves the
    /// next press to delete in the block it has reached — the same "first press
    /// steps out of the atom, second press deletes" every delete key here gets,
    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
    /// above, and reaches it on the second press rather than taking the break and
    /// the picture with it on the first).
    fn delete_around_block_media(&mut self, forward: bool) -> bool {
        // The map answers about offsets, so it has to be this revision's — see
        // the same call in `open_paragraph_at_block_media`.
        self.rebuild_map();
        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
            return false;
        };
        let aimed_at_it = side
            == if forward {
                MediaStop::Before
            } else {
                MediaStop::After
            };
        if !aimed_at_it {
            let over = if forward {
                self.vmap.stop_after(self.caret)
            } else {
                self.vmap.stop_before(self.caret)
            };
            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
                self.caret = off;
                self.anchor = None;
                self.goal_col = None;
            }
            return true;
        }
        // Take the break that held the picture apart from its neighbour with it,
        // so the delete doesn't leave a blank paragraph standing where the
        // picture was. The last arm is a picture that is the whole document.
        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
            (span.start - 2, span.end)
        } else if self.source[span.end..].starts_with("\n\n") {
            (span.start, span.end + 2)
        } else {
            (span.start, span.end)
        };
        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
        true
    }

    /// The Hidden-mode typing path: replace any selection, then insert `text`
    /// escaped so it stays literal. When it replaces a selection the two edits
    /// fold into one undo step, so an overwrite undoes atomically (and restores
    /// the selection) exactly as a plain one does.
    fn insert_literal_typed(&mut self, text: &str) {
        let kind = typed_edit_kind(text);
        match self.selection() {
            Some((s, e)) => {
                if !self.splice(s, e, "", EditKind::Other) {
                    return;
                }
                // Typing over a whole marked run takes its delimiters with it
                // (the empty content couldn't hold them — see
                // `repair_mark_edges`) and leaves its marks armed at the caret.
                // The text taking the run's place inherits them, exactly as it
                // would have by landing inside a run that survived.
                let pending = self.pending_here();
                if !pending.is_empty() && !text.trim().is_empty() {
                    self.insert_with_marks(self.caret, text, pending);
                    return;
                }
                self.insert_literal_at(self.caret, text, kind, true);
            }
            None => {
                self.insert_literal_at(self.caret, text, kind, false);
            }
        }
    }

    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
    /// at a collapsed caret, but only while the caret still stands where they
    /// were armed and nothing is selected. Empty otherwise, so a stale delta
    /// never styles text it wasn't meant for.
    fn pending_here(&self) -> InlineMarks {
        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
            self.pending_marks
        } else {
            InlineMarks::empty()
        }
    }

    /// Drop the armed sticky marks — any caret motion, selection, or edit does
    /// this, so "start bold here" only ever applies at the exact spot it was
    /// asked for.
    fn clear_pending(&mut self) {
        self.pending_marks = InlineMarks::empty();
        self.pending_at = None;
    }

    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
    /// force is wrapped around the freshly typed text; a mark the caret already
    /// stands inside is *shed* — the text is inserted past the run's end so it
    /// lands unmarked ("type normally again"). The caret comes to rest inside any
    /// added runs, so continued typing inherits the marks with no re-wrapping,
    /// and the delta is cleared: the marks now live in the document, not here.
    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
        let base = self.mark_spans_at(at);
        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
        // Nothing to shed, and a run of exactly these marks standing just behind
        // the caret: carry on writing *that* run rather than opening a second
        // one beside it.
        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
            return;
        }
        // Shed the marks we're turning off: step the insertion point past the
        // end of each run the caret sits in, so the new text falls outside it.
        let mut ins_at = at;
        for (kind, span) in &base {
            if marks.contains(*kind) {
                ins_at = ins_at.max(span.end);
            }
        }
        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
            return;
        }
        // The plain splice inserted exactly `text` at `ins_at`; that byte range
        // is the content every added mark wraps.
        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
        for kind in marks.iter() {
            if !base_set.contains(kind) {
                let (ncs, nce) = self.wrap_span(cs, ce, kind);
                cs = ncs;
                ce = nce;
            }
        }
        self.caret = ce.min(self.source.len());
        self.anchor = None;
        self.last_edit_kind = None;
        // Realised: the marks are in the document now, and the caret sits inside
        // them, so there is no delta left to carry. Arm nothing, but remember the
        // spot so a *further* toggle before typing starts a clean delta here.
        self.pending_marks = InlineMarks::empty();
        self.pending_at = Some(self.caret);
        self.clamp_caret();
        self.record_caret();
    }

    /// Carry on the marked run just behind `at` — moving its closing delimiters
    /// out past the new text — instead of opening a second run of the same marks
    /// beside it. Returns whether it did.
    ///
    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
    /// A space typed after a bold word steps the caret out of the run, because
    /// `**bold **` is not bold; the next character has to step back *in*, or the
    /// writer who typed one bold phrase is left with `**bold** **and**` — two
    /// runs that read the same to a reader but spell the file in a way nobody
    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
    /// words it isn't marking), and the marks behind it must be exactly the ones
    /// armed — a run of *some* other kind is a neighbour, not this phrase.
    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
        if text.is_empty() || text.trim() != text {
            return false;
        }
        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
        // Walk in through the delimiters stacked at that point, innermost last:
        // `***both*** ` closes two runs with one `***`, and rejoining means
        // getting behind all of them.
        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
        while let Some((kind, content_end)) = self
            .editor
            .ancestors_at(prev_boundary(&self.source, cut))
            .unwrap_or_default()
            .into_iter()
            .filter(|m| m.span.end == cut)
            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
        {
            if content_end >= cut {
                break; // a mark with no closing delimiter to step behind
            }
            kinds.insert(kind);
            cut = content_end;
        }
        if cut == gap_at || kinds != marks {
            return false;
        }
        // Re-spell the tail: the gap, then the new text, then the delimiters that
        // used to close in front of them — read out of the document rather than
        // written from a table, so whatever twig spells them with is what moves.
        let tail = format!(
            "{}{text}{}",
            &self.source[gap_at..at],
            &self.source[cut..gap_at]
        );
        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
            return false;
        }
        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
        self.anchor = None;
        self.last_edit_kind = None;
        self.pending_marks = InlineMarks::empty();
        self.pending_at = Some(self.caret);
        self.clamp_caret();
        self.record_caret();
        true
    }

    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
    /// never itself wrapped: a mark around a space draws nothing a reader can
    /// see, and in Markdown and Djot it draws its own delimiters instead
    /// (`** **`). So the space goes in unmarked — outside any run the armed
    /// marks are shedding — and the marks stay armed for the character after it,
    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
        let base = self.mark_spans_at(at);
        // What the *next* character carries: the armed delta resolved against the
        // marks in force here, which the space must not quietly drop.
        let want = base
            .iter()
            .map(|(k, _)| *k)
            .collect::<InlineMarks>()
            .xor(marks);
        let mut ins_at = at;
        for (kind, span) in &base {
            if marks.contains(*kind) {
                ins_at = ins_at.max(span.end);
            }
        }
        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
            return;
        }
        self.rearm(want);
        self.record_caret();
    }

    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
    /// added split evenly around the content — half the growth on each side.
    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
        match self.editor.toggle_inline(s, e, kind) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                self.dirty = self.source != self.clean_source;
                let added = (change.new.end - change.new.start).saturating_sub(e - s);
                let half = added / 2;
                (change.new.start + half, change.new.end - half)
            }
            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
            // rather than lose the keystroke.
            Err(e2) => {
                self.status = Some(format!("{kind:?}: {e2}"));
                (s, e)
            }
        }
    }

    /// The safe offset to splice a block-level break at, given a caret that may
    /// sit exactly between an inline mark's content and its own closing
    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
    /// with nothing following it on the line: the closing `**` renders no
    /// glyph of its own, so the caret's "end of line" offset lands right
    /// before it). Splicing a paragraph/list/quote break at `off` itself would
    /// sever the delimiter from its content, stranding it alone on the new
    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
    /// nested marks closing at the same point (`**_x_**`) all clear together.
    /// A no-op everywhere else — mid-run, or past real trailing content, no
    /// mark's `content_span` ends exactly at `off`.
    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
        let off = off.min(self.source.len());
        self.editor
            .ancestors_at(off)
            .unwrap_or_default()
            .into_iter()
            .filter(|m| inline_kind(&m.kind).is_some())
            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
            .map(|m| m.span.end)
            .max()
            .unwrap_or(off)
    }

    /// The offset a *delete* aimed at the character before `off` should stop at,
    /// when `off` is the start of a run's text and the bytes behind it are that
    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
    /// byte behind the caret at the start of a bold word is not a character the
    /// writer can see, let alone one they aimed Backspace at: taking it leaves
    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
    /// delete steps over the whole delimiter to the visible character in front of
    /// it instead. Walks out to the *outermost* mark opening there, so
    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
        let off = off.min(self.source.len());
        self.editor
            .ancestors_at(off)
            .unwrap_or_default()
            .into_iter()
            .filter(|m| inline_kind(&m.kind).is_some())
            .filter(|m| {
                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
            })
            .map(|m| m.span.start)
            .min()
            .unwrap_or(off)
    }

    /// `off` moved *inside* the run whose closing delimiters end there — the
    /// other offset the rich view draws in the same place, since a `**` renders
    /// no glyph of its own. `**bold**` has a caret home on each side of its
    /// closing delimiter, one column apart on screen and eight bytes and a whole
    /// run apart in the file, and a plain ← lands on the outer one whenever a
    /// space follows the phrase. The inner one is what the writer is pointing at
    /// there: the end of their bold word. Walks in through every mark closing at
    /// that point, innermost last, so `***both***` lands inside both. A no-op
    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
    fn step_inside_close_delims(&mut self, off: usize) -> usize {
        let mut off = off.min(self.source.len());
        loop {
            let inner = self
                .editor
                .ancestors_at(prev_boundary(&self.source, off))
                .unwrap_or_default()
                .into_iter()
                .filter(|m| inline_kind(&m.kind).is_some() && m.span.end == off)
                .filter_map(|m| m.content_span.clone().map(|c| c.end))
                .filter(|&end| end < off)
                .max();
            match inner {
                Some(end) => off = end,
                None => return off,
            }
        }
    }

    /// The mirror at the opening edge: `off` moved inside the run whose
    /// delimiters *start* there, onto the first character of its text. See
    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
    fn step_inside_open_delims(&mut self, off: usize) -> usize {
        let mut off = off.min(self.source.len());
        loop {
            let inner = self
                .editor
                .ancestors_at(off)
                .unwrap_or_default()
                .into_iter()
                .filter(|m| inline_kind(&m.kind).is_some() && m.span.start == off)
                .filter_map(|m| m.content_span.clone().map(|c| c.start))
                .filter(|&start| start > off)
                .min();
            match inner {
                Some(start) => off = start,
                None => return off,
            }
        }
    }

    /// The inline mark kinds whose span covers `off`, each with that span — the
    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
    /// ids instead. Used to shed a mark by stepping past the end of its run.
    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
        let off = off.min(self.source.len());
        self.editor
            .ancestors_at(off)
            .unwrap_or_default()
            .into_iter()
            .filter(|m| off < m.span.end)
            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
            .collect()
    }

    /// Insert clipboard `text` at the caret, replacing the selection if there is
    /// one — always its own undo step, whatever its length.
    ///
    /// Provenance is the whole point, and only the caller has it. `insert` reads
    /// a lone character as a keystroke and folds it into the run around it,
    /// which is right for typing and wrong for a one-character paste: that paste
    /// would vanish mid-run on an undo it was never part of, and the characters
    /// the user actually typed would go with it. Length can't tell the two
    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
    /// caller comes through is what says which happened.
    pub fn paste(&mut self, text: &str) {
        // Pasting against a block picture dissolves it exactly as typing does,
        // and for the same reason — see `open_paragraph_at_block_media`.
        self.open_paragraph_at_block_media(text);
        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
        self.splice(s, e, text, EditKind::Other);
    }

    /// Replace `[start, end)` with `text` as one step of an IME composition —
    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
    /// folds into a single undo.
    ///
    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
    /// dozen calls here, each replacing the last one's provisional bytes, and an
    /// undo step per call means undoing a word means pressing ⌘Z until the reading
    /// unspools backwards through kana — the intermediate states were never text
    /// the user wrote. Only the frontend knows a call is provisional (the bytes
    /// look like any other edit), so the door the caller comes through is what
    /// says so, exactly as it is for [`paste`](Self::paste) versus
    /// [`insert`](Self::insert).
    ///
    /// Pair with [`end_composition`](Self::end_composition), or the *next*
    /// composition folds into this one.
    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
        self.splice(start, end, text, EditKind::Compose);
    }

    /// Close the open composition run, so the next one is its own undo step.
    /// Call when the IME commits or withdraws a composition.
    ///
    /// Only clears a *composition* run: a frontend that reports an end it never
    /// began (some IMEs unmark unprompted) would otherwise split the run of
    /// typing around it into two undo steps for no reason the user can see.
    pub fn end_composition(&mut self) {
        if self.last_edit_kind == Some(EditKind::Compose) {
            self.last_edit_kind = None;
        }
    }

    // ── the clipboard's rich flavor ──────────────────────────────────────────

    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
    /// nothing is selected, or when the selection doesn't render (the caller
    /// still has [`selected_text`](Self::selected_text), which is what to publish
    /// as `text/plain` either way).
    ///
    /// **The fragment is a source substring, and that is the honest limit here.**
    /// It's parsed standalone, so a selection whose meaning depends on its
    /// surroundings converts as what it literally says rather than what it looks
    /// like on screen: half a list item is a paragraph, a row torn out of a table
    /// is the text of a row, the `**` of a bold run selected without its closing
    /// `**` is two asterisks. Every one of those still *renders* — there's no
    /// error to report — it just renders as the fragment and not as the document.
    /// Widening the range to whole blocks would publish text the user didn't
    /// select, which is a worse lie than a fragment being a fragment; the plain
    /// flavor has the same substring, so the two flavors at least agree.
    pub fn selection_html(&mut self) -> Option<String> {
        let (start, end) = self.selection()?;
        let inline = self.selection_is_inline(start, end);
        let html = html::render_fragment(&self.source[start..end], self.format)?;
        Some(match inline {
            true => html::strip_sole_paragraph(html),
            false => html,
        })
    }

    /// Paste the clipboard's `text/html` flavor, converting it to this document's
    /// format first. Its own undo step, like any [`paste`](Self::paste).
    ///
    /// Returns whether it landed. `false` means the HTML didn't convert to
    /// anything worth pasting — the caller should fall back to the plain flavor
    /// rather than treat it as an error. The `html` module has the full list of
    /// what that covers: a table twig won't build, markup it doesn't recognise,
    /// an empty result.
    pub fn paste_html(&mut self, html: &str) -> bool {
        match html::parse_fragment(html, self.format) {
            Some(source) => {
                self.paste(&source);
                true
            }
            None => false,
        }
    }

    /// Does the selection live *inside* a single top-level block?
    ///
    /// The question [`selection_html`](Self::selection_html) needs and the
    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
    /// whether the user selected one word of a sentence or a whole paragraph, and
    /// only the document knows which. Selecting a word and pasting into Docs
    /// should extend the line you paste into; selecting the paragraph should make
    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
    /// is an artifact of standalone parsing), and one that covers a whole block —
    /// or spans two — keeps its structure.
    ///
    /// Reads the block from twig rather than guessing from the bytes:
    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
    /// block containing an offset, and two ends inside the same one cannot have
    /// crossed a block boundary.
    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
        // The last *character*, not `end - 1`: the selection's end is exclusive
        // and may sit mid-codepoint's-worth of bytes past the last char.
        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
            return false;
        };
        let (Some(head), Some(tail)) =
            (self.top_block_span(start), self.top_block_span(start + off))
        else {
            return false;
        };
        head == tail && !(start <= head.start && end >= head.end)
    }

    /// The byte span of the top-level block containing `offset`, or `None` at an
    /// offset that belongs to no block (the blank line between two of them).
    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
        self.editor
            .ancestors_at(offset)
            .ok()?
            .get(1)
            .map(|m| m.span.clone())
    }

    // ── indentation ──────────────────────────────────────────────────────────

    /// One indent level.
    ///
    /// Two spaces, not the four both frontends type for Tab today, because in a
    /// markdown document four columns isn't a width — it's a *meaning*. Four
    /// spaces at the head of a line is markdown's indented-code-block marker, so
    /// one Tab on a paragraph would reparse it into code and style it as such;
    /// two cannot, and the line stays the prose it was. Two is also exactly
    /// where a `- ` bullet's content starts, so an indented line lands under its
    /// parent item's text instead of beside it — the column a list-aware indent
    /// has to hit anyway, which keeps this width from being relitigated later.
    const INDENT: &'static str = "  ";

    /// Indent the selected lines — or the caret's line, with no selection — by
    /// one level (Tab).
    pub fn indent(&mut self) {
        self.reindent(true);
        // Nesting changes an ordered list's numbering (the nested item restarts,
        // its old siblings resume) — keep the source markers in step.
        self.renumber_here();
        // Nesting an empty `-` item under a text line reparses that text as a
        // setext heading; swap the dash for a `*` before it can (a no-op unless
        // the collapse actually happened).
        self.avoid_setext_collapse();
    }

    /// Take one indent level back off the selected lines, or the caret's line
    /// (Shift+Tab). A line with no indentation is left exactly as it is.
    ///
    /// A line with *less* than a full level gives back what it has rather than
    /// refusing: outdent's job is to walk a line left, and real documents — hand
    /// written, or reflowed by some other editor — are full of indentation that
    /// was never a clean multiple of anything. Refusing there would strand the
    /// line at a depth Shift+Tab couldn't undo.
    pub fn outdent(&mut self) {
        self.reindent(false);
        self.renumber_here();
    }

    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
    ///
    /// One splice across the whole line range, never one per line: a Tab is one
    /// thing the user did, so it has to be one undo step and one reparse. Per
    /// line, twig would reparse the document once per line and leave a stack of
    /// steps that Shift+⌘Z walks back one line at a time.
    fn reindent(&mut self, add: bool) {
        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
        let start = source_line_range(&self.source, sel_start).start;
        let end = source_line_range(&self.source, sel_end).end;
        let region = self.source[start..end].to_string();
        let lines: Vec<&str> = region.split('\n').collect();
        // A blank line has no text to move, and padding it would leave nothing
        // but trailing whitespace — but Tab on a blank line *is* a request for
        // indentation to type into, so the skip only applies where the op has
        // other lines to do real work on.
        let skip_blank = add && lines.len() > 1;

        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
        let mut line_off = start;
        for (i, full) in lines.iter().enumerate() {
            if i > 0 {
                out.push('\n');
            }
            // A list item moves by having its whole leading prefix *replaced*,
            // never by having spaces pushed in front of the line. twig spells
            // both prefixes, so the quote markers, the parent's indent and an
            // ordered marker's extra column all come out right without leaf
            // measuring any of them — and a line that only looks like an item
            // (a Djot continuation) reports no marker and is left to the plain
            // path, where a Tab is just a Tab.
            let marker = self.list_marker_on_line(line_off);
            let own = marker
                .as_ref()
                .map(|m| m.marker_start - m.line_start)
                .unwrap_or(0);
            let delta = if add {
                if skip_blank && full.trim().is_empty() {
                    out.push_str(full);
                    0
                } else if marker.is_some() && self.first_item_of_list(line_off) {
                    // The first item of a list has no preceding sibling to nest
                    // under, so a Tab here can't spell a sub-list — twig would
                    // reparse the shoved-over marker as the same list, only
                    // indented, which Shift+Tab then can't cleanly undo. Leave the
                    // item where it is, the way every list editor refuses to
                    // over-indent a list's first line.
                    out.push_str(full);
                    0
                } else if marker.is_some() {
                    // Nesting means standing where a *continuation* of this line
                    // would stand: past the parent's marker, inside its content
                    // column. That is `continuation_prefix`, less a checkbox.
                    let new = self.nesting_prefix_at(line_off);
                    let delta = new.len() as isize - own as isize;
                    out.push_str(&new);
                    out.push_str(&full[own..]);
                    delta
                } else {
                    out.push_str(Self::INDENT);
                    out.push_str(full);
                    Self::INDENT.len() as isize
                }
            } else if marker.is_some() {
                // Unnesting is the mirror: stand where the parent item's own
                // line starts, which drops exactly the level it contributed.
                let new = self.outdent_prefix_at(line_off);
                let delta = new.len() as isize - own as isize;
                out.push_str(&new);
                out.push_str(&full[own..]);
                delta
            } else {
                // A plain line gives back the ordinary step.
                let strip = outdent_width(full, Self::INDENT.len());
                out.push_str(&full[strip..]);
                -(strip as isize)
            };
            deltas.push(delta);
            line_off += full.len() + 1;
        }
        // Nothing to give back. Returning before the splice keeps an outdent at
        // column zero from spending an undo step on a document it never changed.
        if deltas.iter().all(|d| *d == 0) {
            return;
        }

        // Every line's text keeps its offset *within the line*, so the caret is
        // remapped by its column, not by its byte offset — which the prefixes on
        // the lines above it have already invalidated.
        let remap = |off: usize| -> usize {
            let (mut old_ls, mut new_ls) = (start, start);
            for (line, delta) in lines.iter().zip(&deltas) {
                let old_le = old_ls + line.len();
                let new_len = (line.len() as isize + delta) as usize;
                if off <= old_le {
                    let col = (off - old_ls) as isize;
                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
                }
                old_ls = old_le + 1;
                new_ls += new_len + 1;
            }
            start + out.len()
        };
        let placed = match self.selection() {
            // Keep the rewritten region selected, the way a container toggle
            // keeps its own: it leaves a second Tab aimed at the same lines
            // rather than at whatever the shifted offsets now happen to cover.
            Some(_) => (start + out.len(), Some(start)),
            None => (remap(self.caret), None),
        };

        // A rolled-back splice leaves the old source in place, where every offset
        // computed above addresses text that was never written.
        if !self.splice(start, end, &out, EditKind::Other) {
            return;
        }
        // `splice` re-anchors to the end of the `Change`, which for a whole-region
        // rewrite is the last line's end — nowhere the caret was. Place it, then
        // re-record the caret so this is the state redo restores, not the one
        // `splice` left behind from the `Change`.
        self.caret = placed.0.min(self.source.len());
        self.anchor = placed.1;
        self.clamp_caret();
        self.record_caret();
    }

    /// The Enter key.
    ///
    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
    /// caret is in decides what actually gets written.
    ///
    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
    ///                            block at the caret and reopens its container
    ///   - list item            → likewise: the next item, its indent, quote
    ///                            prefix and `[ ]` box all reproduced by twig —
    ///                            except an *empty* item, which exits the list
    ///   - block quote          → likewise: a new paragraph inside the quote
    ///   - heading              → a new *paragraph*, not another heading
    ///   - code block           → a literal newline (stay in the block)
    ///   - blank line           → a literal newline (one Backspace undoes it)
    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
    ///                            visible line
    ///
    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
    /// and it is better at it: it drops the whitespace the caret was sitting in
    /// front of instead of stranding it at the head of the second half, and it
    /// knows continuations leaf's marker scan never covered — a checklist item
    /// continues as an *unchecked* checklist item rather than a plain bullet.
    ///
    /// The exceptions above are exceptions because `split_block` is either wrong
    /// there or refuses: parting a fence yields two fences with the code split
    /// between them, parting a heading yields a second heading where every editor
    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
    /// table all report an error rather than a split.
    pub fn newline(&mut self) {
        if self.view == View::Source {
            self.insert_raw("\n");
            return;
        }
        // Enter over a selection replaces it with a paragraph break.
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "\n\n", EditKind::Other);
            return;
        }
        // A caret resting exactly between an inline mark's content and its own
        // closing delimiter (`**bold**` with nothing after it on the line —
        // the WYSIWYG caret's natural end-of-line position) must not splice a
        // block break there: every path below eventually does via
        // `insert_raw`/`self.caret`, and splicing before the hidden closing
        // delimiter would strand it alone on the new line.
        self.caret = self.skip_trailing_close_delims(self.caret);
        // The block the caret is in. `block_offset_for_caret` nudges off a line
        // end (where the caret sits at the doc level); on a bare line (e.g. an
        // empty list item) fall back to the caret so the enclosing list/quote is
        // still visible in the ancestors.
        let off = self.block_offset_for_caret().unwrap_or(self.caret);
        let kinds: Vec<Kind> = self
            .editor
            .ancestors_at(off)
            .map(|c| c.into_iter().map(|m| m.kind).collect())
            .unwrap_or_default();
        let has = |k: Kind| kinds.contains(&k);

        if has(Kind::CodeBlock) {
            self.insert_raw("\n");
            return;
        }
        // An *empty* list item exits the list — the standard double-Enter — which
        // `split_block` reports as an error rather than a split (there is no
        // content to part), so it stays leaf's. `list_marker_on_line` is itself
        // the AST gate — it answers from the tree, so a `- ` that reads as a
        // marker byte-for-byte but opens no item (a setext underline, a Djot
        // continuation line) never reaches here.
        if let Some(marker) = self.list_marker_on_line(self.caret)
            && self.item_is_empty(&marker)
        {
            self.exit_list(&marker);
            return;
        }
        // On an *empty* paragraph line, a lone Enter should add a single blank line,
        // not another full paragraph break — so it moves down one line and one
        // Backspace undoes it, not two. (`split_block` errors here too.)
        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
        let line_end = self.source[self.caret..]
            .find('\n')
            .map_or(self.source.len(), |i| self.caret + i);
        if self.source[line_start..line_end].trim().is_empty() {
            self.insert_raw("\n");
            return;
        }
        // In `Preserve` flow a soft break is a *visible* line the author means to
        // make, so Enter writes a single `\n` and typing continues the same
        // paragraph on the next line — the behaviour of an ordinary text editor.
        // A second Enter then lands on the blank line above and takes the
        // empty-line branch, so double-Enter still promotes to a full paragraph
        // break; and Backspace, which deletes a lone `\n` over a soft break,
        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
        // render as an invisible space, so Enter keeps making the paragraph break
        // that actually shows.
        //
        // Only in running prose. A list or a quote has a continuation of its own
        // to write, and a `\n` there is not a soft line but a lost container.
        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
        if self.line_flow == LineFlow::Preserve && !in_container {
            self.insert_raw("\n");
            return;
        }
        // A heading gets a *paragraph*, never a second heading: Enter at the end
        // of a title is how every editor is asked for the body under it, and
        // `split_block` would repeat the `#` instead. Whitespace at the split
        // point goes with the break rather than opening the new paragraph, which
        // is what `split_block` does everywhere else.
        if has(Kind::Heading) {
            let mut end = self.caret;
            while self.source.as_bytes().get(end) == Some(&b' ') {
                end += 1;
            }
            self.splice(self.caret, end, "\n\n", EditKind::Other);
            return;
        }
        self.split_block_here();
    }

    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
    /// the caret in the second half.
    ///
    /// twig reopens whatever the first half was inside of — the bullet with its
    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
    /// reason this replaced the markup leaf used to spell from the line's bytes.
    /// It renumbers nothing, though: a new item mid-list is written with its
    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
    /// behind it, folded into the same undo step.
    ///
    /// Falls back to a plain paragraph break if twig declines, so an unhandled
    /// shape still moves the caret down rather than swallowing the keystroke.
    fn split_block_here(&mut self) {
        match self.editor.split_block(self.caret) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                self.anchor = None;
                self.caret = change.new.end;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
                // Aimed at the new block's *start*: the caret twig leaves is one
                // past the marker it wrote, where there is no list in reach.
                self.renumber_at(change.new.start);
            }
            Err(_) => self.insert_raw("\n\n"),
        }
    }

    /// Whether the item on the marker's line carries no content — the shape
    /// double-Enter reads as "I'm done with this list."
    fn item_is_empty(&self, line: &ListMarker) -> bool {
        let content_start = line.content_start().min(self.source.len());
        let line_end = self.source[self.caret..]
            .find('\n')
            .map(|i| self.caret + i)
            .unwrap_or(self.source.len());
        self.source[content_start..line_end.max(content_start)]
            .trim()
            .is_empty()
    }

    /// Leave the list: replace the empty item's marker with a blank line, so the
    /// caret lands in a fresh paragraph below it.
    ///
    /// Inside a quote the blank line has to stay quoted (a bare one would end the
    /// quote), and the caret's new line keeps the `> ` it was already behind —
    /// leaving the list without also leaving the quote.
    fn exit_list(&mut self, line: &ListMarker) {
        let prefix = self.quote_prefix_at(line.marker_start);
        let blank = prefix.trim_end();
        self.splice(
            line.line_start,
            self.caret,
            &format!("{blank}\n{prefix}"),
            EditKind::Other,
        );
    }

    /// What a line continuing the containers at `off` has to open with — the
    /// quote markers reproduced, each enclosing item's marker as its width in
    /// spaces. Also the column a nested item's marker stands in, which is what
    /// makes it Tab's answer.
    fn continuation_prefix_at(&mut self, off: usize) -> String {
        self.editor
            .document()
            .and_then(|mut d| d.continuation_prefix(off))
            .map(|p| p.text)
            .unwrap_or_default()
    }

    /// The column a *nested list* may open at inside the item at `off` — which
    /// is not always where the item's own text continues.
    ///
    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
    /// it is markup a rich view hides, and the item's own wrapped text does
    /// stand past it. But a nested list may only open at the *list* marker's
    /// column, and four columns further in is an indented continuation of the
    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
    /// So the box's own width goes back.
    ///
    /// The one place leaf still reads a checkbox's spelling. It goes when twig
    /// reports the list marker's column apart from the box; `checked` is what
    /// says a box is there at all, so only its width is being measured here.
    fn nesting_prefix_at(&mut self, off: usize) -> String {
        let cont = self.continuation_prefix_at(off);
        let Some(item) = self.innermost_list_item(off) else {
            return cont;
        };
        if item.checked.is_none() {
            return cont;
        }
        let box_width = item
            .marker_span
            .and_then(|m| self.source.get(m))
            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
            .unwrap_or(0);
        // The trailing columns are the ones the item's own marker contributed,
        // so trimming from the end leaves any quote prefix standing.
        cont[..cont.len().saturating_sub(box_width)].to_string()
    }

    /// Where the line of the item *containing* the item at `off` begins — the
    /// prefix Shift+Tab moves back to, which gives up exactly the level the
    /// parent contributed. The quote prefix alone for a top-level item, which
    /// has no level left to give.
    fn outdent_prefix_at(&mut self, off: usize) -> String {
        let items: Vec<usize> = self
            .editor
            .document()
            .and_then(|mut d| d.ancestors_at_caret(off))
            .map(|c| {
                c.into_iter()
                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
                    .map(|m| m.span.start)
                    .collect()
            })
            .unwrap_or_default();
        // The second-innermost item is the parent; its own line's indent is the
        // target. `list_marker_on_line` gives that line's prefix directly.
        let parent = items.len().checked_sub(2).map(|i| items[i]);
        match parent.and_then(|p| self.list_marker_on_line(p)) {
            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
            None => self.quote_prefix_at(off),
        }
    }

    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
    /// inside one, `"> > "` inside two.
    ///
    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
    /// the `>` and the space after it are twig's spelling rather than leaf's.
    /// The whole line prefix can't answer this: it also carries the indent of
    /// whatever the quote holds, which a blank separator line must *not* repeat.
    fn quote_prefix_at(&mut self, off: usize) -> String {
        let Ok(chain) = self
            .editor
            .document()
            .and_then(|mut d| d.ancestors_at_caret(off))
        else {
            return String::new();
        };
        let quotes: Vec<usize> = chain
            .iter()
            .filter(|m| m.kind == Kind::BlockQuote)
            .map(|m| m.node_id as usize)
            .collect();
        let Ok(nodes) = self.editor.nodes() else {
            return String::new();
        };
        quotes
            .iter()
            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
            .filter_map(|s| self.source.get(s))
            .collect()
    }

    /// Whether the item at `off` sits inside another one — the test Backspace
    /// uses to choose between outdenting and dropping the marker.
    ///
    /// Counted from the AST rather than from the line's leading whitespace,
    /// which is indentation in Markdown and, in Djot, may be nothing at all.
    fn item_is_nested(&mut self, off: usize) -> bool {
        self.editor
            .document()
            .and_then(|mut d| d.ancestors_at_caret(off))
            .map(|c| {
                c.into_iter()
                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
                    .count()
                    > 1
            })
            .unwrap_or(false)
    }

    /// The innermost list item containing `probe`, under twig's **caret**
    /// containment rule — a block's end is inside it.
    ///
    /// Half-open containment can't answer this. An empty item's span is exactly
    /// its marker, so the caret sitting after `- ` is one past the end and the
    /// item it is plainly in tests as out of reach; that is the shape
    /// double-Enter has to recognise to leave the list.
    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
        let chain = self
            .editor
            .document()
            .and_then(|mut d| d.ancestors_at_caret(probe))
            .ok()?;
        let id = chain
            .iter()
            .rev()
            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
            .node_id as usize;
        self.editor.nodes().ok()?.get(id).cloned()
    }

    /// The list marker opening `off`'s line, per twig — `None` when that line
    /// opens no list item.
    ///
    /// [`Document::line_prefix`] is the whole hidden run from the line start:
    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
    /// and it is `None` on a *continuation* line, which opens nothing. That last
    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
    /// a paragraph and `  - b` is literal text — identical bytes, and only the
    /// parser knows which document it is looking at.
    ///
    /// The item's own marker is separated out via its
    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
    /// the containers around it contribute and what the item does.
    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
        let off = off.min(self.source.len());
        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
        // The prefix belongs to a list only when an item's marker closes it —
        // a heading's `# ` or a bare quote's `> ` is a prefix too.
        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
        let marker = item.marker_span.clone()?;
        if marker.end != prefix.end {
            return None;
        }
        Some(ListMarker {
            line_start: prefix.start,
            marker_start: marker.start,
            text: self.source.get(prefix)?.to_string(),
        })
    }

    /// Whether the list item on `line_start`'s line is the **first item** of its
    /// list — the one Tab must not nest, because nesting needs a preceding
    /// sibling to become the new parent and a first item has none. `false` for a
    /// line that isn't a list item, and for an item with a sibling above it (the
    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
    /// the same in a setext underline that opens no list at all.
    fn first_item_of_list(&mut self, line_start: usize) -> bool {
        let Some(marker) = self.list_marker_on_line(line_start) else {
            return false;
        };
        // Probe just inside the marker, where the item's own node is in reach —
        // the marker offset itself can resolve to the enclosing list, not the
        // `list_item`, whose span starts at the marker.
        let probe = marker.content_start().min(self.source.len());
        let Some(item) = self.innermost_list_item(probe) else {
            return false;
        };
        let Ok(nodes) = self.editor.nodes() else {
            return false;
        };
        match item.parent {
            // First when the parent list opens with this very item.
            Some(pid) => nodes
                .get(pid.0 as usize)
                .is_some_and(|p| p.first_child == Some(item.id)),
            // A parentless item is trivially the first (and only) one.
            None => true,
        }
    }

    pub fn backspace(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
            return;
        }
        // WYSIWYG: Backspace at the very start of a list item's content is a
        // structural key, not a character delete — it walks the "un-indent, then
        // un-list" ladder every list editor gives that keystroke (outdent a
        // nested item, strip a top-level one's marker to a paragraph). In source
        // view the `- ` is visible text the user is deleting a byte of, so it
        // keeps its literal meaning there, like Enter does.
        if self.view != View::Source && self.backspace_list_start() {
            return;
        }
        // WYSIWYG: and the same at the start of a heading's content — the `# `
        // there is markup the rich view hides, not text the user typed.
        if self.view != View::Source && self.backspace_heading_start() {
            return;
        }
        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
        // the markup apart under a caret that cannot see it — see
        // `delete_around_block_media`.
        if self.view != View::Source && self.delete_around_block_media(false) {
            return;
        }
        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
        // stop, not a single newline. On a line with no text of its own, the byte
        // before the caret is a `\n` that spells part of a block boundary — the gap
        // between two blocks, drawn but never a caret home. Removing just it strands
        // the caret in that gap and leaves an odd blank line the eye reads as one
        // separator but the caret can't land on: the "extra newline" left behind
        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
        // Deleting to the previous stop instead collapses the whole break at once,
        // landing the caret at the end of the block above. Two blank lines in a row
        // are one stop apart, so this still removes exactly one — the lone-Enter /
        // lone-Backspace symmetry the empty-line case is built on is untouched.
        if self.view != View::Source
            && self.caret > self.caret_floor()
            && self.caret_on_blank_line()
            && let Some(stop) = self.vmap.stop_before(self.caret)
        {
            let stop = stop.max(self.caret_floor());
            if stop < self.caret {
                self.splice(stop, self.caret, "", EditKind::Delete);
                return;
            }
        }
        if self.caret > self.caret_floor() {
            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
            // takes the whole tag — a single-byte step would leave a broken `<br`
            // showing in the cell. Rich view only (source view edits the literal).
            if self.view != View::Source
                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
            {
                let start = start.max(self.caret_floor());
                if start < end {
                    self.splice(start, end, "", EditKind::Delete);
                    return;
                }
            }
            // Aim the delete at the character the writer can *see* behind the
            // caret, never at a delimiter the rich view drew nothing for. Two
            // steps, and either can apply: from the far side of a run's closing
            // `**` step back into the run (the caret is drawn at the end of its
            // word), and at the start of a run's text step out past its opening
            // `**` to the character in front of it, leaving the run standing.
            // Without them a plain Backspace unspells the phrase it is editing
            // and leaves a literal asterisk on screen.
            let end = if self.view == View::Source {
                self.caret
            } else {
                let inside = self.step_inside_close_delims(self.caret);
                self.skip_leading_open_delims(inside)
                    .max(self.caret_floor())
            };
            // Never delete back across the floor — that would eat hidden
            // frontmatter the WYSIWYG caret can't even see.
            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
            // Take a hidden escape backslash with the char it escapes: the rich
            // view draws `\*` as a single `*`, so Backspace over it must delete
            // both bytes, never strand the `\` as a lone visible backslash (the
            // mirror of the Hidden-mode typing that wrote the escape). Source view
            // shows the `\`, so there it is an ordinary character.
            if self.view != View::Source
                && prev > self.caret_floor()
                && self.is_hidden_escape(prev - 1)
            {
                prev -= 1;
            }
            if prev < end {
                self.splice(prev, end, "", EditKind::Delete);
            }
        }
    }

    /// Whether the caret's own source line holds nothing but whitespace — an
    /// empty paragraph, or the blank line a block boundary is spelled with. The
    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
    /// no text of its own, so the newline before the caret belongs to the gap
    /// between blocks rather than to any word the caret is editing.
    fn caret_on_blank_line(&self) -> bool {
        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
        let line_end = self.source[self.caret..]
            .find('\n')
            .map_or(self.source.len(), |i| self.caret + i);
        self.source[line_start..line_end].trim().is_empty()
    }

    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
    /// `edge` side — the byte range to delete whole. A table row is one source
    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
    /// apart — no ancestor walk needed. Rich view only; source view shows the
    /// literal tag and deletes it a byte at a time.
    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
        let caret = self.caret;
        let nodes = self.nodes();
        let src = self.source.as_bytes();
        nodes
            .iter()
            .find(|n| {
                n.kind == Kind::HardBreak
                    && n.span.start < n.span.end
                    && src.get(n.span.start) == Some(&b'<')
                    && match edge {
                        BreakEdge::Backward => n.span.end == caret,
                        BreakEdge::Forward => n.span.start == caret,
                    }
            })
            .map(|n| (n.span.start, n.span.end))
    }

    /// Whether the source byte at `off` is a backslash twig consumed as an escape
    /// (hidden in the rich view), as against a literal backslash (drawn). A
    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
    /// round-trip needed.
    fn is_hidden_escape(&self, off: usize) -> bool {
        let b = self.source.as_bytes();
        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
    }

    /// Backspace's list behaviour: when the caret sits exactly at the start of a
    /// list item's content (right after its marker), outdent the item if it's
    /// nested, else strip the marker so it becomes a paragraph. Returns whether
    /// it acted — `false` leaves Backspace its ordinary character delete.
    fn backspace_list_start(&mut self) -> bool {
        let Some(marker) = self.list_marker_on_line(self.caret) else {
            return false;
        };
        // Only right after the marker. That the line opens a real item is
        // already settled: `list_marker_on_line` answers from the tree.
        if self.caret != marker.content_start() {
            return false;
        }
        if self.item_is_nested(marker.marker_start) {
            // Nested: give back one level, keeping the marker and carrying the
            // caret with it.
            self.outdent();
        } else {
            // Top level: drop the marker, leaving a paragraph, then renumber the
            // siblings the removed item was counted among. Only the marker goes —
            // a quote prefix in front of it still has a quote to hold up.
            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
            self.renumber_here();
        }
        true
    }

    /// Backspace's heading behaviour: with the caret exactly at the start of an
    /// ATX heading's content — right after the `#` marker the rich view hides —
    /// strip the marker so the line becomes a paragraph. The peer of
    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
    /// reasoning: hidden block markup is structure, so the keystroke over it is
    /// structural.
    ///
    /// Without this the ordinary delete takes the space out of `# Title` and
    /// leaves `#Title`, which is no longer a heading at all — the hash the view
    /// had been hiding surfaces as literal text the user has to delete a second
    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
    /// other end) goes with the marker for the same reason.
    ///
    /// Returns whether it acted; `false` leaves Backspace its character delete.
    fn backspace_heading_start(&mut self) -> bool {
        let caret = self.caret;
        // The heading whose content opens exactly at the caret. A bare `#` has no
        // content span at all — its content starts (and ends) where the line does.
        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
            let (start, end) = match &n.content_span {
                Some(c) => (c.start, c.end),
                None => (n.span.end, n.span.end),
            };
            (n.kind == Kind::Heading && start == caret)
                .then(|| (n.span.clone(), end, n.marker_span.clone()))
        }) else {
            return false;
        };
        // twig reports the marker's own extent, so there is nothing to walk back
        // over and no `#` in this file. A setext heading has no marker — its
        // content opens the line — so it falls through to the ordinary delete,
        // as does anything else sitting at a content start.
        // `m.end == caret` is what excludes a setext heading, whose marker is the
        // underline *after* the content rather than a prefix before it.
        let Some(marker) = marker.filter(|m| m.end == caret) else {
            return false;
        };
        let start = marker.start;
        // A closing `#` sequence is hidden too, so it can't be left behind. Only
        // when the tail really is one: trailing spaces alone are nothing to strip.
        let tail = &self.source[content_end..span.end];
        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
            let kept = self.source[caret..content_end].to_string();
            self.splice(start, span.end, &kept, EditKind::Other);
            // The splice leaves the caret past the text it re-wrote; the caret
            // belongs where the content now starts, which is where it already was.
            self.caret = start;
            self.record_caret();
        } else {
            self.splice(start, caret, "", EditKind::Other);
        }
        true
    }

    pub fn delete_forward(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
        } else if self.caret < self.source.len() {
            // The mirror of Backspace's: forward-delete in front of a picture
            // would eat the `!` off its markup and leave a link where a photo was.
            if self.view != View::Source && self.delete_around_block_media(true) {
                return;
            }
            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
            // strands a broken `<br` in the cell.
            if self.view != View::Source
                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
            {
                self.splice(start, end, "", EditKind::Delete);
                return;
            }
            // The mirror of Backspace's two steps: from in front of a run's
            // opening `**` step into it, onto the first letter of its text, and
            // at the end of a run's text step out past its closing `**` to the
            // character beyond. Either way Delete takes the character it looks
            // like it is pointing at, and never a delimiter drawn as nothing.
            // The caret then settles back inside the run it was standing in —
            // see `settle_inside_close_delims`.
            let from = if self.view == View::Source {
                self.caret
            } else {
                let inside = self.step_inside_open_delims(self.caret);
                self.skip_trailing_close_delims(inside)
            };
            let next = next_boundary(&self.source, from);
            if from < next {
                self.splice(from, next, "", EditKind::Delete);
            }
        }
    }

    /// Delete from the caret back to the start of the previous word (⌥⌫ /
    /// Ctrl+⌫). Deletes the selection instead when one is active.
    pub fn delete_word_back(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
        } else {
            // A word back from just past a picture is a word *of its markup*, and
            // a word back from in front of one runs through the paragraph break
            // into the prose above — dissolving the picture either way. See
            // `delete_around_block_media`.
            if self.view != View::Source && self.delete_around_block_media(false) {
                return;
            }
            let start = self.word_left_from(self.caret).max(self.caret_floor());
            if start < self.caret {
                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
                self.splice(s, e, "", EditKind::Delete);
            }
        }
    }

    /// Delete from the caret forward to the end of the next word (⌥⌦ /
    /// Ctrl+Del). Deletes the selection instead when one is active.
    pub fn delete_word_forward(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
        } else {
            // The mirror: a word forward from in front of a picture is its markup.
            if self.view != View::Source && self.delete_around_block_media(true) {
                return;
            }
            let end = self.word_right_from(self.caret);
            if end > self.caret {
                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
                self.splice(s, e, "", EditKind::Delete);
            }
        }
    }

    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
    /// selection instead when one is active, as every other delete here does.
    ///
    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
    /// stops at the first character and this takes the indentation with it, the
    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
    /// leave an indent behind that nothing can then ask to delete, where a caret
    /// left at column 0 is one press of Home away from either.
    pub fn delete_to_line_start(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
            return;
        }
        // Never back across the floor: hidden frontmatter isn't on this line, or
        // on any line the WYSIWYG caret can see.
        let (start, _) = self.line_span();
        let start = start.max(self.caret_floor());
        if start < self.caret {
            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
            self.splice(s, e, "", EditKind::Delete);
        }
    }

    /// Kill from the caret to the end of its line (^K). Deletes the selection
    /// instead when one is active.
    ///
    /// At the end of the line it does nothing, rather than pulling the line
    /// below up into this one. Joining has no meaning to give it in both views
    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
    /// there is nothing there to delete, while the newline a *source* line ends
    /// with is only half of the blank line that separates two paragraphs —
    /// deleting one leaves a soft break, which is not the join it looks like.
    /// The views agreeing is worth more than emacs' second press, and Delete is
    /// already the key that joins.
    pub fn delete_to_line_end(&mut self) {
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
            return;
        }
        let (_, end) = self.line_span();
        if end > self.caret {
            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
            self.splice(s, e, "", EditKind::Delete);
        }
    }

    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
    ///
    /// A glyph-space range covers what the user can see, which for `**bold**` is
    /// the word and never the delimiters around it — so deleting the word on its
    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
    /// word, and the styling was the word's; the two go together. Only the
    /// node's delimiters are taken, and those are hidden here anyway, so nothing
    /// visible outside the range is lost.
    ///
    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
    /// the strong, and only then is the strong empty too.
    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
        if self.view == View::Source {
            return (start, end);
        }
        let nodes = self.nodes();
        let (mut s, mut e) = (start, end);
        loop {
            let mut grew = false;
            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
                let Some(text) = inline_content_span(n, &self.source) else {
                    continue;
                };
                // Some of its text survives, so the node still has a job.
                if text.start < s || text.end > e {
                    continue;
                }
                if n.span.start < s || n.span.end > e {
                    s = s.min(n.span.start);
                    e = e.max(n.span.end);
                    grew = true;
                }
            }
            if !grew {
                return (s, e);
            }
        }
    }

    /// One splice of document text, keeping the **mark-edge rule**: an inline
    /// mark's content never begins or ends with whitespace. In Markdown and Djot
    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
    /// is four literal asterisks around a word, and a rich view drawing the
    /// document faithfully has no choice but to show them. That is correct
    /// rendering of what the file says, and nobody typing a space after a bold
    /// word meant to say it.
    ///
    /// So the space goes *outside* the run instead — `**bold** ` — which is the
    /// same document to a reader and a live one to a parser. The caret follows it
    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
    ///
    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
    /// through here, so the rule holds however the whitespace arrives at the
    /// edge. The repair is decided *after* the plain edit, by asking whether the
    /// mark actually died: a code span's backticks aren't whitespace-sensitive
    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
        let fix = self.mark_edge_fix(start, end, text);
        if !self.splice_exact(start, end, text, kind) {
            return false;
        }
        if let Some(fix) = fix {
            self.repair_mark_edges(fix);
        }
        if text.is_empty() && end > start {
            self.settle_inside_close_delims();
        }
        true
    }

    /// After a delete, take a caret left standing past a run's closing delimiters
    /// back inside the run.
    ///
    /// A delete leaves the caret where the deleted bytes began, and when those
    /// bytes were the last thing after a marked phrase — the space the mark-edge
    /// rule pushed out of `**bold** `, say — that spot is the far side of the
    /// closing `**`. The rich view has nothing to draw there: the delimiters are
    /// hidden, so the caret shows at the end of the word either way, and the two
    /// offsets are one place on screen with two different meanings. Typing at the
    /// outer one lands past the run, so the writer who backspaced a space out of
    /// their bold phrase watches the next character come out plain, and the
    /// toolbar button go dark, with the caret never appearing to move.
    ///
    /// The end of the run's text is the caret's home there — a delete that took
    /// away everything after a phrase leaves the caret at the end of that phrase,
    /// which is inside it — so it settles onto that
    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
    /// walk, through every mark closing at the point): the word stays bold, the
    /// button stays lit, and the next character carries on the phrase.
    ///
    /// Rich view only, and only where a mark really closes at the caret — mid-run
    /// or in plain prose no span ends there and the caret stays put. The opening
    /// edge is left alone on purpose: a caret in front of a run inherits from the
    /// text on its left, which is the plain text outside.
    fn settle_inside_close_delims(&mut self) {
        if self.view != View::Wysiwyg {
            return;
        }
        let at = self.step_inside_close_delims(self.caret);
        if at != self.caret {
            self.caret = at;
            self.clear_pending();
            self.record_caret();
        }
    }

    /// The splice exactly as asked, with no mark-edge repair — for the callers
    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
    /// the bytes they inserted.
    ///
    /// One `edit_range` through twig, then re-anchor the caret from the returned
    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
    /// Markdown/Djot) leaves the document untouched and reports.
    ///
    /// Returns whether the edit landed — for a caller that has offsets of its
    /// own to place afterwards, which a rolled-back splice would leave pointing
    /// into text that never came to exist.
    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
        // twig records an undo step for every edit; when this one continues a
        // run of the same kind (typing, deleting), tell twig to fold it into the
        // step before it so the whole run undoes at once.
        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
        // Hand twig the pre-edit caret before the splice, so the undo step it
        // retires carries where the caret was standing.
        self.record_caret();
        match self.editor.edit_range(start, end, text) {
            Ok(change) => {
                if coalesce {
                    let _ = self.editor.coalesce_last_undo();
                }
                self.last_edit_kind = Some(kind);
                self.refresh();
                self.caret = change.new.end;
                self.anchor = None;
                self.goal_col = None;
                self.clear_pending();
                self.dirty = self.source != self.clean_source;
                self.status = None;
                // And the post-edit caret, so a later redo restores it.
                self.record_caret();
                true
            }
            // The edit was rolled back, so twig's history did not move and
            // neither may ours: pushing here would leave a step with no edit
            // under it and shift every later undo onto the wrong caret.
            Err(e) => {
                self.status = Some(format!("edit: {e}"));
                false
            }
        }
    }

    /// The re-spelling that would keep the mark-edge rule for the edit
    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
    /// against a delimiter and the plain splice is already right. Computed
    /// *before* the edit, while the run's spans and delimiters can still be read
    /// off the document; applied afterwards, and only if the mark really died —
    /// see [`repair_mark_edges`](Self::repair_mark_edges).
    ///
    /// Rich view only. Source view is for typing raw markup, where a space put
    /// against a `**` is exactly the character it looks like.
    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
            return None;
        }
        // Every inline mark standing over the edit, outermost first, with the
        // content span that says where its delimiters are.
        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
            .editor
            .ancestors_at(start)
            .unwrap_or_default()
            .into_iter()
            .filter_map(|m| {
                let kind = inline_kind(&m.kind)?;
                let content = m.content_span.clone()?;
                Some((kind, m.span.clone(), content))
            })
            .collect();
        // The innermost run whose *content* holds the whole edit: the one whose
        // text is being changed, rather than one the edit merely sits under.
        let (kind, span, content) = chain
            .iter()
            .rev()
            .find(|(_, _, c)| c.start <= start && end <= c.end)?
            .clone();
        // What that content becomes. Whitespace at either end of it is what
        // would put out the mark.
        let body = format!(
            "{}{text}{}",
            &self.source[content.start..start],
            &self.source[end..content.end]
        );
        let (lead, trail) = if body.trim().is_empty() {
            // Nothing but whitespace left: there is no content to mark at all,
            // and the delimiters go with it rather than closing on a space.
            (body.len(), 0)
        } else {
            (
                body.len() - body.trim_start().len(),
                body.len() - body.trim_end().len(),
            )
        };
        // Nothing against a delimiter, and something still between them: the
        // plain edit stands. An emptied run is broken just as surely (`**b**`
        // with the `b` deleted is the literal `****`) and is re-spelt as the
        // nothing it now says.
        if lead == 0 && trail == 0 && !body.is_empty() {
            return None;
        }
        // Marks that open or close exactly where this one does — `***both***` is
        // two runs sharing an edge — spell their delimiters as one run of bytes,
        // so the whitespace has to clear all of them together.
        let (mut open_at, mut close_at) = (span.start, span.end);
        for _ in 0..chain.len() {
            match chain.iter().find(|(_, _, c)| c.start == open_at) {
                Some((_, s, _)) => open_at = s.start,
                None => break,
            }
        }
        for _ in 0..chain.len() {
            match chain.iter().find(|(_, _, c)| c.end == close_at) {
                Some((_, s, _)) => close_at = s.end,
                None => break,
            }
        }
        let open = &self.source[open_at..content.start];
        let close = &self.source[content.end..close_at];
        let core = &body[lead..body.len() - trail];
        let respelt = if core.is_empty() {
            body.clone()
        } else {
            format!(
                "{}{open}{core}{close}{}",
                &body[..lead],
                &body[body.len() - trail..]
            )
        };
        // The caret sits just past the inserted text within the new content —
        // which, when that lands in the whitespace, is now outside the delimiters.
        let pos = (start - content.start) + text.len();
        let caret = if core.is_empty() || pos <= lead {
            open_at + pos
        } else if pos >= lead + core.len() {
            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
        } else {
            open_at + lead + open.len() + (pos - lead)
        };
        Some(MarkEdgeFix {
            kind,
            probe: content.start,
            start: open_at,
            end: close_at + text.len() - (end - start),
            text: respelt,
            caret,
            // The marks in force here, resolved against any armed sticky delta —
            // what the writer is typing in, and so what has to still be true on
            // the far side of the delimiter the caret just stepped over.
            want: chain
                .iter()
                .filter(|(_, s, _)| start < s.end)
                .map(|(k, _, _)| *k)
                .collect::<InlineMarks>()
                .xor(self.pending_here()),
        })
    }

    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
    /// did break the mark. Whether whitespace at a delimiter is fatal is the
    /// format's business, not leaf's: `**bold **` is no longer strong, while
    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
    /// don't care either. Asking the parser afterwards settles it for every kind
    /// and format at once, and costs a re-spelling only where one is due.
    ///
    /// The repair rides along with the edit that caused it — one undo step puts
    /// back what the writer typed, not a delimiter shuffle they never saw.
    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
        if fix.end > self.source.len() {
            return;
        }
        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
            return; // still a mark: these delimiters don't mind the whitespace
        }
        let resumed = self.last_edit_kind;
        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
            return;
        }
        let _ = self.editor.coalesce_last_undo();
        // The keystroke owns the undo step, so the run of typing it belongs to
        // keeps coalescing over the repair rather than breaking in two here.
        self.last_edit_kind = resumed;
        self.caret = fix.caret.min(self.source.len());
        self.anchor = None;
        self.goal_col = None;
        self.rearm(fix.want);
        self.clamp_caret();
        self.record_caret();
    }

    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
    /// writer is typing in, carried across an edit that moved the caret out of
    /// the run holding them. Arms nothing when the caret already stands in
    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
    /// a clean delta here (see [`toggle`](Self::toggle)).
    fn rearm(&mut self, want: InlineMarks) {
        let here: InlineMarks = self
            .marks_at(self.caret)
            .into_iter()
            .map(|(k, _)| k)
            .collect();
        self.pending_marks = want.xor(here);
        self.pending_at = Some(self.caret);
    }

    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
    /// which backslash-escapes any character that would otherwise open markup in
    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
    /// a collapsed point — a selection is deleted by the caller first, since
    /// `insert_literal` inserts rather than replaces.
    fn insert_literal_at(
        &mut self,
        at: usize,
        text: &str,
        kind: EditKind,
        force_coalesce: bool,
    ) -> bool {
        // `force_coalesce` folds this into the immediately preceding edit (the
        // selection-delete of an overwrite) so the pair is one undo step; else it
        // coalesces only when it continues a run of the same-kind typing.
        let coalesce =
            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
        // The mark-edge rule holds for typed text however it is spelled — see
        // `splice`. Only an insert twig passed through unchanged can use it,
        // since a fix is measured in the bytes that actually land, and an escape
        // adds bytes this couldn't have counted.
        let fix = self.mark_edge_fix(at, at, text);
        self.record_caret();
        match self.editor.insert_literal(at, text) {
            Ok(change) => {
                if coalesce {
                    let _ = self.editor.coalesce_last_undo();
                }
                self.last_edit_kind = Some(kind);
                self.refresh();
                self.caret = change.new.end;
                self.anchor = None;
                self.goal_col = None;
                self.clear_pending();
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.record_caret();
                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
                    self.repair_mark_edges(fix);
                }
                true
            }
            Err(e) => {
                self.status = Some(format!("edit: {e}"));
                false
            }
        }
    }

    /// After a structural list edit (a new item, a nest/unnest), renumber the
    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
    /// renumber as its own edit; fold it into the edit that triggered it so the
    /// two undo as one, and only when it actually changed the source (a no-op or
    /// a caret outside any ordered list must not coalesce the real edit into the
    /// step before it).
    fn renumber_here(&mut self) {
        self.renumber_at(self.caret);
    }

    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
    /// caret — for an edit that leaves the caret one past the item it just wrote,
    /// where twig resolves no list to renumber.
    fn renumber_at(&mut self, off: usize) {
        let before = self.source.clone();
        if self.editor.renumber_ordered_lists(off).is_err() {
            return; // not inside an ordered list — nothing to renumber
        }
        self.refresh();
        if self.source != before {
            let _ = self.editor.coalesce_last_undo();
            self.dirty = self.source != self.clean_source;
            self.clamp_caret();
            self.record_caret();
        }
    }

    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
    /// sub-item written directly beneath a text line reparses that text as a
    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
    /// bullets can't underline anything, so swap the dash for a `*`: the item
    /// stays an empty nested bullet, the parent stays prose, and the source
    /// round-trips instead of hiding a heading the user never asked for. Folded
    /// into the triggering edit's undo step, the way renumbering is.
    ///
    /// Gated on the collapse having actually happened (the swapped dash was
    /// swallowed into a `heading`), so a real setext heading the author wrote —
    /// or a `- x` with content, which can't underline anything — is never
    /// touched. This has to live in the *edit*, not the renderer: leaving the
    /// hazardous bytes on disk and only painting over them would ship a file
    /// every other CommonMark tool reads as a heading.
    ///
    /// This one keeps its own byte scan, and has to: the hazard is precisely
    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
    /// which asks twig which lines open an item — reports nothing here. There is
    /// no node to ask about. It is also the last Markdown spelling leaf writes on
    /// purpose rather than for want of an answer; once twig spells continuations
    /// itself, avoiding the trap becomes twig's, and this goes.
    ///
    /// [`list_marker_on_line`]: Self::list_marker_on_line
    fn avoid_setext_collapse(&mut self) {
        let caret = self.caret.min(self.source.len());
        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
        let bytes = self.source.as_bytes();
        let mut dash = line_start;
        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
            dash += 1;
        }
        // A dash bullet is the only marker that doubles as a setext underline.
        if bytes.get(dash) != Some(&b'-') {
            return;
        }
        // Only an *empty* item is a bare underline; `- x` carries content and
        // can't fold the line above into a heading.
        let line_end = self.source[dash..]
            .find('\n')
            .map_or(self.source.len(), |i| dash + i);
        if !self.source[dash + 1..line_end].trim().is_empty() {
            return;
        }
        // The tell: that dash was swallowed into a `heading`. A properly nested
        // empty item sits under a `list_item`, with no heading in reach. Probe
        // the dash byte itself (well inside the heading), not the caret, whose
        // end-of-line offset can fall on the half-open span boundary.
        let collapsed = self
            .editor
            .ancestors_at(dash)
            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
            .unwrap_or(false);
        if !collapsed {
            return;
        }
        let caret = self.caret;
        if self.splice(dash, dash + 1, "*", EditKind::Other) {
            // Same width, so the caret keeps its column; fold into the edit that
            // triggered this so Tab stays one undo step.
            let _ = self.editor.coalesce_last_undo();
            self.caret = caret.min(self.source.len());
            self.clamp_caret();
            self.record_caret();
        }
    }

    fn snapshot(&self) -> CaretState {
        CaretState {
            caret: self.caret,
            anchor: self.anchor,
        }
    }

    /// Hand twig the current caret and selection as the blob for the live
    /// document state. Called before an edit — so the step twig retires records
    /// where the caret was, and undo can restore it — and again once the op has
    /// placed the caret, so redo restores where the edit left it.
    ///
    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
    /// caret through its own history, so coalescing falls out for free (folding
    /// two twig steps into one drops the intermediate blob, keeping the run's
    /// first) and the parallel stacks that had to march in lockstep — and could
    /// silently drift out of it — are gone.
    fn record_caret(&mut self) {
        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
    }

    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
    /// the toggled region selected so a second press cleanly reverses it.
    pub fn toggle(&mut self, kind: InlineKind) {
        // Ahead of the no-selection branch below: arming a mark for text not yet
        // typed is a promise `insert` cannot keep in a format with no delimiters
        // to spell it with. Per *kind*, not per format — Markdown spells three
        // of the eight marks, djot all eight, HTML seven.
        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
            return;
        }
        let Some((s, e)) = self.selection() else {
            // No selection: arm the mark for the next text typed here, the way a
            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
            // in the flow of typing without ever selecting anything — the delta
            // is realised onto the freshly typed text by `insert`. A fresh caret
            // position starts the delta over from the marks actually in force.
            if self.pending_at != Some(self.caret) {
                self.pending_marks = InlineMarks::empty();
                self.pending_at = Some(self.caret);
            }
            self.pending_marks.flip(kind);
            self.status = None;
            return;
        };
        // Whitespace at the edge of a selection is not part of what was chosen —
        // a double-click takes the space after the word with it — and a mark
        // cannot close against one anyway: `**word **` is four literal asterisks
        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
        let picked = &self.source[s..e];
        let (s, e) = (
            s + (picked.len() - picked.trim_start().len()),
            e - (picked.len() - picked.trim_end().len()),
        );
        if s >= e {
            self.status = Some(format!("{kind:?}: nothing selected to mark"));
            return;
        }
        // Styling a selection is a one-shot act, not a sticky mode.
        self.clear_pending();
        self.record_caret();
        match self.editor.toggle_inline(s, e, kind) {
            Ok(change) => {
                self.last_edit_kind = None; // structural edit is its own undo step
                self.refresh();
                self.anchor = Some(change.new.start);
                self.caret = change.new.end;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
        }
    }

    /// Convert the block at the caret to a heading level or paragraph.
    pub fn set_block(&mut self, kind: BlockKind) {
        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
            return;
        }
        self.record_caret();
        // A blank line has no node to convert, and twig opens a block there
        // rather than declining — so the caret's own offset is the right thing
        // to hand it when `block_offset_for_caret` finds nothing.
        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
        match self.editor.set_block(offset, kind) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                // Opening a block on a blank line writes a marker the caret
                // belongs *after*; converting an existing one moves nothing.
                self.caret = self.caret.max(change.new.end);
                self.clamp_caret();
                self.anchor = None;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
        }
    }

    /// Whether `off` is inside a text block (paragraph, heading, code block…).
    fn has_block_at(&mut self, off: usize) -> bool {
        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
            chain
                .iter()
                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
        })
    }

    /// The offset to hand twig's `set_block`: the caret when it is already inside
    /// a block, otherwise nudged onto the previous character (a caret at a line
    /// end sits at the doc level, outside the block). `None` when the caret is on
    /// a blank line — a new paragraph with no block node to convert.
    fn block_offset_for_caret(&mut self) -> Option<usize> {
        let caret = self.caret.min(self.source.len());
        if self.has_block_at(caret) {
            return Some(caret);
        }
        // Nudge to the previous character — but never across a newline: that would
        // target the previous block, and a blank line genuinely has no block.
        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
            && ch != '\n'
            && self.has_block_at(i)
        {
            return Some(i);
        }
        None
    }

    /// The heading level of the text block at the caret, or `None` when that
    /// block is not a heading.
    pub fn current_heading_level(&mut self) -> Option<u32> {
        let caret = self.caret;
        self.nodes()
            .into_iter()
            .filter(|n| n.kind == Kind::Heading)
            .find(|n| n.span.start <= caret && caret <= n.span.end)
            .and_then(|n| n.level)
    }

    /// The inline marks in force at the caret (or over the selection) — what a
    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
    /// inline counterpart. Cheap enough to call every frame: one twig
    /// `ancestors_at` query per caret (two with a selection), each walking root
    /// → deepest node at one offset. It never snapshots the tree the way
    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
    /// the only allocation is twig's own small ancestor `Vec`.
    ///
    /// **A selection reports a mark only when the mark covers *all* of it.**
    /// That's what every real toolbar means by an active button — Bold lit over
    /// a half-bold selection would claim a press turns bold *off*, when
    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
    /// Whole-coverage is asked as "is the same mark node standing over both the
    /// first and the last character?": inline nodes are contiguous, so one node
    /// covering both ends covers every byte between them. Two touching runs
    /// (`**a****b**`) are two nodes, and correctly light nothing.
    ///
    /// At a bare caret a mark is active when the caret stands inside the mark's
    /// span — `span.start <= caret < span.end`, delimiters included, which is
    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
    /// opening `*` (2) through the last byte of the closing `**` (9) are all
    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
    /// typing would actually land inside the marked run. The offset one past the
    /// mark (10) is the text after it and reports nothing, at the end of the
    /// buffer exactly as in the middle.
    pub fn active_inline_marks(&mut self) -> InlineMarks {
        let Some((start, end)) = self.selection() else {
            // The marks actually in force at the caret, flipped by any armed
            // sticky delta — so `⌘b` at a bare caret lights the Bold button
            // immediately, before a single character is typed.
            let base: InlineMarks = self
                .marks_at(self.caret)
                .into_iter()
                .map(|(k, _)| k)
                .collect();
            return base.xor(self.pending_here());
        };
        // The selection's *last character*, not its exclusive end: `end` is the
        // offset one past the selection, which for a selection ending exactly at
        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
        // entirely bold, but offset 10 is the space after).
        let last = prev_boundary(&self.source, end);
        let head = self.marks_at(start);
        let tail = self.marks_at(last);
        head.into_iter()
            .filter(|m| tail.contains(m))
            .map(|(k, _)| k)
            .collect()
    }

    /// The inline marks whose span covers `off`, each with the id of the node
    /// carrying it — the id is what lets a selection tell one mark node from
    /// another of the same kind.
    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
        let off = off.min(self.source.len());
        self.editor
            .ancestors_at(off)
            .unwrap_or_default()
            .into_iter()
            // `span.end` is the offset one *past* the mark, so it isn't in it.
            // twig already resolves a boundary to whatever starts there — in
            // `**bold** x` offset 8 is the following text, not the strong — but
            // when nothing follows, the tie has nobody to break for and the
            // chain still ends at the mark. That would make the answer at the
            // last offset of the document depend on whether the file happens to
            // end in a newline; the rule is `span.start <= off < span.end`, and
            // it's the same rule at the end of a buffer as in the middle.
            .filter(|m| off < m.span.end)
            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
            .collect()
    }

    /// Toggle a heading at the caret: if the block is already this heading level,
    /// revert it to a paragraph; otherwise convert it to this heading level.
    /// This gives the heading commands the same toggle feel as bold/italic/code —
    /// re-applying a heading a line already has turns it back into body text.
    pub fn toggle_heading(&mut self, level: u32) {
        if self.current_heading_level() == Some(level) {
            self.set_block(BlockKind::Paragraph);
        } else {
            self.set_block(BlockKind::Heading(level));
        }
    }

    /// Toggle a block quote around the selection, or around the block at the
    /// caret — the toolbar's Quote button.
    pub fn toggle_blockquote(&mut self) {
        self.toggle_container(BlockContainerKind::BlockQuote);
    }

    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
    /// over the block at the caret — one op with the kind as a flag, the way
    /// `toggle_heading` takes its level, so a frontend needs no twig type to
    /// name the two buttons.
    ///
    /// Pressing the *other* list's button while in a list converts in place
    /// rather than nesting, so the pair reads as one three-state control
    /// (bulleted / numbered / neither) rather than two independent wrappers.
    pub fn toggle_list(&mut self, ordered: bool) {
        self.toggle_container(if ordered {
            BlockContainerKind::OrderedList
        } else {
            BlockContainerKind::BulletList
        });
    }

    // ── Task list items ──────────────────────────────────────────────────────
    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
    // inline content of the item's first paragraph rather than part of its
    // marker, so adding or removing one must leave the item's continuation
    // indentation alone, and an item inside a quote is found past the quote
    // markers. leaf names the gesture and the offset; the spelling is twig's.

    /// Whether the list item at the caret carries a checkbox, and which way it
    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
    /// item or no item at all. What a toolbar reads to light its checkbox button.
    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
        self.task_checked_at(self.caret)
    }

    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
    /// offset — what a frontend asks before deciding a click landed on a box.
    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
        self.innermost_list_item(offset.min(self.source.len()))?
            .checked
    }

    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
    /// A no-op with a reported reason when the caret is in no task item — minting
    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
    pub fn toggle_task_checked(&mut self) {
        self.toggle_task_at(self.caret);
    }

    /// Tick or untick the task item covering `offset` — what a *click* on a
    /// rendered checkbox is. Separate from the caret form because a click carries
    /// its own offset and must not first move the caret there: ticking a box
    /// three paragraphs away should not take the cursor with it.
    pub fn toggle_task_at(&mut self, offset: usize) {
        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
            return;
        }
        let offset = offset.min(self.source.len());
        self.record_caret();
        match self.editor.toggle_task_checked(offset) {
            Ok(_) => self.after_task_edit(),
            Err(e) => self.status = Some(format!("task: {e}")),
        }
    }

    /// Give the list item at the caret a checkbox, or take its checkbox away —
    /// the gesture that converts between a plain bullet and a task. A new box
    /// arrives unticked.
    pub fn toggle_task_item(&mut self) {
        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
            return;
        }
        let caret = self.caret.min(self.source.len());
        self.record_caret();
        match self.editor.toggle_task_item(caret) {
            Ok(_) => self.after_task_edit(),
            Err(e) => self.status = Some(format!("task: {e}")),
        }
    }

    /// Settle after a task gesture. The caret rides its old byte offset and is
    /// clamped back in: a box is three or four bytes on the item's first line, so
    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
    /// real stop either way.
    fn after_task_edit(&mut self) {
        self.last_edit_kind = None;
        self.refresh();
        self.anchor = None;
        self.dirty = self.source != self.clean_source;
        self.status = None;
        self.clamp_caret();
        self.record_caret();
    }

    // ── Tables ───────────────────────────────────────────────────────────────
    // A table is a grid, and twig edits it as one — add/remove/move a row or
    // column, set a column's alignment — re-spelling the whole table in a single
    // splice. Every gesture is anchored at the caret's cell. leaf just names the
    // gesture and re-reads the result; the whole table's numbering, borders, and
    // delimiter are twig's to keep straight.

    /// Whether the caret is inside a table — what a frontend asks to enable or
    /// disable its table controls.
    ///
    /// An HTML `<table>` still answers `true`: the caret really is in a table,
    /// and the reason the grid controls stay dark there is
    /// [`Capabilities::table`], which is a fact about the document's format
    /// rather than about the caret. A frontend needs both.
    pub fn caret_in_table(&mut self) -> bool {
        let caret = self.caret.min(self.source.len());
        self.editor
            .ancestors_at(caret)
            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
            .unwrap_or(false)
    }

    /// One grid op, guarded and settled — the shared body of the seven below.
    ///
    /// The guard is why this exists rather than seven copies of the same three
    /// lines, and it is the one guard leaf cannot delegate to twig. The table
    /// editor is the gesture family that consults no `Syntax` table (it spells a
    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
    /// grid as a *pipe table* and reports success, swapping the element out for
    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
    /// downstream could tell that from a successful edit — the splice is real,
    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
    /// stopping at the door rather than detecting after the fact. See
    /// [`spells_pipe_tables`].
    fn table_op(
        &mut self,
        what: &str,
        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
    ) {
        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
            return;
        }
        self.record_caret();
        let at = self.caret;
        let r = op(&mut self.editor, at);
        self.apply_table(r, what);
    }

    /// Insert an empty row below (`below`) or above the caret's row.
    pub fn table_insert_row(&mut self, below: bool) {
        self.table_op("table row", |e, at| e.table_insert_row(at, below));
    }

    /// Delete the caret's row (not the header, not the last body row).
    pub fn table_delete_row(&mut self) {
        self.table_op("table row", |e, at| e.table_delete_row(at));
    }

    /// Insert an empty column right (`right`) or left of the caret's column.
    pub fn table_insert_column(&mut self, right: bool) {
        self.table_op("table column", |e, at| e.table_insert_column(at, right));
    }

    /// Delete the caret's column (unless it is the only one).
    pub fn table_delete_column(&mut self) {
        self.table_op("table column", |e, at| e.table_delete_column(at));
    }

    /// Set the caret's column to `alignment`.
    pub fn table_set_alignment(&mut self, alignment: Alignment) {
        self.table_op("table alignment", |e, at| {
            e.table_set_alignment(at, alignment)
        });
    }

    /// Move the caret's row one place down (`down`) or up, within the body rows.
    pub fn table_move_row(&mut self, down: bool) {
        self.table_op("table row", |e, at| e.table_move_row(at, down));
    }

    /// Move the caret's column one place right (`right`) or left.
    pub fn table_move_column(&mut self, right: bool) {
        self.table_op("table column", |e, at| e.table_move_column(at, right));
    }

    /// Settle the caret and document flags after a table op (or report its
    /// error). twig re-spells the whole table, so the caret rides its old byte
    /// offset and is clamped back into the rebuilt bytes — near enough to where
    /// it was, since the op preserves the cells' content and order around it.
    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
        match result {
            Ok(()) => {
                self.last_edit_kind = None;
                self.refresh();
                self.anchor = None;
                self.clamp_caret();
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("{what}: {e}")),
        }
    }

    /// One `toggle_block_container` over the block-level target.
    ///
    /// leaf says *where*; twig decides everything else — which blocks the range
    /// covers, whether that means wrapping, unwrapping, nesting or converting,
    /// and how this document's format spells the prefix. The rule that a
    /// container only comes off when the range covers every block it holds is
    /// what the re-anchoring below is built around.
    fn toggle_container(&mut self, kind: BlockContainerKind) {
        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
            return;
        }
        let selected = self.selection();
        // A blank line holds no block, and twig opens an *empty* container on one
        // — since 3.2.0; it used to decline the range with `NotFound`, which is
        // why this used to lend it a scratch paragraph to wrap. Worth knowing
        // here because the line-for-line caret mapping below cannot describe it:
        // opening one under a paragraph writes the blank line the format needs
        // above the marker too, so the rewritten region has a line the old one
        // didn't, and "the same line, the same distance from its end" lands on
        // that new blank instead of in the container.
        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
        // Without a selection the target is the caret's own block, resolved the
        // way `set_block` resolves it — a caret at a line end sits at the doc
        // level and has to be nudged back onto the block it looks like it's in.
        // An empty range is enough: twig widens to the whole lines it touches.
        let (start, end) = match selected {
            Some(range) => range,
            None => {
                let off = self.block_offset_for_caret().unwrap_or(self.caret);
                (off, off)
            }
        };
        self.record_caret();
        match self.editor.toggle_block_container(start, end, kind) {
            Ok(change) => {
                // Read the caret's place out of the *pre-edit* source, before
                // `refresh` swaps that source out from under it.
                let place = (selected.is_none() && !opened_empty)
                    .then(|| self.caret_line_tail(&change.old));
                self.last_edit_kind = None; // structural edit is its own undo step
                self.refresh();
                match place {
                    // Both land the caret at the far end of what twig wrote, and
                    // differ only in what they leave selected.
                    //
                    // From a selection: select what the container now holds, the
                    // way `toggle` keeps its marked region selected — and for a
                    // stronger reason than symmetry: a container comes *off* only
                    // a range covering every block it holds, so a selection left
                    // on its old bytes (now short by a prefix per line) would nest
                    // on the second press instead of reversing the first.
                    //
                    // From a blank line: nothing to select, and the end of the
                    // region is exactly past the bare `> ` / `- ` twig wrote —
                    // the caret standing inside the container that was asked for.
                    None => {
                        self.anchor = (!opened_empty).then_some(change.new.start);
                        self.caret = change.new.end;
                    }
                    Some(place) => {
                        self.anchor = None;
                        self.caret = self.line_tail_offset(&change.new, place);
                    }
                }
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
        }
    }

    /// The caret's place inside the region a container toggle is rewriting, in
    /// the only terms the rewrite preserves: which of the region's lines it sits
    /// on, and how many bytes of that line lie ahead of it.
    ///
    /// A container's markup goes in at column 0 and never touches what follows
    /// on the line, so that pair survives the edit exactly where a byte offset
    /// does not — a caret left on its old offset slides back by one prefix per
    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
    /// `> ` it just asked for.
    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
        let caret = self.caret.clamp(old.start, old.end);
        let line = self.source[old.start..caret].matches('\n').count();
        let end = self.source[caret..old.end]
            .find('\n')
            .map_or(old.end, |i| caret + i);
        (line, end - caret)
    }

    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
    /// region: the offset `tail` bytes back from the end of the region's `line`.
    ///
    /// Both walks are clamped rather than trusted, because the one op that does
    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
    /// the items back apart with blank lines between them — and a caret landing
    /// on the nearest line of the right item beats one landing out of the region
    /// entirely.
    fn line_tail_offset(
        &self,
        new: &std::ops::Range<usize>,
        (line, tail): (usize, usize),
    ) -> usize {
        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
        let mut start = 0;
        for _ in 0..line {
            match region[start..].find('\n') {
                Some(i) => start += i + 1,
                None => break,
            }
        }
        let end = region[start..]
            .find('\n')
            .map_or(region.len(), |i| start + i);
        new.start + end.saturating_sub(tail).max(start)
    }

    /// Link the selection to `destination` — the toolbar's Link button. With no
    /// selection it acts at the caret, which re-points a link the caret is
    /// already standing in (twig replaces an existing link's destination and
    /// keeps its text) and otherwise spells a link that has no text of its own:
    /// an autolink (`<https://x.dev>`) where the destination is one, and
    /// `[destination](destination)` where it isn't.
    ///
    /// `destination` reaches twig raw. Escaping it is format knowledge and the
    /// two formats genuinely disagree — Markdown ends a destination at the first
    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
    /// itself — so the side holding the document is the side that gets to spell
    /// it. A destination twig can't carry at all (one with a newline) comes back
    /// as an error rather than a quietly rewritten URL.
    pub fn insert_link(&mut self, destination: &str) {
        if self.refuse_unsupported("link", Gesture::InsertLink) {
            return;
        }
        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
        self.record_caret();
        match self.editor.insert_link(start, end, destination) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                match self.link_text_span(change.new.start) {
                    // A link with text of its own: select it, so typing replaces
                    // a `[dest](dest)`'s stand-in label and a second press
                    // re-points what the first one linked.
                    Some(text) => {
                        self.anchor = (text.start != text.end).then_some(text.start);
                        self.caret = text.end;
                    }
                    // An autolink is finished the moment it's written — its text
                    // *is* the URL. Leaving it selected would aim the next press
                    // at the one shape twig still wraps instead of re-points.
                    None => {
                        self.anchor = None;
                        self.caret = change.new.end;
                    }
                }
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("link: {e}")),
        }
    }

    /// Insert a block-level image at the caret: `![alt](destination)`. Any
    /// selection becomes the alt text (so "select a caption, insert image" labels
    /// it); with no selection, `alt` is used — empty for none. The caret lands
    /// just past the inserted image.
    ///
    /// Both halves go through twig (`insert_literal` for the alt text,
    /// `insert_image` for the image), so neither is spelled here. That used to be a
    /// `format!`, and it was wrong the first time an app inserted a real filename:
    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
    /// not an image at all — and the fix is per-format, since moving into the
    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
    pub fn insert_image(&mut self, destination: &str, alt: &str) {
        if self.refuse_unsupported("image", Gesture::InsertImage) {
            return;
        }
        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
        self.record_caret();
        // With no selection and an explicit `alt`, the alt text has to exist in the
        // document before it can be the image's — and it is raw caller input, so
        // it goes in through `insert_literal`, which escapes it for the format
        // rather than letting a `]` in someone's caption close the image early.
        let (start, end) = if start == end && !alt.is_empty() {
            match self.editor.insert_literal(start, alt) {
                Ok(change) => (change.new.start, change.new.end),
                Err(e) => {
                    self.status = Some(format!("image: {e}"));
                    return;
                }
            }
        } else {
            (start, end)
        };
        match self.editor.insert_image(start, end, destination) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                // Just past the image, nothing selected — where a caret belongs
                // after inserting one.
                self.anchor = None;
                self.caret = change.new.end;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("image: {e}")),
        }
    }

    /// Insert a block-level image, video, or audio at the caret. The image case
    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
    /// HTML elements, which is the only spelling Markdown and Djot have for them:
    ///
    /// ```text
    /// <video src="clip.mp4" controls>alt</video>
    /// <audio src="take.mp3" controls>alt</audio>
    /// ```
    ///
    /// HTML rather than a `::video{…}` directive deliberately. A directive means
    /// something only to an app that knows the vocabulary, so the document would
    /// read as literal punctuation everywhere else; `<video>` is what every other
    /// renderer already understands, and what leaf's own reader picks back up
    /// through `html_elements` promotion (see [`parse_extensions`]).
    ///
    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
    /// `html_elements`. Before that only the multi-line form parsed as a block at
    /// all, and this wrote three lines to work around it.
    ///
    /// `controls` is always written: a player with no transport is a still frame
    /// the reader can't do anything with. Any selection becomes the element's
    /// fallback text, exactly as it becomes an image's alt.
    ///
    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
    /// applies, and bites harder here: a `"` in `destination` closes the
    /// attribute. A frontend taking these from a file picker is fine; one taking
    /// them from free text should keep them tame.
    ///
    /// [`MediaInfo`]: crate::MediaInfo
    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
        if kind == MediaKind::Image {
            return self.insert_image(destination, alt);
        }
        // Gated on the *image* gesture, not on one of its own — there isn't one,
        // since the bytes below are spelled here rather than by twig, and an HTML
        // document would in fact parse them. The button is one control with three
        // kinds behind it, and two of them working in a format where the third
        // cannot is a worse surface than three that agree — especially as
        // `insert_image` is the kind anyone reaches for first.
        if self.refuse_unsupported("media", Gesture::InsertImage) {
            return;
        }
        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
        let alt_text = self
            .selected_text()
            .map(str::to_string)
            .unwrap_or_else(|| alt.to_string());
        let tag = match kind {
            MediaKind::Audio => "audio",
            _ => "video",
        };
        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
        self.edit(start, end, &markup);
    }

    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
    /// button. Spelling and placement are both twig's; leaf used to write `---`
    /// itself, which was the Markdown spelling in a djot document too.
    ///
    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
    /// mid-paragraph and lands it after the caret's whole block. To get a rule
    /// *at* the caret — the paragraph parted in two around it, which is what a
    /// rule button is understood to do — the paragraph is first divided with
    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
    /// the offset `split_block` returns puts the rule after the *second* half
    /// instead, which is a rule in the right document and the wrong place.
    ///
    /// Only a plain paragraph is split. Everywhere else the rule simply lands
    /// after the block, which is both twig's own answer and the better one:
    /// splitting a fenced code block would leave two fences with a rule between
    /// them, and splitting a list item would mint an item nobody asked for on the
    /// way to a rule that lands after the list regardless. A table and a setext
    /// heading refuse the split outright, so they take the same path by
    /// themselves.
    pub fn insert_thematic_break(&mut self) {
        if self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak) {
            return;
        }
        self.caret = self.skip_trailing_close_delims(self.caret);
        // A selection is replaced by the rule, so collapse it first and let the
        // split-and-rule below run from the caret it leaves behind.
        if let Some((s, e)) = self.selection() {
            self.splice(s, e, "", EditKind::Other);
        }
        self.anchor = None;
        self.record_caret();
        let at = self.caret;
        if self.caret_in_bare_paragraph() {
            // A failure here is not fatal: the rule still lands after the block,
            // which is exactly what this call was trying to improve on.
            let _ = self.editor.split_block(at);
        }
        match self.editor.insert_thematic_break(at) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                self.anchor = None;
                self.caret = change.new.end;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("thematic break: {e}")),
        }
    }

    /// Whether the caret sits in a paragraph and nothing else — no list item, no
    /// quote, no fence, no table. The one shape where parting the block around
    /// the caret is unambiguously what a rule button means; see
    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
    /// container is left to take the rule after itself.
    fn caret_in_bare_paragraph(&mut self) -> bool {
        let caret = self.caret.min(self.source.len());
        let Ok(chain) = self.editor.ancestors_at(caret) else {
            return false;
        };
        let mut in_para = false;
        for m in chain {
            match m.kind {
                Kind::Para => in_para = true,
                Kind::ListItem
                | Kind::TaskListItem
                | Kind::BlockQuote
                | Kind::CodeBlock
                | Kind::Table => return false,
                _ => {}
            }
        }
        in_para
    }

    /// The destination of the link under the caret — what a Link prompt shows so
    /// ⌘K on an existing link edits its URL instead of asking for it again.
    /// `None` when the caret stands in no link.
    ///
    /// An autolink carries no separate destination: its text *is* the URL, so
    /// that's what comes back for one.
    pub fn link_destination_at_caret(&mut self) -> Option<String> {
        self.link_destination_at(self.caret)
    }

    /// The destination of the link at `off`.
    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
    /// the caret isn't.
    ///
    /// The offset form exists for the same reason
    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
    /// the document somewhere else — a footnote's text in a popover, say — has
    /// rows and runs but no caret in them, and still needs to know which of those
    /// runs a reader can follow.
    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
        self.nodes()
            .into_iter()
            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
            .filter(|n| n.span.start <= off && off < n.span.end)
            .max_by_key(|n| n.span.start)
            .and_then(|n| n.destination.or(n.text))
    }

    /// Where the locator `id` lands in this document — the `#v2` half of a
    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
    /// answers to it.
    ///
    /// The other end of a link, and the reason this exists: without it a
    /// destination has only file granularity, so following a citation into a
    /// chapter drops the reader at the top of it to hunt for the verse. Which is
    /// also why it is a *document* query rather than a caret one — the document
    /// being asked is usually not the one the reader is in.
    ///
    /// Three readings, tried in order, because the same `#some-heading` is
    /// written three ways across the formats leaf opens:
    ///
    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
    ///    the auto-ids djot mints for its headings. The only exact answer, so it
    ///    goes first — a document that says `{#v1}` has settled the question.
    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
    ///    authored anywhere land on a djot heading.
    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
    ///    none and `{#custom}` is literal text in a Markdown heading — so for
    ///    the format most vaults are written in, the heading's own words are the
    ///    only thing a fragment can name. This is the rule every Markdown
    ///    renderer already follows, which is what makes `#a-heading` mean in
    ///    diaryx what it means on the web.
    ///
    /// Ties go to the earliest match, then to the widest: a duplicated id is the
    /// document's mistake and the first one is the answer every anchor
    /// implementation gives, while preferring the wider span picks the section
    /// over the heading that opens it — more for a peek to show, same place to
    /// land.
    pub fn locate(&mut self, id: &str) -> Option<Landing> {
        let id = id.trim();
        if id.is_empty() {
            return None;
        }
        let nodes = self.nodes();

        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
        // is picking, among nodes that start together, the one that ends last.
        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
            matches
                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
                .map(|n| Landing {
                    start: n.span.start,
                    end: n.span.end,
                })
        };

        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
            return Some(landing);
        }
        let want = slug(id);
        if want.is_empty() {
            return None;
        }
        if let Some(landing) = pick(
            &mut nodes
                .iter()
                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
        ) {
            return Some(landing);
        }

        // A heading by its words. Its span is one line, so the end comes from
        // where the *section* it opens gives out — the next heading that is not
        // under it, or the end of the document. A Markdown heading has no
        // section node to ask (twig only builds those for djot), and a peek that
        // showed the heading alone would answer "what does that say" with the
        // title of the thing it says.
        let heading = nodes
            .iter()
            .filter(|n| n.kind == Kind::Heading)
            .filter(|n| {
                n.content_span
                    .clone()
                    .and_then(|s| self.source.get(s))
                    .is_some_and(|text| slug(text) == want)
            })
            .min_by_key(|n| n.span.start)?;
        let level = heading.level.unwrap_or(u32::MAX);
        let end = nodes
            .iter()
            .filter(|n| n.kind == Kind::Heading)
            .filter(|n| n.span.start > heading.span.start)
            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
            .map(|n| n.span.start)
            .min()
            .unwrap_or(self.source.len());
        Some(Landing {
            start: heading.span.start,
            end,
        })
    }

    /// Write a footnote at the caret — the toolbar's Footnote button, and the
    /// one gesture in the footnote story that *authors* rather than follows.
    ///
    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
    /// the `[^1]:` definition at the end of the document. Half a footnote is not
    /// a footnote — a bare reference with nothing defining it renders as literal
    /// brackets — so a single button that wrote only the reference would leave
    /// the author to hand-spell the other half in a document that had just
    /// stopped showing them what the first half meant. One edit also means one
    /// undo takes both back.
    ///
    /// The definition's body is left empty and **the caret lands in it**, which
    /// is the whole point of pressing the button: nobody wants a reference to a
    /// note they have not written yet. Getting back to where they were writing
    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
    /// the same return leg a reader following a reference already uses, so the
    /// author is left standing on the near end of a round trip that works.
    ///
    /// A selection collapses to its *end* rather than being replaced: a
    /// reference annotates the words before it, so "select the claim, add a
    /// footnote" should mark that claim, not consume it.
    pub fn insert_footnote(&mut self) {
        if self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
            return;
        }
        let at = self.selection().map_or(self.caret, |(_, end)| end);
        self.anchor = None;
        self.caret = at;
        self.record_caret();
        let label = self.next_footnote_label();
        match self.editor.insert_footnote(at, &label) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                self.anchor = None;
                // `change.new` runs from the reference to the end of the
                // document, so its start is the `[^1]` just written and
                // `footnote_at` resolves it to the note the same way a reader's
                // tap does — and to the note's *body*, which is already a caret
                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
                // and has none), so this needs no snap on top. The fallback is
                // the reference's own offset: a format that spelled the pair some
                // way leaf can't read back should still leave the caret on the
                // edit rather than at the far end of a document it just grew.
                self.caret = self
                    .footnote_at(change.new.start)
                    .and_then(|note| note.offset)
                    .unwrap_or(change.new.start);
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("footnote: {e}")),
        }
    }

    /// The label to give a footnote the author has not named: the lowest counting
    /// number no footnote in the document is already wearing.
    ///
    /// twig takes the label rather than minting one, because it holds no opinion
    /// about what a document's footnotes should be called — and it is right not
    /// to. Numbering them is what every author of a numbered note expects, and
    /// re-using a taken number would silently point the new reference at somebody
    /// else's note (twig reuses an existing definition rather than appending a
    /// second one, which is the right rule for citing a note twice on purpose and
    /// exactly the wrong accident to have by default).
    ///
    /// *References* are counted alongside definitions, not just definitions: a
    /// document carrying a dangling `[^2]` has a 2 that means something to
    /// whoever wrote it, and minting a definition for it here would answer a
    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
    /// count entirely — they take no number, so they block none.
    fn next_footnote_label(&mut self) -> String {
        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
            .into_iter()
            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
            .filter_map(|label| label.parse().ok())
            .collect();
        taken.extend(
            self.nodes()
                .into_iter()
                .filter(|n| n.kind == Kind::FootnoteReference)
                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
                .filter_map(|label| label.parse::<u32>().ok()),
        );
        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
    }

    /// The footnote reference under the caret, resolved to the note it names.
    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
        self.footnote_at(self.caret)
    }

    /// The footnote reference at `off`, resolved to the note it names — what a
    /// frontend shows when a reader activates a `[^1]`.
    ///
    /// A reference is not a link node, so
    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
    /// (and should not) answer for one: a link names a destination to leave for,
    /// a reference names a note that is already in this document. Following one
    /// is a move within the page, which is why this hands back an `offset`
    /// rather than something to open.
    ///
    /// Offset-based rather than caret-only because the gesture that wants this
    /// most is the one that must not move the caret: a pointer hovering a `[1]`
    /// asks what note it names without disturbing where the reader was typing.
    /// The caret is just the offset a click already placed —
    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
    ///
    /// `None` when `off` stands in no reference. A reference whose note the
    /// document never defines is *not* `None` — it answers with the label it
    /// looked for and no text, which is what lets a frontend say so instead of
    /// silently doing nothing.
    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
        // Innermost-wins by latest start, the rule its link sibling uses.
        let span = self
            .nodes()
            .into_iter()
            .filter(|n| n.kind == Kind::FootnoteReference)
            .filter(|n| n.span.start <= off && off < n.span.end)
            .max_by_key(|n| n.span.start)?
            .span;
        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();

        // The note itself. Definitions are roots beside `doc` rather than
        // children of it, so they're asked for directly — see
        // `wysiwyg::footnote_definitions`.
        let note = wysiwyg::footnote_definitions(&mut self.editor)
            .into_iter()
            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
        let Some(note) = note else {
            return Some(FootnoteRef {
                label,
                text: None,
                offset: None,
                end: None,
            });
        };
        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
        Some(FootnoteRef {
            label,
            text: body
                .clone()
                .and_then(|b| self.source.get(b))
                .map(str::to_string),
            // The body's start, not the definition's — see `FootnoteRef::offset`.
            offset: body.clone().map(|b| b.start),
            end: body.map(|b| b.end),
        })
    }

    /// The footnote *definition* the caret stands in, and where the reference
    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
    /// at the caret's offset.
    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
        self.footnote_definition_at(self.caret)
    }

    /// The footnote definition spanning `off`, and where the reference that
    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
    ///
    /// The mirror image, deliberately: the same gesture that takes a reader from
    /// `[1]` down to the note takes them from the note back up to `[1]`, so
    /// following a footnote is a round trip rather than a fall. It needs no
    /// memory of how the reader arrived — the document says where the reference
    /// is — which is what makes it work for a reader who scrolled to the notes
    /// themselves, and what keeps it right after an edit moves either end.
    ///
    /// `None` when `off` stands in no definition. A definition nothing cites is
    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
    /// its label and no offset, so a frontend can say "nothing refers to this"
    /// rather than offer a jump that goes nowhere.
    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
        // Definitions are roots beside `doc`, so `nodes()` — which walks the
        // document body — never reports one. They're asked for directly, the way
        // `footnote_at` asks for the note it resolves to.
        //
        // Closed at the end, unlike the half-open test its neighbours use. A
        // definition's span stops at its last content byte — the newline ending
        // the line is outside it — so `span.end` is the caret stop at the end of
        // the note's own row, not the first byte of anything after. Excluding it
        // meant the one caret an author is guaranteed to have, the one left
        // sitting at the end of the note they just typed, was in no definition at
        // all: writing a note and then asking to go back to its reference
        // answered nothing. Two definitions in a row still can't both match —
        // there is a blank line between them — and `max_by_key` decides anyway.
        let note = wysiwyg::footnote_definitions(&mut self.editor)
            .into_iter()
            .filter(|m| m.span.start <= off && off <= m.span.end)
            .max_by_key(|m| m.span.start)?;
        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();

        // The earliest reference carrying this label. `min` rather than a `find`,
        // because `nodes()` reports a flattened walk whose order is twig's
        // business, not document order. Bound first: the walk needs `&mut self`
        // and reading the labels back out needs `&self.source`.
        let nodes = self.nodes();
        let offset = nodes
            .into_iter()
            .filter(|n| n.kind == Kind::FootnoteReference)
            .filter(|n| {
                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
            })
            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
            .map(|n| n.span.start + 2)
            .min();
        Some(FootnoteDef { label, offset })
    }

    /// The destination of the image under the caret — what an image prompt shows
    /// so editing an existing image starts from its current URL instead of blank,
    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
    /// `None` when the caret stands in no image. A caret resting just after a
    /// block image (its trailing stop) is still "in" it — the half-open span test
    /// excludes that offset, which is the intended precision: past the image is
    /// past it.
    pub fn image_destination_at_caret(&mut self) -> Option<String> {
        let off = self.caret;
        self.nodes()
            .into_iter()
            .filter(|n| n.kind == Kind::Image)
            .filter(|n| n.span.start <= off && off < n.span.end)
            .max_by_key(|n| n.span.start)
            .and_then(|n| n.destination)
    }

    /// The language of the fenced code block the caret stands in — what a
    /// language prompt shows so editing it starts from the current value rather
    /// than blank. `None` when the caret is in no code block, or in one whose
    /// fence carries no language (or an indented block, which has no fence).
    pub fn code_language_at_caret(&mut self) -> Option<String> {
        let start = self.code_block_start_at_caret()?;
        wysiwyg::code_language(&self.source, start)
    }

    /// Whether the caret stands in a fenced code block — the one a language
    /// prompt could edit. A frontend gates its "set language" affordance on this
    /// (an indented block, which can't carry a language, reports `false`).
    pub fn caret_in_fenced_code(&mut self) -> bool {
        self.code_block_start_at_caret()
            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
    }

    /// Set (or clear, with `""`) the language of the fenced code block the caret
    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
    /// block, and a reported error for a language the format's fence cannot
    /// carry.
    ///
    /// twig rewrites the info string, so the fence's own width — measured
    /// against a body neither side touches — is kept, and a language holding a
    /// space, a line end or the fence character is refused rather than written
    /// out to reparse as something else. Leaf used to splice over the info span
    /// itself and `trim()` the input, which handled the one bad case it had
    /// thought of.
    pub fn set_code_language(&mut self, lang: &str) {
        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
            return;
        }
        if self.code_block_start_at_caret().is_none() {
            return;
        }
        let lang = lang.trim();
        // `None` clears the info string; `Some("")` asks for an empty one. Both
        // write a bare fence, and the prompt's empty value means "clear".
        let want = (!lang.is_empty()).then_some(lang);
        self.record_caret();
        match self.editor.set_code_language(self.caret, want) {
            Ok(_) => {
                self.last_edit_kind = None;
                self.refresh();
                self.anchor = None;
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.clamp_caret();
                self.record_caret();
            }
            Err(e) => self.status = Some(format!("code language: {e}")),
        }
    }

    /// The `span.start` of the code block covering the caret — the anchor
    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
    /// in none.
    fn code_block_start_at_caret(&mut self) -> Option<usize> {
        let off = self.caret;
        self.nodes()
            .into_iter()
            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
            .max_by_key(|n| n.span.start)
            .map(|n| n.span.start)
    }

    /// The source range of the text inside the link covering `off` — what sits
    /// between its `[` and `]`. `None` when twig reports no link there.
    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
        self.nodes()
            .into_iter()
            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
            // the other's `span.start`; the link that starts latest at or before
            // `off` is the one `off` is actually in.
            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
            .max_by_key(|n| n.span.start)
            .and_then(|n| n.content_span)
    }

    // ── undo / redo ───────────────────────────────────────────────────────────
    // twig owns the history of *bytes* (it owns the buffer) and now carries the
    // caret through it too: `record_caret` stashes each state's caret in twig's
    // opaque per-step blob, and undo/redo hand it back with the source they
    // restore. So leaf keeps no history of its own — no parallel stacks to march
    // in lockstep and silently drift out of it.

    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
    /// where they were when that step began.
    pub fn undo(&mut self) {
        match self.editor.undo() {
            Ok(Some(change)) => self.after_history(change),
            Ok(None) => self.status = Some("nothing to undo".into()),
            Err(e) => self.status = Some(format!("undo: {e}")),
        }
    }

    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
    /// selection back where that step originally left them.
    pub fn redo(&mut self) {
        match self.editor.redo() {
            Ok(Some(change)) => self.after_history(change),
            Ok(None) => self.status = Some("nothing to redo".into()),
            Err(e) => self.status = Some(format!("redo: {e}")),
        }
    }

    /// Refresh the cached source and put the caret back where the step being
    /// undone/redone had it, clearing any active run.
    ///
    /// The caret comes from twig's blob for the restored state (what
    /// `record_caret` stored). `change` is only the fallback for a state with no
    /// blob — a caret at the end of the restored text, which is where this always
    /// landed before the blobs were kept. It is the edit site, not where the user
    /// was standing, so it's a floor and not the behaviour: undoing should hand
    /// back the document *and* the place you were working, which for an edit made
    /// anywhere but under the caret are two different places.
    fn after_history(&mut self, change: Change) {
        self.refresh();
        match self
            .editor
            .caret_blob()
            .ok()
            .and_then(|b| CaretState::from_blob(&b))
        {
            Some(state) => {
                self.caret = state.caret.min(self.source.len());
                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
            }
            None => {
                self.caret = change.new.end.min(self.source.len());
                self.anchor = None;
            }
        }
        self.goal_col = None;
        self.last_edit_kind = None;
        self.dirty = self.source != self.clean_source;
        self.status = None;
        self.clamp_caret();
    }

    // ── the file ──────────────────────────────────────────────────────────────

    #[cfg(feature = "fs")]
    pub fn save(&mut self) {
        if self.is_untitled() {
            // No path to write and no name to invent: ⌘S on an untitled document
            // is a Save As, and only a frontend has a picker to ask with. Say so
            // rather than failing at the filesystem with an empty path.
            self.status = Some("untitled — save as…".into());
            return;
        }
        let path = self.path.clone();
        if self.write(&path) {
            self.mark_saved();
        }
    }

    /// Save As: write the document to `path` and *move* it there — `self.path`
    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
    /// what Save As means; a copy would leave the user editing a document whose
    /// name is no longer where their keystrokes go.
    ///
    /// The move only happens if the bytes actually landed. A failed write leaves
    /// the path, `dirty`, and the disk watermark exactly as they were, with the
    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
    /// must never come away believing it was saved.
    ///
    /// An existing `path` is overwritten, and the caller is the one that knows
    /// whether to ask first: a Save As picker has already run that prompt, and a
    /// second confirmation from down here would be the same question twice.
    ///
    /// `format` does **not** follow the new extension. The buffer is parsed as
    /// the format it was opened with, and re-reading it as another one is a
    /// conversion — a different, lossy operation that would throw away the undo
    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
    /// until it's reopened.
    #[cfg(feature = "fs")]
    pub fn save_as(&mut self, path: PathBuf) {
        if !self.write(&path) {
            return;
        }
        self.path = path;
        self.mark_saved();
    }

    /// Put `source` on disk at `path`, reporting whether it got there. The one
    /// place leaf writes a document, so a save and a Save As can't disagree
    /// about what a failure looks like.
    #[cfg(feature = "fs")]
    fn write(&mut self, path: &Path) -> bool {
        match std::fs::write(path, self.source.as_bytes()) {
            Ok(()) => true,
            Err(e) => {
                self.status = Some(format!("save failed: {e}"));
                false
            }
        }
    }

    /// Re-base the document's saved watermark to the current bytes: clears
    /// `dirty`, records `source` as the new clean state (so undoing back to here
    /// clears the flag again), and re-stamps the on-disk hash.
    ///
    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
    /// the hook a **filesystem-free host** calls itself once it has persisted
    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
    /// are already where that host wants them, and this just tells the model they
    /// are safe.
    pub fn mark_saved(&mut self) {
        self.clean_source = self.source.clone();
        self.dirty = false;
        // The bytes on disk are now ours, so this is the new watermark: without
        // re-stamping it, every save would report its own work as an external
        // change forever after.
        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
        self.status = Some(format!("saved {}", self.file_name()));
    }

    /// What the file looks like now against the bytes leaf last read or wrote.
    ///
    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
    /// so this is a filesystem round-trip, not a per-frame question — ask it
    /// when a window regains focus, on a timer, or before a save.
    ///
    /// This *only* reports the file. Whether the document also has unsaved edits
    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
    /// [`DiskState::Changed`] means a save overwrites someone's work and a
    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
    /// it has no way to ask — so it hands a frontend both halves and lets it put
    /// the question to the person who can answer it.
    #[cfg(feature = "fs")]
    pub fn disk_state(&self) -> DiskState {
        let Some(want) = self.disk_hash else {
            return DiskState::Untitled;
        };
        match std::fs::read(&self.path) {
            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
            Ok(_) => DiskState::Changed,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
            Err(_) => DiskState::Unreadable,
        }
    }

    /// Re-read the file and replace the document with what's there — the other
    /// answer to a [`DiskState::Changed`].
    ///
    /// **Discards unsaved changes and the undo history, unconditionally.** It
    /// doesn't check `dirty` first: a frontend that wants to protect unsaved
    /// work asks (`dirty` + [`Doc::disk_state`]) *before* calling this, and one
    /// reloading a clean document shouldn't have to argue with a guard. The
    /// history goes because twig's undo stack belongs to the buffer, and these
    /// are different bytes — replaying a step recorded against the old ones onto
    /// them would corrupt the document, and nothing here can honestly rebase it.
    ///
    /// The caret keeps its byte offset, clamped to the new length; the selection
    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
    /// file changed, so it can't know where the caret "still" is. Clamping keeps
    /// it where the user left it in the common case (a change further down the
    /// file, or none in the text they're sitting in), and never puts it
    /// somewhere invalid. A selection has two such offsets and no such excuse —
    /// silently reinterpreting one over changed bytes would arm the *next*
    /// keystroke to delete something the user never selected.
    ///
    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
    /// document alone with a status.
    #[cfg(feature = "fs")]
    pub fn reload(&mut self) {
        if self.is_untitled() {
            self.status = Some("no file to reload".into());
            return;
        }
        let bytes = match std::fs::read(&self.path) {
            Ok(b) => b,
            Err(e) => {
                self.status = Some(format!("reload failed: {e}"));
                return;
            }
        };
        let Ok(source) = String::from_utf8(bytes) else {
            self.status = Some("reload failed: file is not UTF-8".into());
            return;
        };
        // Reparse rather than splice the difference in: leaf doesn't know what
        // changed, and `format` is the format this document is, not what the
        // (unchanged) name now says — see `save_as`.
        let editor = match new_editor(source.as_bytes(), self.format) {
            Ok(ed) => ed,
            Err(e) => {
                self.status = Some(format!("reload failed: {e}"));
                return;
            }
        };
        self.editor = editor;
        self.disk_hash = Some(hash_bytes(source.as_bytes()));
        self.clean_source = source.clone();
        self.source = source;
        // Reload replaces the text without going through `refresh`, so it has to
        // move the revision itself or every frontend would keep painting the old
        // file from cache.
        self.revision += 1;
        self.caret = self.caret.min(self.source.len());
        self.anchor = None;
        self.goal_col = None;
        self.last_edit_kind = None;
        self.dirty = false;
        self.status = Some(format!("reloaded {}", self.file_name()));
        self.clamp_caret();
    }

    /// Re-read the source from twig after it has changed the document. The one
    /// funnel every edit, undo, and redo comes through — so it's where the
    /// revision moves, and anything cached against the text dies here.
    fn refresh(&mut self) {
        if let Ok(s) = self.editor.source_str() {
            self.source = s;
        }
        self.revision += 1;
        self.clamp_caret();
    }

    // ── caret movement ─────────────────────────────────────────────────────────
    // `extend` grows the selection (Shift+motion): it pins the anchor on the
    // first extended step and moves only the caret; an un-extended motion drops
    // the selection.

    /// Place the caret at byte `offset` (clamped to a char boundary), extending
    /// the selection when `extend` is set. The public form of `move_to`, for a
    /// frontend that hit-tests pixels straight to a source offset.
    pub fn place_caret(&mut self, offset: usize, extend: bool) {
        self.goal_col = None;
        let before = self.caret;
        // A pixel hit-test can land between the visible caret stops — in the
        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
        // Snap to the nearest real stop so the caret can't come to rest where it
        // would draw in one place and type in another. The `(row, col)` click
        // path (`click`) already snaps this way through `offset_of_pos`; the
        // source view reaches every byte, so it snaps to nothing.
        let target = match self.view {
            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
            // The source view reaches every byte, so there is no stop to snap
            // to — but "every byte" still means every *character* boundary. A
            // caret resting inside a multi-byte character draws nowhere real
            // and panics the next time anything slices there.
            View::Source => {
                let mut o = offset.min(self.source.len());
                while o > 0 && !self.source.is_char_boundary(o) {
                    o -= 1;
                }
                o
            }
        };
        self.move_to(target, extend);
        self.clamp_caret();
        self.debug_assert_on_a_stop(before);
    }

    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
    /// grab the metadata) while the source view still selects the literal whole.
    pub fn select_all(&mut self) {
        self.anchor = Some(self.caret_floor());
        self.caret = self.source.len();
        self.goal_col = None;
        self.last_edit_kind = None;
        self.status = None;
    }

    /// Select the word (or whitespace / punctuation run) at `offset` — the
    /// double-click gesture. Anchors on the run's start with the caret at its
    /// end so a following Shift-motion extends from the far edge.
    pub fn select_word_at(&mut self, offset: usize) {
        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
        self.anchor = Some(s);
        self.caret = e;
        self.goal_col = None;
        self.last_edit_kind = None;
        self.status = None;
        self.clamp_caret();
    }

    /// Select the whole enclosing text block (paragraph, heading, list item's
    /// text…) at `offset` — the triple-click gesture. Reads the range straight
    /// from the AST (twig's `content_span`), so it selects the entire *logical*
    /// paragraph even when that paragraph soft-wraps across several visual rows —
    /// where a visual-row-based select breaks down, because one source offset at
    /// a wrap boundary belongs to two rows at once.
    pub fn select_block_at(&mut self, offset: usize) {
        let off = offset.min(self.source.len());
        let range = self
            .editor
            .ancestors_at(off)
            .ok()
            .and_then(|chain| {
                // Ancestors run root → deepest; the deepest node that is neither
                // an inline span nor a multi-block container is the text block
                // the caret sits in (a paragraph, a heading, a code block…).
                chain
                    .into_iter()
                    .rev()
                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
                    .map(|m| m.content_span.unwrap_or(m.span))
            })
            .unwrap_or_else(|| source_line_range(&self.source, off));
        self.anchor = Some(range.start.min(self.source.len()));
        self.caret = range.end.min(self.source.len());
        self.goal_col = None;
        self.last_edit_kind = None;
        self.status = None;
        self.clamp_caret();
    }

    /// The lowest source offset the caret may occupy in the active view. In
    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
    /// the first rendered offset; the source view reaches everything, so it's 0.
    fn caret_floor(&self) -> usize {
        match self.view {
            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
            View::Source => 0,
        }
    }

    /// Land in a table cell with its whole content selected — the anchor at the
    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
    /// like tabbing into a form field: the text comes up selected, so typing
    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
    /// end`) collapses to a plain caret home (an empty selection is no selection).
    fn select_cell(&mut self, start: usize, end: usize) {
        let floor = self.caret_floor();
        self.anchor = Some(start.min(self.source.len()).max(floor));
        self.caret = end.min(self.source.len()).max(floor);
        self.goal_col = None;
        self.status = None;
        self.last_edit_kind = None;
        self.clear_pending();
    }

    fn move_to(&mut self, offset: usize, extend: bool) {
        if extend {
            if self.anchor.is_none() {
                self.anchor = Some(self.caret);
            }
        } else {
            self.anchor = None;
        }
        self.caret = offset.min(self.source.len()).max(self.caret_floor());
        self.status = None;
        // A caret move ends the current typing/deletion run, so the next edit
        // starts a fresh undo group rather than coalescing across the gap.
        self.last_edit_kind = None;
        // Moving away disarms any sticky mark — "start bold" applies only where
        // it was asked for, not wherever the caret next lands.
        self.clear_pending();
    }

    // In the source view, motion walks source bytes / source lines. In the
    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
    // what steps the caret cleanly over hidden delimiters.

    pub fn move_left(&mut self, extend: bool) {
        self.goal_col = None;
        if !extend && let Some((s, _e)) = self.selection() {
            self.move_to(s, false);
            return;
        }
        let target = match self.view {
            View::Source => {
                if self.caret > 0 {
                    prev_boundary(&self.source, self.caret)
                } else {
                    0
                }
            }
            // Walks caret *stops*, not columns: decoration (a table border, a
            // cell's padding) is stepped over in one press, and a hidden
            // delimiter never holds the caret up.
            View::Wysiwyg => self.vmap.stop_before(self.caret).unwrap_or(self.caret),
        };
        let before = self.caret;
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    pub fn move_right(&mut self, extend: bool) {
        self.goal_col = None;
        if !extend && let Some((_s, e)) = self.selection() {
            self.move_to(e, false);
            return;
        }
        let target = match self.view {
            View::Source => {
                if self.caret < self.source.len() {
                    next_boundary(&self.source, self.caret)
                } else {
                    self.caret
                }
            }
            View::Wysiwyg => self.vmap.stop_after(self.caret).unwrap_or(self.caret),
        };
        let before = self.caret;
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// Move to the start of the previous word (⌥← / Ctrl+←).
    pub fn move_word_left(&mut self, extend: bool) {
        self.goal_col = None;
        let before = self.caret;
        let target = self.word_left_from(self.caret);
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// Move to the end of the next word (⌥→ / Ctrl+→).
    pub fn move_word_right(&mut self, extend: bool) {
        self.goal_col = None;
        let before = self.caret;
        let target = self.word_right_from(self.caret);
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    // Word boundaries are found in the space the *view* is in. The source view
    // walks the source, because there the source is what's rendered. WYSIWYG
    // walks the rendered text instead: `**` is invisible to the user, so it has
    // to be invisible to word motion too — a caret parked inside one draws in
    // the column after `bold` and types two bytes earlier, and a word-delete
    // that stops there shreds the markup into `a ** c`.

    /// The word boundary to the left of `off` in the active view's space.
    fn word_left_from(&self, off: usize) -> usize {
        match self.view {
            View::Source => prev_word(&self.source, off),
            View::Wysiwyg => self.glyph_word_left(off),
        }
    }

    /// The word boundary to the right of `off` in the active view's space.
    fn word_right_from(&self, off: usize) -> usize {
        match self.view {
            View::Source => next_word(&self.source, off),
            View::Wysiwyg => self.glyph_word_right(off),
        }
    }

    /// The character class of the glyph drawn at stop `off`.
    ///
    /// Read from the source, because a stop points at the source byte its glyph
    /// came from — the source *is* where the rendered character is written. What
    /// makes the walk glyph space rather than source space is that it only ever
    /// visits stops, and the hidden bytes between them have none.
    fn class_at(&self, off: usize) -> Class {
        self.source
            .get(off..)
            .and_then(|s| s.chars().next())
            .map_or(Class::Space, classify)
    }

    /// [`next_word`] in glyph space: skip any leading separators, then consume
    /// the following word run, with the stop table standing in for the source's
    /// characters.
    fn glyph_word_right(&self, from: usize) -> usize {
        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
            return from;
        };
        let mut in_word = false;
        loop {
            match self.class_at(off) {
                Class::Word => in_word = true,
                _ if in_word => return off,
                _ => {}
            }
            match self.vmap.stop_after(off) {
                Some(next) => off = next,
                None => return off,
            }
        }
    }

    /// [`prev_word`] in glyph space: skip separators walking left, then consume
    /// the preceding word run.
    fn glyph_word_left(&self, from: usize) -> usize {
        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
            return from;
        };
        let mut in_word = false;
        while let Some(prev) = self.vmap.stop_before(off) {
            match self.class_at(prev) {
                Class::Word => in_word = true,
                _ if in_word => return off,
                _ => {}
            }
            off = prev;
        }
        off
    }

    /// After a motion that walks the visual map, the caret must be *on* the map.
    /// A stop is the only offset where the caret draws and edits in the same
    /// place, and it's the invariant both a caret parked inside an emoji and one
    /// parked inside a `**` were quietly breaking.
    ///
    /// Only when the caret actually moved: a walk with nowhere to go leaves it
    /// where it was, which is wherever the floor or a frontend put it rather
    /// than somewhere this motion chose.
    fn debug_assert_on_a_stop(&self, before: usize) {
        debug_assert!(
            self.view != View::Wysiwyg
                || self.vmap.num_rows() == 0
                || self.caret == before
                || self.vmap.is_stop(self.caret),
            "motion left the caret at {}, which is not a caret stop: it would draw in \
             one place and type in another",
            self.caret
        );
    }

    // Up and Down run off the ends of the document rather than stopping dead at
    // them: Up from the first row lands at the document's start, Down from the
    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
    // reaching the end of the text is what a reader means by it.
    //
    // The views used to disagree here by accident rather than by decision: the
    // source view fell into the edge behaviour through `row_col_to_offset`
    // clamping an out-of-range row to the end of the string, while WYSIWYG had
    // no row below to walk to and did nothing at all. They share the rule now,
    // each in its own space — the source view reaches every byte, WYSIWYG only
    // the offsets it draws.

    pub fn move_up(&mut self, extend: bool) {
        let (row, col) = self.caret_pos();
        let goal = self.goal_col.unwrap_or(col);
        let target = match self.view {
            View::Source => match row.checked_sub(1) {
                Some(r) => row_col_to_offset(&self.source, r, goal),
                None => self.reachable_start(),
            },
            // A table's border rules are drawn but hold no caret, so Up steps
            // over them to the row that does.
            View::Wysiwyg => match self.vmap.navigable_above(row) {
                Some(r) => self.row_target(r, goal),
                None => self.reachable_start(),
            },
        };
        self.step_vertical(target, goal, extend);
    }

    pub fn move_down(&mut self, extend: bool) {
        let (row, col) = self.caret_pos();
        let goal = self.goal_col.unwrap_or(col);
        let target = match self.view {
            View::Source => match self.source_row_below(row) {
                Some(r) => row_col_to_offset(&self.source, r, goal),
                None => self.reachable_end(),
            },
            View::Wysiwyg => match self.vmap.navigable_below(row) {
                Some(r) => self.row_target(r, goal),
                None => self.reachable_end(),
            },
        };
        self.step_vertical(target, goal, extend);
    }

    /// Land a vertical motion at `target`, latching the `goal` column it aimed
    /// with so the rest of the run keeps aiming there.
    ///
    /// A motion with nowhere to go changes *nothing*, the goal column included:
    /// the latch used to run before the early return at the top of the document,
    /// so an Up that did nothing still armed a column, and the next Down aimed
    /// at one the caret had never been in.
    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
        let before = self.caret;
        if target == before {
            return;
        }
        self.goal_col = Some(goal);
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// The source line below `row`, or `None` when `row` is the last one. Lines
    /// are counted by newline, so a trailing one leaves a real, empty last line
    /// for the caret to sit on — the document ends below it, not on it.
    fn source_row_below(&self, row: usize) -> Option<usize> {
        let last = self.source.bytes().filter(|&b| b == b'\n').count();
        (row < last).then_some(row + 1)
    }

    /// Where a vertical motion aiming at the `goal` column lands on visual row
    /// `r`: the column clamped to the row, mapped to its offset, then held
    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
    /// column belongs to the row below, and a gutter's column 0 points at the
    /// block rather than at this row.
    fn row_target(&self, r: usize, goal: usize) -> usize {
        let (start, end) = self.row_bounds(r);
        self.vmap
            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
            .clamp(start, end)
    }

    /// The first and last offsets the caret can reach in the active view.
    ///
    /// Not the same span in both: the source view shows every byte, so it can
    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
    /// sits below the first stop, and a document's trailing newline is drawn
    /// nowhere and so sits past the last.
    fn reachable_start(&self) -> usize {
        match self.view {
            View::Source => 0,
            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
        }
    }

    fn reachable_end(&self) -> usize {
        match self.view {
            View::Source => self.source.len(),
            View::Wysiwyg => self
                .vmap
                .stop_at_or_before(self.source.len())
                .unwrap_or(self.caret),
        }
    }

    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
    /// including the space a soft wrap ate off its end, which is drawn on this
    /// row however much the offset past it belongs to the next one.
    fn row_span(&self, r: usize) -> (usize, usize) {
        let start = self
            .vmap
            .row_start(r)
            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
        (start.min(end), end)
    }

    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
    /// this row's last position is the one before it — the offset before the
    /// space the wrap ate, where the caret draws just past the row's last word
    /// and types there too.
    ///
    /// Aiming at the shared offset instead is what stalled End: it is the row's
    /// last *column*, so End pressed on the row reached it and then read back as
    /// the row below's start, where a second press ran on to that row's end and
    /// the next to the one after — End walking down the paragraph a row a press.
    fn row_bounds(&self, r: usize) -> (usize, usize) {
        let (start, end) = self.row_span(r);
        let wraps = self
            .vmap
            .navigable_below(r)
            .and_then(|b| self.vmap.row_start(b))
            .is_some_and(|off| off == end);
        match wraps {
            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
            false => (start, end),
        }
    }

    /// The `[start, end]` of the line Home and End aim at: the visual row in
    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
    ///
    /// A soft-wrapped row is a line here, because it is one to the eye and the
    /// eye is what these keys are aimed by — a reader pressing End means the end
    /// of the line they can see. (`select_block_at` wants the opposite and reads
    /// the AST for it: a triple-click grabs the whole paragraph, however many
    /// rows it folds into.)
    fn line_bounds(&self) -> (usize, usize) {
        let (row, _) = self.caret_pos();
        match self.view {
            View::Source => {
                let start = line_start(&self.source, row);
                (start, line_end_from(&self.source, start))
            }
            View::Wysiwyg => self.row_bounds(row),
        }
    }

    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
    /// *drawn* — what a kill takes.
    ///
    /// The two part only at a soft wrap, over the space the wrap ate: the caret
    /// can't stand after it (that offset opens the row below, and End stopping
    /// there would walk), but it is on this row, and a kill that spared it would
    /// leave a double space behind where the row's text had been. Deleting it
    /// joins nothing — a wrap is drawn, not written.
    fn line_span(&self) -> (usize, usize) {
        let (row, _) = self.caret_pos();
        match self.view {
            View::Source => self.line_bounds(),
            View::Wysiwyg => self.row_span(row),
        }
    }

    /// The first offset in `[start, end]` holding something other than
    /// whitespace, or `end` when the line holds nothing else — where Home aims.
    ///
    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
    /// so a hidden delimiter is never taken for the line's first character (nor
    /// landed on), and the source view steps the source it is showing.
    fn first_non_space(&self, start: usize, end: usize) -> usize {
        let mut off = start;
        while off < end {
            if self.class_at(off) != Class::Space {
                return off;
            }
            off = match self.view {
                View::Source => next_boundary(&self.source, off),
                View::Wysiwyg => match self.vmap.stop_after(off) {
                    Some(next) => next,
                    None => return end,
                },
            };
        }
        end
    }

    /// Home: to the first character on the line, or to column 0 when the caret
    /// is already on it — the two-press toggle every editor spells this way.
    /// The indentation is somewhere the caret has to be able to reach and almost
    /// never where a reader is headed, so it costs the second press.
    pub fn move_home(&mut self, extend: bool) {
        self.goal_col = None;
        let (start, end) = self.line_bounds();
        let text = self.first_non_space(start, end);
        let target = if self.caret == text { start } else { text };
        let before = self.caret;
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// End: to the end of the line.
    pub fn move_end(&mut self, extend: bool) {
        self.goal_col = None;
        let (_, end) = self.line_bounds();
        let before = self.caret;
        self.move_to(end, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
    /// when the caret isn't in a table, or is already in the last/first cell — the
    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
    /// meaning everywhere else.
    pub fn cell_hop(&mut self, forward: bool) -> bool {
        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
            return false;
        };
        // Flatten to document (row-major) order and step one cell either way.
        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
        let next = if forward {
            i.checked_add(1)
        } else {
            i.checked_sub(1)
        };
        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
            return false; // at the table's edge; leave Tab to the frontend
        };
        self.select_cell(start, end);
        true
    }

    /// Move the caret to the cell directly above (`down == false`) or below in
    /// the same column, landing with the cell's whole content selected (see
    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
    /// when the caret isn't in a table), so the frontend can fall through — the
    /// vertical counterpart of [`cell_hop`].
    ///
    /// A ragged row that is short a column clamps to its last cell, so Down never
    /// falls out of the table over a gap the row above happened to have.
    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
            return false;
        };
        let target = match down {
            true => r + 1,
            false if r == 0 => return false,
            false => r - 1,
        };
        let Some(row) = grid.get(target) else {
            return false;
        };
        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
            return false;
        };
        self.select_cell(start, end);
        true
    }

    /// The table containing `off` as a row-major grid of `(start, end)` cell
    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
    /// isn't in a table. Read straight off the visual map's laid-out grid, so
    /// every cell (an empty one included, whose derived home twig gives no
    /// `content_span` for) is present and in the order Tab walks them.
    // Grid, row, column — three returns that only ever travel together, and a
    // named type for the pair of them would be read at one call site.
    #[allow(clippy::type_complexity)]
    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
        for t in &self.vmap.tables {
            let mut pos = None;
            let grid: Vec<Vec<(usize, usize)>> = t
                .grid
                .iter()
                .enumerate()
                .map(|(r, row)| {
                    row.cells
                        .iter()
                        .enumerate()
                        .map(|(c, cell)| {
                            if pos.is_none() && off >= cell.start && off <= cell.end {
                                pos = Some((r, c));
                            }
                            (cell.start, cell.end)
                        })
                        .collect()
                })
                .collect();
            if let Some((r, c)) = pos {
                return Some((grid, r, c));
            }
        }
        None
    }

    // ── table key policy ──────────────────────────────────────────────────────
    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
    // as one policy every frontend shares, rather than each re-deriving it. Each
    // reports whether it acted *as a table key*; a `false` hands the key back to
    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
    // everywhere else.

    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
    /// back and simply stays put at the very first cell. `false` when the caret
    /// isn't in a table.
    pub fn cell_tab(&mut self, forward: bool) -> bool {
        if !self.caret_in_table() {
            return false;
        }
        if self.cell_hop(forward) {
            return true;
        }
        // Off the last cell: grow the table by a row and step into its first
        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
        if forward {
            self.append_row_and_enter(0);
        }
        true
    }

    /// Return inside a table: drop to the cell below in the same column,
    /// appending a new row when the caret is already in the last one. `false`
    /// when the caret isn't in a table, so the frontend inserts a newline.
    pub fn cell_return(&mut self) -> bool {
        if !self.caret_in_table() {
            return false;
        }
        if self.cell_move_vertical(true) {
            return true;
        }
        // Already on the last row: grow one below and drop into the same column.
        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
        self.append_row_and_enter(col);
        true
    }

    /// Append a row below the caret's (last) row and land in `col` of it. The
    /// caret is in the last row, so twig's "insert below" makes the fresh row the
    /// table's new last — but twig re-spells the whole table, moving every byte,
    /// so the destination is read back from the rebuilt grid by the table's
    /// position (stable across a row insert), not from the pre-edit caret.
    fn append_row_and_enter(&mut self, col: usize) {
        let table = self.caret_table_index();
        self.table_insert_row(true);
        self.rebuild_map();
        let Some((start, end)) = table
            .and_then(|ti| self.vmap.tables.get(ti))
            .and_then(|t| t.grid.last())
            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
            .map(|cell| (cell.start, cell.end))
        else {
            return;
        };
        self.select_cell(start, end);
    }

    /// The index, among the document's tables, of the one the caret sits in —
    /// `None` when it's in none. Used to re-find a table after an edit re-spells
    /// it (a row insert leaves the table order unchanged).
    fn caret_table_index(&self) -> Option<usize> {
        let off = self.caret;
        self.vmap.tables.iter().position(|t| {
            t.grid
                .iter()
                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
        })
    }

    /// Shift+Return inside a table: insert a hard line break *within* the current
    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
    /// table, so the frontend inserts an ordinary line break.
    ///
    /// A table row is a single source line, so the newline-spelled hard break
    /// can't live in a cell. twig spells the in-cell break the format's way
    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
    /// break round-trips as structure the renderer reads back as a line — not the
    /// opaque raw HTML the old raw-splice left behind.
    ///
    /// Djot has no idiomatic in-cell break, so twig refuses it
    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
    /// would render as the literal text `<br>`. The gesture is still *consumed*
    /// there — returning `false` would let the frontend insert a real newline,
    /// which splits the one-line row — it just leaves the cell unchanged and says
    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
    ///
    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
    /// have to be read together: djot is not the only `false`, and naming it in
    /// the message was already a guess that HTML — which spells the break as its
    /// own `<br>` — would have made wrong.
    pub fn cell_line_break(&mut self) -> bool {
        if !self.caret_in_table() {
            return false;
        }
        self.record_caret();
        match self.editor.insert_line_break(self.caret) {
            Ok(change) => {
                self.last_edit_kind = None;
                self.refresh();
                self.caret = change.new.end;
                self.anchor = None;
                self.goal_col = None;
                self.clamp_caret();
                self.dirty = self.source != self.clean_source;
                self.status = None;
                self.record_caret();
            }
            Err(twig::Error::UnsupportedFormat) => {
                self.status = Some(format!(
                    "in-cell line breaks aren't supported in {}",
                    self.format_name()
                ));
            }
            Err(_) => {}
        }
        true
    }

    /// Rebuild the visual map at the width the last build used. A structural edit
    /// bumps the revision and swaps the source in, but leaves the *map* stale;
    /// when a single gesture edits and then moves over the result (Tab appending
    /// a row, then stepping into it), the move needs the map to already show the
    /// edit rather than waiting for the frontend's next frame.
    fn rebuild_map(&mut self) {
        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
        self.build_map(wrap);
    }

    /// Move the caret to the very start of the document (⌘↑ on macOS,
    /// Ctrl+Home on Windows/Linux).
    pub fn move_doc_start(&mut self, extend: bool) {
        self.goal_col = None;
        self.move_to(0, extend);
    }

    /// Move the caret to the very end of the document (⌘↓ on macOS,
    /// Ctrl+End on Windows/Linux).
    pub fn move_doc_end(&mut self, extend: bool) {
        self.goal_col = None;
        let end = self.source.len();
        self.move_to(end, extend);
    }

    /// Point the caret at the body cell `(row, col)` the mouse landed on —
    /// `col` being a cell of the terminal grid, which is what a display column
    /// is. A click on the far cell of a wide character lands at that
    /// character's start; the mapping's own doc-comments carry the rule.
    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
        self.goal_col = None;
        let target = match self.view {
            View::Source => row_col_to_offset(&self.source, row, col),
            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
        };
        let before = self.caret;
        self.move_to(target, extend);
        self.debug_assert_on_a_stop(before);
    }

    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
    /// screen if it has moved since the last frame, and never scroll past the
    /// last of `rows`.
    ///
    /// Only if it has *moved* — that's the whole point. Revealing the caret on
    /// every frame ties the viewport to it, and a scroll wheel that fights the
    /// caret for the viewport loses: the view snaps back the instant it tries to
    /// pass the caret's row, so the document can't be scrolled beyond what's
    /// already on screen. A caret move is the frontend's cue to follow; a scroll
    /// with the caret sitting still is the reader's cue to leave it alone.
    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
        if self.drawn_caret != Some(self.caret) {
            if caret_row < self.scroll {
                self.scroll = caret_row;
            } else if height > 0 && caret_row >= self.scroll + height {
                self.scroll = caret_row + 1 - height;
            }
            self.drawn_caret = Some(self.caret);
        }
        self.scroll = self.scroll.min(rows.saturating_sub(1));
    }

    /// The caret's screen position `(row, col)` in the active view's grid, with
    /// `col` a display column: the cell to draw the caret in, which on a line of
    /// `你好` or emoji is not the count of characters before it.
    pub fn caret_pos(&self) -> (usize, usize) {
        match self.view {
            View::Source => offset_to_row_col(&self.source, self.caret),
            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
        }
    }

    fn clamp_caret(&mut self) {
        if self.caret > self.source.len() {
            self.caret = self.source.len();
        }
        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
        // any selection anchor) to the first rendered offset.
        let floor = self.caret_floor();
        if self.caret < floor {
            self.caret = floor;
        }
        if let Some(a) = self.anchor
            && a < floor
        {
            self.anchor = Some(floor);
        }
        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
            self.caret -= 1;
        }
    }
}

// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────

// Left/right motion and backspace/delete step by *grapheme cluster*, not
// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
// marks moves and deletes as the single character a user sees. Grapheme
// boundaries are a superset of char boundaries, so the caret stays valid for twig.

/// How an insert of `text` groups for undo: a single typed character folds into
/// the run of typing around it, while a newline or a multi-character insert is a
/// step of its own.
fn typed_edit_kind(text: &str) -> EditKind {
    if text.chars().take(2).count() == 1 && text != "\n" {
        EditKind::Insert
    } else {
        EditKind::Other
    }
}

fn prev_boundary(s: &str, i: usize) -> usize {
    let mut cursor = GraphemeCursor::new(i, s.len(), true);
    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
}

fn next_boundary(s: &str, i: usize) -> usize {
    let mut cursor = GraphemeCursor::new(i, s.len(), true);
    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
}

// ── word boundaries ──────────────────────────────────────────────────────────
// The shared primitive behind word-wise motion, word deletion, and
// double-click-to-select-a-word. A "word" is a maximal run of one character
// class; whitespace and punctuation are their own classes, so motion skips
// cleanly between them the way native text fields do.

#[derive(PartialEq, Eq, Clone, Copy)]
enum Class {
    Word,
    Space,
    Other,
}

/// The source range of an inline node's own visible text — the part of it a
/// WYSIWYG caret can reach, as against the delimiters that only spell it.
/// `None` for a node with no interior to empty (a `str`, a break).
///
/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
/// one delimiter in from the span — the same place the renderer maps it to. A
/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
/// against the source rather than trusted: a range guessed wrong here is text
/// deleted wrong.
fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
    if let Some(span) = n.content_span.clone() {
        return Some(span);
    }
    match n.kind.as_str() {
        "verbatim" | "inline_math" => {
            let text = n.text.as_ref()?;
            let start = n.span.start + 1;
            let range = start..start + text.len();
            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
        }
        _ => None,
    }
}

/// The `id` a node declares, or `None` for one that declares none — the
/// attribute djot writes for a `{#v1}` and mints for a heading.
///
/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
/// names nothing, so it reads as absent rather than as the empty string.
fn declared_id(n: &FlatNode) -> Option<&str> {
    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
}

/// A heading's words reduced to the form a link fragment spells them in:
/// lowercase, runs of anything else collapsed to a single `-`, with none left
/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
///
/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
/// any other language is still a heading someone will link to. Underscores
/// survive for the same reason they do on the web: they are word characters
/// wherever identifiers are written.
fn slug(text: &str) -> String {
    let mut out = String::new();
    let mut pending = false;
    for c in text.chars() {
        if c.is_alphanumeric() || c == '_' {
            if pending && !out.is_empty() {
                out.push('-');
            }
            pending = false;
            out.extend(c.to_lowercase());
        } else {
            pending = true;
        }
    }
    out
}

fn is_block_container(kind: &Kind) -> bool {
    matches!(
        kind,
        Kind::Doc
            | Kind::Section
            | Kind::BlockQuote
            | Kind::BulletList
            | Kind::OrderedList
            | Kind::TaskList
            | Kind::ListItem
            | Kind::TaskListItem
            // Every `container` — a directive in any of its three forms, or a
            // promoted HTML element. A *text* directive is really inline, so
            // claiming it here is a small overreach, and the deliberate one this
            // function's kind-only peer `is_inline_kind` documents: the pair is
            // consulted together, and answering "block container" for something
            // inline is what keeps an ancestor walk from stopping short of the
            // paragraph that actually holds it.
            | Kind::Container
    )
}

/// The `[start, end)` byte range of the source line containing `off` (newline
/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
/// line between paragraphs).
fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
    let off = off.min(s.len());
    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
    start..end
}

/// How many leading bytes an outdent takes off `line`: a whole indent level
/// where the line has one, and whatever it has where it has less.
///
/// A leading tab counts as a level on its own. It's indentation some other
/// editor wrote, and one tab is one level everywhere it came from — measuring it
/// in spaces it doesn't contain would leave it untouchable.
fn outdent_width(line: &str, unit: usize) -> usize {
    if line.starts_with('\t') {
        return 1;
    }
    line.bytes().take(unit).take_while(|b| *b == b' ').count()
}

/// A list marker found at the head of a line, together with everything before it
/// that a sibling line has to repeat.
///
/// The three offsets differ only inside a block quote, where `>   - b` opens with
/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
/// `line_start == marker_start`, and `text` is the plain `"  - "`.
#[derive(Clone, Debug)]
struct ListMarker {
    /// The line's first byte.
    line_start: usize,
    /// Where the marker proper begins, past any quote prefix. The offset to hand
    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
    marker_start: usize,
    /// `line_start` through the marker's trailing space — quote prefix, indent
    /// and bullet together, which is what the next item's line opens with.
    text: String,
}

impl ListMarker {
    /// Where the item's content starts — one past the marker's trailing space.
    fn content_start(&self) -> usize {
        self.line_start + self.text.len()
    }
}

fn classify(c: char) -> Class {
    if c == '_' || c.is_alphanumeric() {
        Class::Word
    } else if c.is_whitespace() {
        Class::Space
    } else {
        Class::Other
    }
}

/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
/// skip any leading separators, then consume the following word run.
fn next_word(s: &str, i: usize) -> usize {
    let mut off = i;
    let mut in_word = false;
    for c in s[i..].chars() {
        if classify(c) == Class::Word {
            in_word = true;
        } else if in_word {
            break;
        }
        off += c.len_utf8();
    }
    off
}

/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
/// skip separators walking left, then consume the preceding word run.
fn prev_word(s: &str, i: usize) -> usize {
    let mut off = i;
    let mut in_word = false;
    for c in s[..i].chars().rev() {
        if classify(c) == Class::Word {
            in_word = true;
        } else if in_word {
            break;
        }
        off -= c.len_utf8();
    }
    off
}

/// The `[start, end)` run of same-class characters surrounding `off` — the
/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
/// the run ending there is used.
fn word_range_at(s: &str, off: usize) -> (usize, usize) {
    if s.is_empty() {
        return (0, 0);
    }
    let off = off.min(s.len());
    let reference = if off < s.len() {
        s[off..].chars().next()
    } else {
        s[..off].chars().next_back()
    };
    let Some(rc) = reference else {
        return (off, off);
    };
    let class = classify(rc);

    let mut start = off;
    for c in s[..start].chars().rev() {
        if classify(c) == class {
            start -= c.len_utf8();
        } else {
            break;
        }
    }
    let mut end = off;
    for c in s[end..].chars() {
        if classify(c) == class {
            end += c.len_utf8();
        } else {
            break;
        }
    }
    (start, end)
}

/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
/// the line's start — terminal cells, not characters, so the column names the
/// cell the caret is drawn in even on a line of `你好` or emoji.
fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
    let off = off.min(s.len());
    let mut row = 0;
    let mut line_start = 0;
    for (i, &b) in s.as_bytes().iter().enumerate() {
        if i >= off {
            break;
        }
        if b == b'\n' {
            row += 1;
            line_start = i + 1;
        }
    }
    (row, wysiwyg::text_width(&s[line_start..off]))
}

/// The byte offset at display column `col` of `row` (clamped to that line's
/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
///
/// A column landing *inside* a character — the second cell of `你`, or any cell
/// but the first of an emoji — resolves to that character's start, which is the
/// column the caret would have been drawn at to begin with. So both cells of a
/// wide character mean the character, and every offset survives the round trip
/// out to a column and back. The walk steps by grapheme cluster for the same
/// reason the caret does: a cluster is the character, and the cells belong to it
/// rather than to the codepoints spelling it.
fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
    let start = line_start(s, row);
    let end = line_end_from(s, start);
    let mut off = start;
    let mut at = 0; // the display column `off` sits at
    while off < end {
        let next = next_boundary(s, off).min(end);
        let cells = wysiwyg::text_width(&s[off..next]);
        if at + cells > col {
            break; // `col` is one of this cluster's own cells
        }
        at += cells;
        off = next;
    }
    off
}

fn line_start(s: &str, row: usize) -> usize {
    if row == 0 {
        return 0;
    }
    let mut r = 0;
    for (i, &b) in s.as_bytes().iter().enumerate() {
        if b == b'\n' {
            r += 1;
            if r == row {
                return i + 1;
            }
        }
    }
    s.len()
}

fn line_end_from(s: &str, start: usize) -> usize {
    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
}

/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
/// twig applies writing the mark out, so the toolbar can light the same button
/// that made the node.
///
/// `None` for every other kind, including the inline nodes that aren't marks at
/// all (`str`, `link`, `image`, the math and break kinds): they're things a
/// caret stands in, not formatting a button toggles.
fn inline_kind(kind: &Kind) -> Option<InlineKind> {
    Some(match kind {
        Kind::Strong => InlineKind::Strong,
        Kind::Emph => InlineKind::Emph,
        Kind::Verbatim => InlineKind::Verbatim,
        Kind::Mark => InlineKind::Mark,
        Kind::Superscript => InlineKind::Superscript,
        Kind::Subscript => InlineKind::Subscript,
        Kind::Insert => InlineKind::Insert,
        Kind::Delete => InlineKind::Delete,
        _ => return None,
    })
}

/// A watermark for a file's contents (see `Doc::disk_hash`).
///
/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
/// watermark is compared only against one taken by the same process moments
/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
fn hash_bytes(bytes: &[u8]) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    bytes.hash(&mut h);
    h.finish()
}

#[cfg(feature = "fs")]
fn detect_format(path: &Path) -> Result<Format> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    Ok(match ext.as_str() {
        "dj" | "djot" => Format::Djot,
        "md" | "markdown" => Format::Markdown,
        "xml" => Format::Xml,
        "html" | "htm" => Format::Html,
        other => return Err(anyhow!("unknown document extension: .{other}")),
    })
}

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

    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
    /// without one is a view no user is ever in.
    fn doc_in(view: View, name: &str, body: &str) -> Doc {
        // The fixture name doubles as the temp file's, so two tests picking the
        // same one raced under the parallel runner and read each other's body —
        // a green suite proving the wrong thing. The counter makes that
        // unreachable rather than asking every future caller to notice.
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut p = std::env::temp_dir();
        p.push(format!("leaf_test_{name}_{seq}.md"));
        std::fs::write(&p, body).unwrap();
        let mut d = Doc::open(p).unwrap();
        d.view = view;
        if view == View::Wysiwyg {
            d.build_visual(80);
        }
        d
    }

    // Source-view document for the source-behaviour tests. `Doc::open` now
    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
    // `wysiwyg_doc` builds the rich-text variant on top of this.
    fn doc_with(name: &str, body: &str) -> Doc {
        doc_in(View::Source, name, body)
    }

    /// Every visual row's drawn text — what the reader actually sees, which is
    /// the only thing the reveal preference is supposed to change.
    fn drawn_rows(d: &Doc) -> Vec<String> {
        d.vmap
            .rows
            .iter()
            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
            .collect()
    }

    /// Put the caret at the first byte of `needle` and rebuild, so the row under
    /// it becomes the revealed line.
    fn caret_at(d: &mut Doc, needle: &str) {
        d.caret = d.source.find(needle).expect("needle in source");
        d.build_visual(80);
    }

    #[test]
    fn blockquote_after_a_list_is_not_bulleted() {
        // twig nests a following top-level block quote under the `bullet_list`
        // (a direct child, not a `list_item`). The map must render it de-nested —
        // `│ quote`, never `• │ quote` — with a blank separator, like any block
        // that follows a list. Regression for the "combined list + blockquote" bug.
        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
        d.build_visual(80);
        let rows: Vec<String> = d
            .vmap
            .rows
            .iter()
            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
            .collect();
        assert!(
            rows.iter().any(|r| r == "│ quote"),
            "block quote should render on its own gutter, got rows: {rows:?}"
        );
        assert!(
            !rows.iter().any(|r| r.contains('') && r.contains('')),
            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
        );
    }

    // ── the map is built at most once per (revision, wrap) ───────────────────
    //
    // A frontend repaints for reasons that have nothing to do with the text — a
    // blinking caret, a scroll — and rebuilding the map is O(document). These
    // pin *that the cache fires*, which a passing suite can't tell you: a cache
    // that never hits is invisible to every other test in this file.
    //
    // The probe is to wreck the built map and ask for it again. A rebuild
    // repairs it; a cache hit hands the wreckage straight back. Nothing else
    // can distinguish the two from outside.

    #[test]
    fn a_rebuild_with_nothing_changed_reuses_the_map() {
        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
        d.build_visual(80);
        assert!(!d.vmap.rows.is_empty());
        d.vmap.rows.clear(); // wreck it
        d.build_visual(80);
        assert!(
            d.vmap.rows.is_empty(),
            "the map was rebuilt though nothing changed — the cache never fired"
        );
    }

    #[test]
    fn an_edit_rebuilds_the_map() {
        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
        d.build_visual(80);
        let before = d.revision();
        d.vmap.rows.clear();
        d.insert("x");
        d.build_visual(80);
        assert!(d.revision() > before, "an edit must move the revision");
        assert!(
            !d.vmap.rows.is_empty(),
            "an edited document must not paint from a stale map"
        );
    }

    #[test]
    fn a_width_change_rebuilds_the_map() {
        // The map is a function of the wrap width too, so a resize is a miss
        // even though the text is untouched.
        let mut d = doc_in(
            View::Wysiwyg,
            "cache_width",
            "one two three four five six\n",
        );
        d.build_visual(80);
        d.vmap.rows.clear();
        d.build_visual(12);
        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
        // And the unwrapped map is its own key, not the same as any width.
        d.vmap.rows.clear();
        d.build_visual_unwrapped();
        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
    }

    #[test]
    fn a_motion_does_not_rebuild_the_map() {
        // The whole point: moving the caret changes nothing the map is built
        // from. If a motion bumped the revision, every arrow key would cost a
        // full rebuild and the cache would be worthless.
        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
        d.build_visual(80);
        let rev = d.revision();
        d.move_right(false);
        d.move_right(true);
        d.move_down(false);
        assert_eq!(d.revision(), rev, "a motion must not move the revision");
        d.vmap.rows.clear();
        d.build_visual(80);
        assert!(
            d.vmap.rows.is_empty(),
            "a motion should not rebuild the map"
        );
    }

    #[test]
    fn saving_does_not_rebuild_the_map() {
        // Saving changes `dirty`, not the text.
        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
        d.insert("x");
        d.build_visual(80);
        let rev = d.revision();
        d.save();
        assert_eq!(d.revision(), rev, "a save must not move the revision");
        assert!(!d.dirty, "the save should have cleaned the document");
    }

    #[test]
    fn a_reload_rebuilds_the_map() {
        // Reload replaces the text without going through `refresh`, so it has to
        // move the revision itself — else the editor paints the old file.
        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
        d.build_visual(80);
        let rev = d.revision();
        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
        d.reload();
        assert!(d.revision() > rev, "a reload must move the revision");
        d.build_visual(80);
        let text: String = d
            .vmap
            .rows
            .iter()
            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
            .collect();
        assert!(
            text.contains("wholly new"),
            "the reloaded text should be on screen, got {text:?}"
        );
    }

    // ── golden-case harness ──────────────────────────────────────────────────
    // The pattern the whole parity suite can reuse: write a fixture with the
    // caret marked by `|`, run one action, and compare the rendered result —
    // also caret-marked — against the expected string. One readable line per
    // behavior, and it exercises the exact `Doc` ops both frontends call.

    /// Split a `|`-marked fixture into `(source, caret_offset)`.
    fn parse_caret(marked: &str) -> (String, usize) {
        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
        (marked.replacen('|', "", 1), caret)
    }

    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
    /// selection) so a result reads like the fixtures.
    fn render_caret(d: &Doc) -> String {
        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
        // so the caret always renders inside its own selection.
        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
        if let Some((s, e)) = d.selection() {
            marks.push((s, 0, '['));
            marks.push((e, 2, ']'));
        }
        // Insert right-to-left: descending offset, then descending rank.
        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
        let mut out = d.source.clone();
        for (at, _, ch) in marks {
            out.insert(at, ch);
        }
        out
    }

    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
        golden_in(View::Source, name, marked, action)
    }

    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
    /// the same fixture has to read the same way in both.
    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
        let (src, caret) = parse_caret(marked);
        let mut d = doc_in(view, name, &src);
        d.caret = caret;
        action(&mut d);
        render_caret(&d)
    }

    #[test]
    fn word_motion_walks_word_by_word() {
        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
        assert_eq!(
            g("hello wor|ld", |d| d.move_word_left(false)),
            "hello |world"
        );
        assert_eq!(
            g("hello| world", |d| d.move_word_left(false)),
            "|hello world"
        );
        assert_eq!(
            g("hel|lo world", |d| d.move_word_right(false)),
            "hello| world"
        );
        assert_eq!(
            g("hello| world", |d| d.move_word_right(false)),
            "hello world|"
        );
        // Punctuation is its own class, so motion stops at the boundary.
        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
    }

    #[test]
    fn word_motion_extends_the_selection_when_asked() {
        assert_eq!(
            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
            "hello [world|]"
        );
    }

    #[test]
    fn delete_word_removes_a_whole_word() {
        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
    }

    // ── Home / End ───────────────────────────────────────────────────────────

    #[test]
    fn home_toggles_between_the_line_s_text_and_its_margin() {
        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
        // indent to the markup it spells everywhere it means one, so the fixture
        // with whitespace left to walk is a code block, which is verbatim.
        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
        // A line with no indentation has one place to go, so the toggle is a
        // no-op rather than a trip to nowhere.
        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");

        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
        let indent = d.source.find("    indented").unwrap();
        d.caret = indent + 6; // inside "indented"
        d.move_home(false);
        assert_eq!(
            d.caret,
            indent + 4,
            "wysiwyg: Home aims at the code line's text"
        );
        d.move_home(false);
        assert_eq!(
            d.caret, indent,
            "wysiwyg: the second press takes the indent"
        );
        d.move_home(false);
        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
    }

    #[test]
    fn end_takes_the_line_the_view_is_showing() {
        // The line differs by view for the same document, and that is the point:
        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
        // as a space on one row and the source view as two lines.
        let mut d = doc_with("end_src", "one two\nthree\n");
        d.caret = 1;
        d.move_end(false);
        assert_eq!(d.caret, 7, "source: the end of the source line");

        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
        d.caret = 1;
        d.move_end(false);
        assert_eq!(
            d.caret, 13,
            "wysiwyg: the end of the row, soft break and all"
        );
    }

    #[test]
    fn home_and_end_extend_the_selection_when_asked() {
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
            d.caret = 6;
            d.move_end(true);
            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
            d.caret = 6;
            d.move_home(true);
            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
        }
    }

    // ── kill to the line's start / end ───────────────────────────────────────

    #[test]
    fn kill_to_the_line_start_and_end_in_both_views() {
        for (view, tag) in VIEWS {
            // The gap that reads as a paragraph break in each view: the source
            // view's lines are the renderer's rows only where the source says so.
            let gap = if view == View::Source { "\n" } else { "\n\n" };
            let mut d = doc_in(
                view,
                &format!("kill_end_{tag}"),
                &format!("one two{gap}three\n"),
            );
            d.caret = 3;
            d.delete_to_line_end();
            assert_eq!(
                d.source,
                format!("one{gap}three\n"),
                "{tag}: ^K to the line's end"
            );
            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");

            let mut d = doc_in(
                view,
                &format!("kill_start_{tag}"),
                &format!("one two{gap}three\n"),
            );
            d.caret = 7; // the end of the first line
            d.delete_to_line_start();
            assert_eq!(
                d.source,
                format!("{gap}three\n"),
                "{tag}: ⌘⌫ to the line's start"
            );
            assert_eq!(d.caret, 0, "{tag}");
        }
    }

    #[test]
    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
        // The decision: at the boundary both kills do nothing, rather than
        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
        // at a soft wrap as often as at a newline, where there is nothing
        // written to delete — and a source newline is only half of the blank
        // line between two paragraphs, so taking it leaves a soft break rather
        // than the join it looks like. Backspace and Delete are the keys for it.
        for (view, tag) in VIEWS {
            let gap = if view == View::Source { "\n" } else { "\n\n" };
            let src = format!("one{gap}three\n");
            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
            d.caret = 3; // the end of "one"
            d.delete_to_line_end();
            assert_eq!(
                d.source, src,
                "{tag}: ^K at the line's end joined it to the next"
            );

            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
            d.caret = 3 + gap.len(); // the start of "three"
            d.delete_to_line_start();
            assert_eq!(
                d.source, src,
                "{tag}: ⌘⌫ at the line's start joined it to the last"
            );
        }
    }

    #[test]
    fn a_kill_takes_the_selection_when_there_is_one() {
        // What every other delete here does with one, so these two as well.
        for (view, tag) in VIEWS {
            for (name, kill) in [
                (
                    "end",
                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
                ),
                ("start", |d: &mut Doc| d.delete_to_line_start()),
            ] {
                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
                d.anchor = Some(4);
                d.caret = 7; // "two"
                kill(&mut d);
                assert_eq!(
                    d.source, "one  three\n",
                    "{tag}: {name} ignored the selection"
                );
                assert_eq!(d.selection(), None, "{tag}: {name}");
            }
        }
    }

    #[test]
    fn a_kill_takes_the_markup_it_empties_with_it() {
        // The same hazard a word-delete has: a WYSIWYG range covers what the
        // user can see, which for `**bold**` is the word and never the
        // delimiters, so a kill that stopped at the text would leave `a ****` —
        // markup wrapped around nothing.
        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
        d.caret = d.source.find("bold").unwrap();
        d.delete_to_line_end();
        assert_eq!(d.source, "a \n");
    }

    #[test]
    fn a_kill_is_undone_in_one_step() {
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
            d.caret = 3;
            d.delete_to_line_end();
            assert_eq!(d.source, "one\n", "{tag}");
            d.undo();
            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
        }
    }

    #[test]
    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
        // Regression: triple-click used move_home/move_end over visual rows, so
        // it only worked on a paragraph's first row (a wrap-boundary offset maps
        // to the earlier row). select_block_at reads the AST, so every offset in
        // the paragraph selects the whole thing.
        let body = "one two three four five six seven eight\n";
        let mut d = doc_with("sel_block", body);
        d.view = View::Wysiwyg;
        d.build_visual(12); // force the paragraph to wrap into several rows
        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
        let para = (0, "one two three four five six seven eight".len());
        for off in [0usize, 8, 19, 28, 38] {
            d.caret = 0;
            d.anchor = None;
            d.select_block_at(off);
            assert_eq!(
                d.selection(),
                Some(para),
                "offset {off} should select the paragraph"
            );
        }
    }

    #[test]
    fn select_block_uses_content_span_for_a_heading() {
        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
        d.select_block_at(4); // inside "Title"
        // content_span excludes the "# " marker.
        assert_eq!(d.selected_text(), Some("Title"));
        d.select_block_at(10); // inside "body"
        assert_eq!(d.selected_text(), Some("body"));
    }

    #[test]
    fn select_all_spans_the_document() {
        let mut d = doc_with("sel_all", "abc\n\ndef\n");
        d.select_all();
        assert_eq!(d.selection(), Some((0, d.source.len())));
    }

    #[test]
    fn select_word_at_picks_the_surrounding_word() {
        let mut d = doc_with("sel_word", "hello world\n");
        d.select_word_at(8); // inside "world"
        assert_eq!(d.selection(), Some((6, 11)));
        // Double-clicking at end-of-word still grabs the word to its left.
        d.select_word_at(5); // the space between the words
        assert_eq!(d.selection(), Some((5, 6)));
    }

    #[test]
    fn word_helpers_respect_utf8_boundaries() {
        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
        assert_eq!(
            golden("utf8", "|café ok", |d| d.move_word_right(false)),
            "café| ok"
        );
        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
    }

    #[test]
    fn typing_inserts_at_the_caret_and_advances_it() {
        let mut d = doc_with("type", "hello\n");
        d.insert("Hi ");
        assert_eq!(d.source, "Hi hello\n");
        assert_eq!(d.caret, 3);
        assert!(d.dirty);
    }

    #[test]
    fn backspace_deletes_the_char_before_the_caret() {
        let mut d = doc_with("bs", "hello\n");
        d.caret = 3; // after "hel"
        d.backspace();
        assert_eq!(d.source, "helo\n");
        assert_eq!(d.caret, 2);
    }

    #[test]
    fn typing_replaces_the_selection() {
        let mut d = doc_with("replace", "a word b\n");
        d.anchor = Some(2);
        d.caret = 6; // "word" selected
        d.insert("X");
        assert_eq!(d.source, "a X b\n");
        assert_eq!(d.caret, 3);
        assert_eq!(d.anchor, None);
    }

    #[test]
    fn toggle_bold_wraps_then_unwraps_the_selection() {
        let mut d = doc_with("bold", "a word b\n");
        d.anchor = Some(2);
        d.caret = 6;
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "a **word** b\n");
        // The toggled region stays selected, so a second toggle reverses it.
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "a word b\n");
    }

    #[test]
    fn toggle_code_wraps_then_unwraps_the_selection() {
        let mut d = doc_with("code_rt", "a word b\n");
        d.anchor = Some(2);
        d.caret = 6;
        d.toggle(InlineKind::Verbatim);
        assert_eq!(d.source, "a `word` b\n");
        d.toggle(InlineKind::Verbatim);
        assert_eq!(d.source, "a word b\n");
    }

    #[test]
    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
        // ⌘b at a bare caret, then type: the text comes out bold with no
        // selection ever made — the word-processor "start bold here" gesture.
        let mut d = doc_with("sticky_wrap", "xy\n");
        d.caret = 1; // between x and y
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
        d.insert("A");
        assert_eq!(d.source, "x**A**y\n");
    }

    #[test]
    fn sticky_bold_lights_the_toolbar_before_any_typing() {
        // The button must light the instant ⌘b is pressed, or the mode is
        // invisible until the first character lands.
        let mut d = doc_with("sticky_light", "xy\n");
        d.caret = 1;
        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
        d.toggle(InlineKind::Strong);
        assert!(d.active_inline_marks().contains(InlineKind::Strong));
    }

    #[test]
    fn sticky_bold_toggled_off_types_normally_again() {
        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
        // in the flow of typing, the exact sequence the user described.
        let mut d = doc_with("sticky_off", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        d.insert("a");
        d.insert("b"); // continues inside the run, no re-arming
        assert_eq!(d.source, "**ab**\n");
        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
        d.insert("c");
        assert_eq!(d.source, "**ab**c\n");
    }

    #[test]
    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
        // Once a mark is realised the caret sits inside the run, so plain typing
        // extends it rather than starting a second, adjacent bold span.
        let mut d = doc_with("sticky_cont", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Emph);
        d.insert("h");
        d.insert("i");
        assert_eq!(d.source, "*hi*\n");
    }

    #[test]
    fn moving_the_caret_disarms_a_sticky_mark() {
        // Arming a mark and then moving away must not style text elsewhere.
        let mut d = doc_with("sticky_disarm", "xy\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        d.move_right(false); // caret 0 → 1, disarms
        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
        d.insert("A");
        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
    }

    #[test]
    fn stacked_sticky_marks_apply_together() {
        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
        let mut d = doc_with("sticky_stack", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        d.toggle(InlineKind::Emph);
        d.insert("x");
        // Land the caret on the styled character and confirm both marks are live.
        d.anchor = Some(d.source.find('x').unwrap());
        d.caret = d.anchor.unwrap() + 1;
        let marks = d.active_inline_marks();
        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
    }

    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────

    #[test]
    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
        // The space inside the run made `**bold **`, which is *not* bold — four
        // literal asterisks — so the rich view drew them, correctly and
        // uselessly, until the next character happened to close the run again.
        let mut d = wysiwyg_doc("edge_typing", "a \n");
        d.caret = 2;
        d.toggle(InlineKind::Strong);
        for c in "bold".chars() {
            d.insert(&c.to_string());
        }
        assert_eq!(d.source, "a **bold**\n");
        d.insert(" ");
        assert_eq!(
            d.source, "a **bold** \n",
            "the space belongs outside the run"
        );
        assert!(
            d.active_inline_marks().contains(InlineKind::Strong),
            "bold is still what's being typed, so the button stays lit"
        );
        // What the writer is looking at while all this happens: their words.
        d.build_visual(80);
        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
        for c in "hey".chars() {
            d.insert(&c.to_string());
        }
        assert_eq!(
            d.source, "a **bold hey**\n",
            "one bold phrase, not two runs"
        );
    }

    #[test]
    fn typing_past_a_space_can_still_leave_the_bold_behind() {
        // The other half: the marks stay armed across the space, so ⌘b turns
        // them off again there and the next word is plain — the run isn't
        // rejoined by a caret that was told not to.
        let mut d = wysiwyg_doc("edge_shed", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        for c in "bold ".chars() {
            d.insert(&c.to_string());
        }
        assert_eq!(d.source, "**bold** \n");
        d.toggle(InlineKind::Strong);
        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
        d.insert("x");
        assert_eq!(d.source, "**bold** x\n");
    }

    #[test]
    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
        // ⌘b and then a space before any word: the space is not marked (nothing
        // is), and the word after it is.
        let mut d = wysiwyg_doc("edge_space_first", "a\n");
        d.caret = 1;
        d.toggle(InlineKind::Strong);
        d.insert(" ");
        assert_eq!(d.source, "a \n");
        assert!(d.active_inline_marks().contains(InlineKind::Strong));
        d.insert("b");
        assert_eq!(d.source, "a **b**\n");
    }

    #[test]
    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
        d.caret = 8; // the caret's home at the end of the run's text
        d.insert(" ");
        assert_eq!(
            d.source, "x **bold** \n",
            "the space lands past the delimiters"
        );
        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");

        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
        d.caret = 4; // in front of the "b"
        d.insert(" ");
        assert_eq!(d.source, "x  **bold** y\n");
        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
    }

    #[test]
    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
        // Backspace over the last letter of a bold phrase.
        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
        d.caret = 10; // past the "h"
        d.backspace();
        assert_eq!(d.source, "a **bold** \n");
        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
        assert!(d.active_inline_marks().contains(InlineKind::Strong));
        d.insert("x");
        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
    }

    #[test]
    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
        // mark, which is only text. The marks live on in the caret instead.
        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
        d.caret = 5;
        d.backspace();
        assert_eq!(d.source, "a  c\n");
        assert!(d.active_inline_marks().contains(InlineKind::Strong));
        d.insert("x");
        assert_eq!(d.source, "a **x** c\n");
    }

    #[test]
    fn typing_over_a_whole_bold_word_keeps_it_bold() {
        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
        d.anchor = Some(4);
        d.caret = 8; // the word, not its delimiters
        d.insert("x");
        assert_eq!(d.source, "a **x** c\n");
    }

    #[test]
    fn a_code_span_keeps_the_space_it_is_given() {
        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
        // is still verbatim, so nothing is re-spelt. The repair asks the parser
        // rather than a table of kinds, and this is the answer it gets.
        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
        d.caret = 7;
        d.insert(" ");
        assert_eq!(d.source, "a `code ` c\n");
    }

    #[test]
    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
        // A run's closing delimiter has a caret home on each side of it, one
        // column apart on screen — and a plain ← off the space after a bold word
        // lands on the outer one. The character drawn behind the caret there is
        // still the last letter of the phrase, so that is what Backspace takes;
        // the byte behind it is a `*` nobody can see.
        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
        d.caret = 9;
        d.move_left(false);
        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
        d.backspace();
        assert_eq!(
            d.source, "**bol** x\n",
            "a letter of the phrase, not its `*`"
        );
        assert_eq!(d.caret, 5);

        // And the mirror in front of the opening delimiter, where Delete's
        // character is the first letter of the run.
        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
        d.caret = 1;
        d.delete_forward();
        assert_eq!(d.source, "x**old**\n");
        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
    }

    #[test]
    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
        // The byte beside the caret at either edge of a bold word is a `*` the
        // rich view draws nothing for. Taking it is not the character delete the
        // key was pressed for — it unspells the run and puts a literal asterisk
        // on screen (`a *bold** c`). The visible character is the one that goes.
        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
        d.caret = 4; // in front of the "b"
        d.backspace();
        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");

        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
        d.caret = 8; // past the "d"
        d.delete_forward();
        assert_eq!(d.source, "a **bold**c\n");
        assert_eq!(d.caret, 8, "and the caret stays inside the run");
        d.insert("x");
        assert_eq!(d.source, "a **boldx**c\n");

        // A code span's backticks are hidden the same way, so they are covered
        // by the same rule and not by a list of kinds.
        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
        d.caret = 3;
        d.backspace();
        assert_eq!(d.source, "a`code` c\n");
    }

    #[test]
    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
        // The asterisks are on the screen there and the caret can stand between
        // them, so a delete takes exactly the byte it is aimed at.
        let mut d = doc_with("edge_open_src", "a **bold** c\n");
        d.caret = 4;
        d.backspace();
        assert_eq!(d.source, "a *bold** c\n");

        let mut d = doc_with("edge_close_src", "a **bold** c\n");
        d.caret = 8;
        d.delete_forward();
        assert_eq!(d.source, "a **bold* c\n");
    }

    #[test]
    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
        // The space had stepped outside the run (the mark-edge rule), taking the
        // caret with it, so the delete put it back down on the far side of the
        // closing `**` — one place on screen, and the wrong side of it. Typing
        // came out plain and the toolbar went dark, with nothing to see.
        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        for c in "bold".chars() {
            d.insert(&c.to_string());
        }
        d.insert(" ");
        assert_eq!(d.source, "**bold** \n");
        d.backspace();
        assert_eq!(
            d.source, "**bold**\n",
            "the space goes, the delimiters stay"
        );
        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
        assert!(
            d.active_inline_marks().contains(InlineKind::Strong),
            "so the button is still lit"
        );
        d.insert("x");
        assert_eq!(
            d.source, "**boldx**\n",
            "and the next character is still bold"
        );
    }

    #[test]
    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
        // What the stranded caret did next: the byte behind it was the closing
        // `*`, so a second press took that instead of a letter — `**bold*`, the
        // styling gone and an asterisk on the screen where the word had been.
        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
        d.caret = 0;
        d.toggle(InlineKind::Strong);
        for c in "bold ".chars() {
            d.insert(&c.to_string());
        }
        assert_eq!(d.source, "**bold** \n");
        d.backspace();
        d.backspace();
        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
        assert_eq!(d.caret, 5);
    }

    #[test]
    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
        // `***both***` closes two runs with one stack of asterisks: the caret has
        // to walk in through all of them, or it lands between the emph and the
        // strong and types half-marked.
        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
        d.caret = 11;
        d.backspace();
        assert_eq!(d.source, "***both***\n");
        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
        d.insert("x");
        assert_eq!(d.source, "***bothx***\n");
    }

    #[test]
    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
        // The settle only moves a caret a run actually closed over. Ordinary
        // deletes — inside a run, or in plain prose — are untouched.
        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
        d.caret = 8;
        d.backspace();
        assert_eq!(d.source, "a **bol** c\n");
        assert_eq!(d.caret, 7);

        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
        d.caret = 5;
        d.backspace();
        assert_eq!(d.source, "plai\n");
        assert_eq!(d.caret, 4);
    }

    #[test]
    fn the_source_view_leaves_a_delete_where_it_landed() {
        // The delimiters are on the screen there, so the offset past them is a
        // place the caret can be seen to be — nothing to settle.
        let mut d = doc_with("edge_bksp_src", "**bold** \n");
        d.caret = 9;
        d.backspace();
        assert_eq!(d.source, "**bold**\n");
        assert_eq!(d.caret, 8);
    }

    #[test]
    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
        // `***both***` closes two runs with one stack of asterisks; a space that
        // clears only the inner one lands against the outer's and breaks that
        // instead.
        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
        d.caret = 9;
        d.insert(" ");
        assert_eq!(d.source, "a ***both*** \n");
        assert_eq!(d.caret, 13);
        d.insert("x");
        assert_eq!(d.source, "a ***both x***\n");
    }

    #[test]
    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
        // The delimiter shuffle is not an edit the writer made, so it is not a
        // step they have to undo past.
        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
        d.caret = 8;
        d.insert(" ");
        assert_eq!(d.source, "a **bold** \n");
        d.undo();
        assert_eq!(d.source, "a **bold**\n");
    }

    #[test]
    fn the_source_view_types_the_space_where_it_was_asked_to() {
        // The rule is a rich-view courtesy. In the source view the delimiters are
        // on the screen and the user is editing the bytes they can see.
        let mut d = doc_with("edge_src", "a **bold** c\n");
        d.caret = 8;
        d.insert(" ");
        assert_eq!(d.source, "a **bold ** c\n");
    }

    #[test]
    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
        // Double-clicking a word takes the space after it; bolding that must not
        // spell `**word **`, which is not bold at all.
        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
        d.anchor = Some(2);
        d.caret = 7; // "word "
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "a **word** b\n");
        // And a selection of nothing but whitespace has no word to mark.
        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
        d.anchor = Some(6);
        d.caret = 7;
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "a word b\n");
        assert!(d.status.is_some());
    }

    #[test]
    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
        let mut d = doc_with("head_set", "hello\n");
        d.caret = 2; // caret inside the paragraph, no selection
        d.set_block(BlockKind::Heading(1));
        assert_eq!(d.source, "# hello\n");
    }

    #[test]
    fn set_block_heading_works_in_wysiwyg_view() {
        // The app defaults to WYSIWYG; the caret is a source offset either way.
        let mut d = wysiwyg_doc("head_wys", "hello\n");
        d.caret = 2;
        d.set_block(BlockKind::Heading(1));
        assert_eq!(d.source, "# hello\n");
    }

    #[test]
    fn toggle_heading_applies_switches_and_reverts() {
        let mut d = doc_with("head_toggle", "hello\n");
        d.caret = 2;
        d.toggle_heading(1);
        assert_eq!(d.source, "# hello\n"); // paragraph → H1
        d.toggle_heading(2);
        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
        d.toggle_heading(2);
        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
    }

    #[test]
    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
        // the blank line but the caret rendered on the *next* line, because the
        // separator was a non-navigable decoration row. In Preserve flow that
        // blank line is a real caret home — the caret must resolve onto it, and
        // typing there makes the soft break that continues the paragraph.
        let src = "line one:\nsecond line\n";
        let mut d = wysiwyg_doc("pre_enter_lineend", src);
        d.set_line_flow(LineFlow::Preserve);
        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
        d.newline();
        d.build_visual_unwrapped();
        assert_eq!(d.source, "line one:\n\nsecond line\n");
        assert_eq!(
            d.caret, 10,
            "caret sits on the new blank line, not the next line"
        );
        // The blank line is row 1, and the caret resolves onto it — not row 2.
        assert_eq!(
            d.vmap.pos_of_offset(10),
            (1, 0),
            "caret renders on the blank row"
        );
        assert!(
            !d.vmap.rows[1].decoration,
            "the blank line is navigable in Preserve"
        );
        // Typing there makes a soft break: one paragraph, three lines.
        d.insert("new clause,");
        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
    }

    #[test]
    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
        // that keeps it one paragraph — where Fold would open a second paragraph.
        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
        d.set_line_flow(LineFlow::Preserve);
        d.caret = 3;
        d.newline();
        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");

        // End-of-paragraph: Enter then typing continues the same paragraph on a
        // new line (a soft break), not a fresh paragraph.
        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
        d.set_line_flow(LineFlow::Preserve);
        d.caret = 3;
        d.newline();
        d.insert("def");
        assert_eq!(
            d.source, "abc\ndef\n",
            "end-of-line Enter + typing is a soft break"
        );
    }

    #[test]
    fn preserve_double_enter_still_makes_a_paragraph() {
        // Two Enters in a row promote to a real paragraph break: the second lands
        // on the blank line the first opened and takes the empty-line branch.
        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
        d.set_line_flow(LineFlow::Preserve);
        d.caret = 3;
        d.newline();
        d.newline();
        d.insert("def");
        assert_eq!(
            d.source, "abc\n\ndef\n",
            "double Enter is a paragraph break"
        );
    }

    #[test]
    fn preserve_backspace_joins_across_a_soft_break() {
        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
        // soft break it deletes the single newline and joins the two lines.
        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
        d.set_line_flow(LineFlow::Preserve);
        d.build_visual(80);
        d.caret = 4; // start of "def", just past the soft break
        d.backspace();
        assert_eq!(
            d.source, "abcdef\n",
            "Backspace joins across the soft break"
        );
        assert_eq!(d.caret, 3, "caret lands where the lines meet");
    }

    #[test]
    fn fold_enter_still_starts_a_new_paragraph() {
        // The default flow is unchanged: a lone `\n` would render as an invisible
        // space, so Enter keeps opening the paragraph break that actually shows.
        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
        d.caret = 3;
        d.newline();
        assert_eq!(
            d.source, "abc\n\ndef\n",
            "Fold mid-line Enter is a paragraph break"
        );
    }

    #[test]
    fn wysiwyg_one_enter_starts_a_new_paragraph() {
        // Regression: one Enter left the caret between the two newlines, so typing
        // made a soft break (one paragraph) and you needed a second Enter.
        let mut d = wysiwyg_doc("wys_enter", "abc\n");
        d.caret = 3;
        d.newline();
        d.insert("def");
        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
    }

    #[test]
    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
        // Regression: Enter at the caret's natural End-of-line resting place
        // after a bold run with nothing following it (on screen: right after
        // "bold", before the hidden closing "**") spliced the paragraph break
        // at that very byte offset — which sits *before* the closing "**" in
        // the source, since the delimiter is hidden and emits no glyph of its
        // own for `push_row`'s "end of row" fallback to count. That severed the
        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
        // "**" alone on the new line instead of leaving "**bold**" intact with
        // a fresh empty paragraph after it.
        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
        d.move_end(false); // the WYSIWYG End key, from caret 0
        assert_eq!(
            d.caret, 6,
            "caret rests right after \"bold\", before the hidden \"**\""
        );
        d.newline();
        assert!(
            d.source.starts_with("**bold**"),
            "the closing ** must stay attached to \"bold\": got {:?}",
            d.source
        );
        assert_eq!(
            d.source, "**bold**\n\n\n",
            "a fresh empty paragraph follows the still-intact bold run"
        );
    }

    #[test]
    fn source_view_enter_is_a_single_newline() {
        let mut d = doc_with("src_enter", "abc\n");
        d.caret = 3;
        d.newline();
        assert_eq!(d.source, "abc\n\n");
    }

    #[test]
    fn heading_applies_at_the_end_of_a_paragraph() {
        // The caret at a line end sits at the doc level; set_block must still find
        // the block on that line.
        let mut d = doc_with("head_end", "abc\n");
        d.caret = 3; // end of "abc"
        d.toggle_heading(1);
        assert_eq!(d.source, "# abc\n");
    }

    #[test]
    fn heading_on_an_empty_new_paragraph_creates_one() {
        let mut d = wysiwyg_doc("head_empty", "abc\n");
        d.caret = 3;
        d.newline(); // caret now on a fresh, empty paragraph
        d.toggle_heading(1);
        d.insert("Title");
        assert!(d.source.contains("# Title"), "got {:?}", d.source);
    }

    #[test]
    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
        // The reported bug, end to end: click a blank line with another one under
        // it, press H1, type. The text landed in the heading and the caret's
        // offset was right (the source view drew it there), but the rich view
        // drew it two rows lower, on the trailing blank line — the empty `# `
        // heading had left every row below it short by the marker's two bytes,
        // and the blank line ended up claiming the heading's own end offset.
        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
        d.build_visual_unwrapped();
        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
        d.toggle_heading(1);
        for c in "title".chars() {
            d.insert(&c.to_string());
            d.build_visual_unwrapped(); // as a frontend does, one frame per key
        }
        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
        assert_eq!(
            d.caret_pos(),
            (4, 5),
            "the caret draws at the end of the heading"
        );
    }

    #[test]
    fn clicking_an_empty_heading_types_after_its_marker() {
        // The same anchor from the other side: the empty heading's row is its own
        // caret home, so a click on it must land past the hidden `# `. Landing in
        // front of the hashes made the first keystroke un-heading the line.
        let mut d = wysiwyg_doc("head_click", "# \n");
        d.build_visual_unwrapped();
        d.caret = d.vmap.offset_of_pos(0, 0);
        d.insert("x");
        assert_eq!(d.source, "# x\n");
    }

    #[test]
    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
        let mut d = wysiwyg_doc("head_enter", "# Title\n");
        d.caret = 7; // end of the heading
        d.newline();
        d.insert("body");
        assert_eq!(d.source, "# Title\n\nbody\n");
    }

    #[test]
    fn wysiwyg_enter_continues_a_bullet_list() {
        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
        d.caret = 6; // end of "item"
        d.newline();
        d.insert("two");
        assert_eq!(d.source, "- item\n- two\n");
    }

    #[test]
    fn wysiwyg_enter_increments_an_ordered_list() {
        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
        d.caret = 6; // end of "one"
        d.newline();
        d.insert("two");
        assert_eq!(d.source, "1. one\n2. two\n");
    }

    #[test]
    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
        // Regression for the "extra newline" left between a list and the paragraph
        // below it. Enter, Enter leaves the list on a fresh empty paragraph
        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
        // Backspace should then take the caret cleanly back to the end of the list
        // item, `- item\n\nnext`, not delete a single newline and strand it on the
        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
        // no caret can land on. The map is rebuilt between keystrokes exactly as a
        // frontend does, since Backspace reads the stop table to place the delete.
        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
        d.caret = 6; // end of "item"
        d.newline();
        d.build_visual(80);
        d.newline(); // leave the list onto a fresh empty paragraph
        d.build_visual(80);
        assert_eq!(
            d.source, "- item\n\n\n\nnext\n",
            "double-Enter opens the empty paragraph"
        );
        d.backspace();
        assert_eq!(
            d.source, "- item\n\nnext\n",
            "one Backspace collapses the whole gap"
        );
        assert_eq!(
            d.caret, 6,
            "and lands the caret back at the end of the list item"
        );
    }

    #[test]
    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
        // The stop-wise delete must not over-reach when there is no block boundary
        // to cross: two blank lines in a row are one caret stop apart, so pressing
        // Enter on an empty line and then Backspace removes exactly the one newline
        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
        d.caret = 5; // the empty paragraph the first Enter already opened
        d.build_visual(80);
        d.newline();
        d.build_visual(80);
        assert_eq!(
            d.source, "abc\n\n\n\n",
            "Enter on the blank line adds one newline"
        );
        d.backspace();
        assert_eq!(
            d.source, "abc\n\n\n",
            "Backspace takes back exactly that one newline"
        );
    }

    #[test]
    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
        d.caret = 6; // end of the empty "- " item
        d.newline();
        d.insert("p");
        assert_eq!(d.source, "- a\n\np\n");
    }

    #[test]
    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
        // not take the list-exit path (which would splice the `- ` away as if
        // leaving an empty item); the AST guard sends it to a normal break and
        // leaves the underline intact.
        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
        assert!(
            d.nodes().iter().any(|n| n.kind == Kind::Heading),
            "precondition: twig parses this as a heading, not a list",
        );
        d.caret = 7; // on the `- ` underline line
        d.newline();
        assert!(
            d.source.contains("- "),
            "the setext underline survives, not spliced away as a list item: {:?}",
            d.source,
        );
    }

    #[test]
    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
        d.caret = 7; // end of "abc" inside the fence
        d.newline();
        d.insert("def");
        assert_eq!(d.source, "```\nabc\ndef\n```\n");
    }

    #[test]
    fn wysiwyg_enter_continues_a_block_quote() {
        // Enter opens a new *paragraph* inside the quote, not a second line of
        // the same one. `> quote\n> more` is a soft break, which under
        // `LineFlow::Fold` renders as a space — the keystroke would look like it
        // did nothing. The quoted blank line is what makes the break visible, and
        // it's the same thing Enter does in running prose.
        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
        d.caret = 7; // end of "quote"
        d.newline();
        d.insert("more");
        assert_eq!(d.source, "> quote\n>\n> more\n");
        // Still one quote, now holding two paragraphs — not a quote and a stray
        // line that fell out of it.
        let quotes = d
            .nodes()
            .iter()
            .filter(|n| n.kind == Kind::BlockQuote)
            .count();
        assert_eq!(quotes, 1);
    }

    #[test]
    fn set_block_makes_a_heading_at_the_caret() {
        let mut d = doc_with("head", "Title\n\nbody\n");
        d.caret = 0;
        d.set_block(BlockKind::Heading(2));
        assert_eq!(d.source, "## Title\n\nbody\n");
        d.set_block(BlockKind::Paragraph);
        assert_eq!(d.source, "Title\n\nbody\n");
    }

    // ── block containers (quote / list) ──────────────────────────────────────

    #[test]
    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
        // A caret at a line end sits at the doc level; the block is still found.
        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
    }

    #[test]
    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
        // Every source line of the paragraph gets its own `> `, so a caret left
        // on its old byte offset falls one prefix per line above it too far
        // back — inside the markup it just asked for rather than in its word.
        assert_eq!(
            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
            "> aaa\n> b|bb\n> ccc\n"
        );
    }

    #[test]
    fn toggle_blockquote_works_in_wysiwyg_view() {
        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
        assert_eq!(
            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
            "> hel|lo\n"
        );
        assert_eq!(
            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
            "hel|lo\n"
        );
    }

    #[test]
    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
        // The *other* kind converts in place instead of nesting, which is what
        // makes the two buttons one three-state control.
        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
        // Its own kind, over the only item the list holds, takes it off.
        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
    }

    #[test]
    fn toggle_list_works_in_wysiwyg_view() {
        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
        assert_eq!(
            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
            "1. hel|lo\n"
        );
        assert_eq!(
            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
            "- hel|lo\n"
        );
        assert_eq!(
            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
            "hel|lo\n"
        );
    }

    #[test]
    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
        // The selection has to grow with the markup: twig takes a container off
        // only a range covering every block it holds, so the second press can
        // reverse the first only if the result is what's selected.
        let mut d = doc_with("list_sel", "abc\n\ndef\n");
        d.select_all();
        d.toggle_list(true);
        assert_eq!(d.source, "1. abc\n\n2. def\n");
        assert_eq!(d.selection(), Some((0, d.source.len())));
        d.toggle_list(true);
        assert_eq!(d.source, "abc\n\ndef\n");
    }

    #[test]
    fn toggle_blockquote_nests_a_partly_covered_quote() {
        // twig's rule: covering only some of a container's blocks nests, because
        // taking the quote off would drag its uncovered siblings out with it.
        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
        d.caret = 2; // in the first quoted paragraph only
        d.toggle_blockquote();
        assert_eq!(d.source, "> > a\n>\n> b\n");
    }

    #[test]
    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
        // A blank line used to be no block for twig to wrap —
        // `toggle_block_container` answered `NotFound` — so Quote and the list
        // buttons did nothing on the very line the H1 button works on, and leaf
        // lent twig a scratch paragraph to wrap and took it back out again.
        // twig 3.2.0 opens an empty container there itself, so what is left here
        // is where the caret lands: inside the marker that was just written.
        let mut d = doc_with("quote_blank", "\nabc\n");
        d.caret = 0;
        d.toggle_blockquote();
        assert_eq!(d.source, "> \nabc\n");
        assert_eq!(
            d.caret, 2,
            "the caret belongs inside the quote it just opened"
        );
        assert!(d.status.is_none(), "{:?}", d.status);
        assert!(d.dirty);

        // And the paragraph below is still its own block: an empty container one
        // soft break from `abc` would take that paragraph into the quote with it.
        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
        d.caret = 0;
        d.toggle_blockquote();
        d.build_visual(80);
        assert_eq!(drawn_rows(&d), ["", "", "abc"]);

        // The same from the other side: a blank line directly under a paragraph
        // earns the blank line an empty block needs, rather than being read as a
        // soft break inside that paragraph.
        let mut d = doc_with("list_blank_below", "abc\n");
        d.caret = 4;
        d.toggle_list(false);
        assert_eq!(d.source, "abc\n\n- ");
        assert_eq!(d.caret, 7);
    }

    #[test]
    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
        // The gesture the rendering fix is for. `newline` inside a quote already
        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
        // spelling — but the two marker lines it adds belonged to no node until
        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
        // just made drew as plain prose under the quote.
        let mut d = wysiwyg_doc("quote_enter", "> a\n");
        d.caret = 3; // past `a`, at the end of the quoted line
        d.newline();
        assert_eq!(d.source, "> a\n>\n> \n");
        d.build_visual(80);
        assert_eq!(drawn_rows(&d), ["│ a", "", ""]);
        // And the caret is on the new line, not stranded on the old one.
        assert_eq!(d.caret, 8);
    }

    #[test]
    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
        // now it is twig's single edit. Either way one ⌘z has to put the blank
        // line back rather than undoing into a half-built document.
        for open in [
            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
            &|d: &mut Doc| d.toggle_list(false),
            &|d: &mut Doc| d.toggle_list(true),
        ] {
            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
            d.caret = 3;
            open(&mut d);
            assert_ne!(d.source, "a\n\n\n\nb\n");
            d.undo();
            assert_eq!(d.source, "a\n\n\n\nb\n");
        }
    }

    #[test]
    fn a_container_toggle_is_one_undo_step() {
        let mut d = doc_with("quote_undo", "hello\n");
        d.caret = 3;
        d.insert("X"); // a typing run the structural edit must not fold into
        d.toggle_blockquote();
        assert_eq!(d.source, "> helXlo\n");
        d.undo();
        assert_eq!(d.source, "helXlo\n");
    }

    // ── links ────────────────────────────────────────────────────────────────

    #[test]
    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
        let mut d = doc_with("link_sel", "word here\n");
        d.anchor = Some(0);
        d.caret = 4;
        d.insert_link("http://x.dev");
        assert_eq!(d.source, "[word](http://x.dev) here\n");
        // The text, not the destination — so a second press re-points the link
        // the first one made rather than nesting one inside it.
        assert_eq!(d.selected_text(), Some("word"));
        d.insert_link("http://y.dev");
        assert_eq!(d.source, "[word](http://y.dev) here\n");
        assert_eq!(d.selected_text(), Some("word"));
    }

    #[test]
    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
        let mut d = doc_with("img_caret", "before after\n");
        d.caret = 7; // between "before " and "after"
        d.insert_image("cat.png", "a cat");
        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
        // The caret sits just past the inserted image, nothing selected.
        assert_eq!(d.selection(), None);
        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
    }

    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
    /// destination at the first space, so the `format!` this used to be wrote
    /// something that was not an image at all — and the reader saw the markup as
    /// text. twig owns the spelling now, and moves it into the angle form.
    #[test]
    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
        let mut d = doc_with("img_space", "x\n");
        d.caret = 0;
        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
        assert_eq!(
            d.source,
            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
        );
        // And it reads back as an image pointing at the unescaped path — the angle
        // brackets are spelling, not part of the destination.
        d.caret = 2;
        assert_eq!(
            d.image_destination_at_caret(),
            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
        );
    }

    /// A `)` in a caption or a filename must not close the image early.
    #[test]
    fn insert_image_escapes_a_paren_in_either_half() {
        let mut d = doc_with("img_paren", "x\n");
        d.caret = 0;
        d.insert_image("a)b.png", "");
        assert_eq!(d.source, "![](a\\)b.png)x\n");
        d.caret = 2;
        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
    }

    #[test]
    fn insert_image_uses_the_selection_as_alt_text() {
        let mut d = doc_with("img_sel", "caption here\n");
        d.anchor = Some(0);
        d.caret = 7; // "caption"
        d.insert_image("p.png", "ignored fallback");
        assert_eq!(d.source, "![caption](p.png) here\n");
    }

    #[test]
    fn insert_image_with_no_alt_leaves_empty_brackets() {
        let mut d = doc_with("img_noalt", "\n");
        d.caret = 0;
        d.insert_image("logo.svg", "");
        assert_eq!(d.source, "![](logo.svg)\n");
    }

    #[test]
    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
        // The round trip is the point: it's no use writing markup the reader
        // can't pick up again. This is the pair that only holds from twig 2.5.1
        // on — before it, the one-line form went in fine and came back as a
        // paragraph of raw tags, publishing no media at all.
        let mut d = doc_with("vid_rt", "\n");
        d.caret = 0;
        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
        assert_eq!(
            d.source,
            "<video src=\"clip.mp4\" controls>a clip</video>\n"
        );

        d.build_visual(80);
        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
        assert_eq!(d.vmap.media[0].alt, "a clip");
    }

    #[test]
    fn insert_media_spells_audio_with_its_own_tag() {
        let mut d = doc_with("aud_rt", "\n");
        d.caret = 0;
        d.insert_media(MediaKind::Audio, "take.mp3", "");
        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
        d.build_visual(80);
        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
    }

    #[test]
    fn insert_media_uses_the_selection_as_fallback_text() {
        // The same courtesy `insert_image` does with alt: select a caption,
        // insert, and the caption labels the thing rather than being replaced.
        let mut d = doc_with("vid_sel", "the talk here\n");
        d.anchor = Some(0);
        d.caret = 8; // "the talk"
        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
        assert_eq!(
            d.source,
            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
        );
    }

    #[test]
    fn insert_media_with_an_image_kind_is_just_insert_image() {
        let mut d = doc_with("img_via_media", "\n");
        d.caret = 0;
        d.insert_media(MediaKind::Image, "logo.svg", "x");
        assert_eq!(d.source, "![x](logo.svg)\n");
    }

    // ── thematic breaks ─────────────────────────────────────────────────────

    /// The node the source parses as at `caret` — what confirms an inserted
    /// `---` actually reads back as a rule, not stray text or a setext heading.
    ///
    /// The *narrowest* node covering the offset. Every ancestor covers it too,
    /// and since twig 2.8 that includes the `doc` root, which now carries a real
    /// span (it reported none before, so taking the first match used to land on
    /// the block by luck and now always answers `"doc"`).
    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
        d.nodes()
            .into_iter()
            .filter(|n| n.span.start <= caret && caret < n.span.end)
            .min_by_key(|n| n.span.end - n.span.start)
            .map(|n| n.kind)
    }

    #[test]
    fn a_task_box_toggles_at_the_caret_and_reads_back() {
        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
        d.caret = 8; // inside "todo"
        assert_eq!(d.task_checked_at_caret(), Some(false));
        d.toggle_task_checked();
        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
        assert_eq!(d.task_checked_at_caret(), Some(true));
        d.toggle_task_checked();
        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
    }

    #[test]
    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
        // The whole reason `toggle_task_at` exists apart from the caret form:
        // ticking a box elsewhere must not move the cursor out of what's being
        // typed.
        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
        d.caret = 8; // inside "first"
        let second = d.source.find("second").unwrap();
        d.toggle_task_at(second);
        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
        assert_eq!(d.caret, 8, "the caret stayed in the first item");
    }

    #[test]
    fn a_plain_item_gains_and_loses_a_box() {
        let mut d = doc_with("task_mint", "- plain\n");
        d.caret = 4;
        assert_eq!(d.task_checked_at_caret(), None);
        d.toggle_task_item();
        assert_eq!(d.source, "- [ ] plain\n");
        assert_eq!(
            d.task_checked_at_caret(),
            Some(false),
            "a new box arrives unticked"
        );
        d.toggle_task_item();
        assert_eq!(d.source, "- plain\n");
    }

    #[test]
    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
        // `set checked` must not silently convert a bullet into a task — that is
        // `toggle_task_item`'s job, and twig refuses it here.
        let mut d = doc_with("task_none", "- plain\n");
        d.caret = 4;
        d.toggle_task_checked();
        assert_eq!(d.source, "- plain\n", "nothing written");
        assert!(
            d.status.is_some(),
            "the refusal should reach the status line"
        );
    }

    #[test]
    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
        let mut d = doc_with("task_quote", "> - [ ] nested\n");
        d.caret = d.source.find("nested").unwrap();
        assert_eq!(d.task_checked_at_caret(), Some(false));
        d.toggle_task_checked();
        assert_eq!(d.source, "> - [x] nested\n");
    }

    #[test]
    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
        // A rule is a block, so twig's `insert_thematic_break` alone lands it
        // after the whole paragraph. `split_block` parts the paragraph first and
        // the rule is aimed at the *first* half, which is what a rule button is
        // understood to do — and what leaf spelled by hand until twig grew both
        // halves of the gesture.
        let mut d = doc_with("hr_mid", "before after\n");
        d.caret = 7; // between "before " and "after"
        d.insert_thematic_break();
        assert_eq!(d.source, "before \n\n---\n\nafter\n");
        assert_eq!(d.selection(), None);
        assert_eq!(
            kind_at(&mut d, "before \n\n".len()),
            Some(Kind::ThematicBreak)
        );
    }

    #[test]
    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
        // and leaf wrote the first into both until twig started spelling it.
        let mut md = doc_with("hr_md", "para\n");
        md.caret = 2;
        md.insert_thematic_break();
        assert_eq!(md.source, "pa\n\n---\n\nra\n");

        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
        dj.caret = 2;
        dj.insert_thematic_break();
        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
    }

    #[test]
    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
        // The same bytes are two documents. In Markdown `  - b` is a nested item
        // and the next one belongs beside it, at its indent. In Djot a list
        // marker can't interrupt a paragraph, so those bytes are literal text in
        // item `a` and there is only one item — writing `  - ` under it would add
        // no item at all, just more text, and the new sibling has to go to
        // column zero. Both spellings come out of the *enclosing item's* line.
        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
        md.caret = "- a\n  - b".len();
        md.newline();
        assert_eq!(md.source, "- a\n  - b\n  - \n");
        assert_eq!(list_items(&mut md), 3);

        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
        dj.view = View::Wysiwyg;
        dj.build_visual(80);
        dj.caret = "- a\n  - b".len();
        dj.newline();
        assert_eq!(dj.source, "- a\n  - b\n- \n");
        assert_eq!(list_items(&mut dj), 2);

        // Where Djot's nesting is real — opened by a blank line — the indent is
        // reproduced there too, and the two formats agree again.
        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
        dj.view = View::Wysiwyg;
        dj.build_visual(80);
        dj.caret = "- a\n\n  - b".len();
        dj.newline();
        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
        assert_eq!(list_items(&mut dj), 3);
    }

    #[test]
    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
        // Tab replaces the line's whole prefix with the one twig spells, so the
        // quote markers, the parent's indent and an ordered marker's extra
        // column are all its answer rather than leaf's arithmetic.
        for (name, body, caret, want) in [
            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
            // A checkbox is markup the item's own text wraps past, but a nested
            // list may only open at the *list* marker's column — four in from
            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
            // parses as one item, not two.
            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
            (
                "quoted task",
                "> - [ ] a\n> - [ ] b\n",
                18,
                "> - [ ] a\n>   - [ ] b\n",
            ),
        ] {
            let mut doc = wysiwyg_doc(name, body);
            doc.caret = caret;
            doc.indent();
            assert_eq!(doc.source, want, "{name}");
            // The nesting is real, not just indented text.
            assert_eq!(list_items(&mut doc), 2, "{name}");
        }
    }

    #[test]
    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
        // The same bytes, the two formats disagreeing, and a gesture that used
        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
        // so those bytes are literal text inside item `a` — there is nothing to
        // outdent, and treating them as a marker turned one item into two, a
        // structural edit from a keystroke that should delete one character.
        //
        // twig's `line_prefix` is what tells them apart: it reports the marker
        // on the Markdown line and nothing on the Djot one, which is a
        // continuation. No byte scan can reach that answer.
        let src = "- a\n  - b\n";
        let at = "- a\n  - ".len();

        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
        md.view = View::Wysiwyg;
        md.build_visual(80);
        md.caret = at;
        md.backspace();
        assert_eq!(md.source, "- a\n- b\n");
        assert_eq!(list_items(&mut md), 2);

        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
        dj.view = View::Wysiwyg;
        dj.build_visual(80);
        dj.caret = at;
        dj.backspace();
        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
    }

    #[test]
    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
        // Leaf used to spell the next item from the marker bytes it scanned, and
        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
        // and dropped out of the checklist. twig reproduces the whole
        // continuation, and a fresh item is always unticked however the one above
        // it stands.
        for (name, body, want) in [
            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
        ] {
            let mut doc = wysiwyg_doc(name, body);
            doc.caret = body.trim_end_matches('\n').len();
            doc.newline();
            assert_eq!(doc.source, want, "{name}");
            // Both items are checklist items — the new one is a box, not the
            // plain bullet the old marker scan left behind — and it is unticked
            // whichever way the one above it faces.
            let boxes: Vec<Option<bool>> = doc
                .nodes()
                .iter()
                .filter(|n| n.kind == Kind::TaskListItem)
                .map(|n| n.checked)
                .collect();
            assert_eq!(boxes.len(), 2, "{name}");
            assert_eq!(boxes[1], Some(false), "{name}");
        }
    }

    #[test]
    fn a_split_takes_the_space_the_caret_was_in_front_of() {
        // Splicing a break at the caret strands the space the words were parted
        // at on the head of the second block, where it reads as an indent nobody
        // typed. twig's split consumes it.
        for (name, body, caret, want) in [
            ("para", "one two\n", 3, "one\n\ntwo\n"),
            ("item", "- one two\n", 5, "- one\n- two\n"),
            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
            // A heading takes leaf's own path, which has to match.
            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
        ] {
            let mut doc = wysiwyg_doc(name, body);
            doc.caret = caret;
            doc.newline();
            assert_eq!(doc.source, want, "{name}");
        }
    }

    #[test]
    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
        // The one place leaf keeps its own break: `split_block` repeats the `#`,
        // and Enter after a title is how the body under it is asked for.
        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
        doc.caret = "# Title".len();
        doc.newline();
        doc.insert("body");
        assert_eq!(doc.source, "# Title\n\nbody\n");
        assert_eq!(
            doc.nodes()
                .iter()
                .filter(|n| n.kind == Kind::Heading)
                .count(),
            1
        );
    }

    #[test]
    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
        // A quoted item's marker doesn't open its line, so a scan that starts at
        // column zero finds a `>` where it wanted a bullet, calls the line "not a
        // list" and hands Enter to the plain-quote branch — which writes `> ` and
        // drops the list. The next item has to carry the whole prefix.
        for (name, body, want) in [
            ("flat", "> - a\n", "> - a\n> - \n"),
            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
        ] {
            let mut doc = wysiwyg_doc(name, body);
            doc.caret = body.trim_end_matches('\n').len();
            doc.newline();
            assert_eq!(doc.source, want, "{name}");
            // The marker isn't just spelled right, it parses as an item.
            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
        }
    }

    #[test]
    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
        // Double-Enter exits the list. Unquoted that means a blank line, but a
        // *bare* blank line would end the quote too and drop the caret out of it,
        // so the separator keeps its `>` and the caret's line keeps its `> `.
        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
        doc.caret = "> - a\n> - ".len();
        doc.newline();
        assert_eq!(doc.source, "> - a\n>\n> \n");
        assert_eq!(list_items(&mut doc), 1);
        // What "still in the quote" means for the next keystroke: the caret sits
        // behind the prefix, and what's typed there lands inside the quote as a
        // paragraph of its own — not as more of item `a`.
        doc.insert("x");
        assert_eq!(doc.source, "> - a\n>\n> x\n");
        assert!(
            doc.editor
                .ancestors_at(doc.caret - 1)
                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
        );
    }

    #[test]
    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
        // The marker is hidden block markup, so Backspace over it is structural —
        // but only the marker is the list's. Splicing from the line start would
        // take the `>` with it and silently unquote the line.
        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
        doc.caret = "> - ".len();
        doc.backspace();
        assert_eq!(doc.source, "> a\n");
        assert_eq!(list_items(&mut doc), 0);

        // A nested one outdents instead, moving the bullet within the quote
        // rather than moving the quote.
        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
        doc.caret = "> - a\n>   - ".len();
        doc.backspace();
        assert_eq!(doc.source, "> - a\n> - b\n");
        assert_eq!(list_items(&mut doc), 2);
    }

    #[test]
    fn only_a_bare_paragraph_is_parted_around_the_caret() {
        // The split is deliberately narrow. Parting a fenced block would leave
        // two fences with a rule between them, and parting a list item would
        // mint an item nobody asked for on the way to a rule that lands after
        // the list either way — so both keep the whole block intact and take the
        // rule after it. A caret in a quote is likewise left alone.
        for (name, body, caret, want) in [
            (
                "code",
                "```\nfn x() {}\n```\n",
                8,
                "```\nfn x() {}\n```\n\n---\n",
            ),
            ("list", "- one two\n", 6, "- one two\n\n---\n"),
            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n"),
        ] {
            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
            d.caret = caret;
            d.insert_thematic_break();
            assert_eq!(d.source, want, "{name}: the block should stay whole");
        }
    }

    #[test]
    fn insert_thematic_break_replaces_the_selection() {
        // Now that the rule lands *at* the caret again, replacing the selection
        // is coherent once more: the text goes, and the rule takes its place.
        // The space the deletion left leading the second half is consumed by the
        // split rather than opening the new paragraph with it.
        let mut d = doc_with("hr_sel", "one two three\n");
        d.anchor = Some(4);
        d.caret = 7; // "two"
        d.insert_thematic_break();
        assert_eq!(d.source, "one \n\n---\n\nthree\n");
        assert_eq!(d.selection(), None);
    }

    #[test]
    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
        // because writing `---` into one is code, not a rule — twig now walks out
        // to the block that owns the caret's line, so there is nothing to refuse.
        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
        code.caret = 5; // inside the fenced code
        code.insert_thematic_break();
        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n");
        assert_eq!(code.status, None, "no refusal to report any more");

        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
        table.caret = 3; // in the header row
        table.insert_thematic_break();
        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n");
    }

    #[test]
    fn insert_thematic_break_in_a_list_item_ends_the_list() {
        // The un-indented rule cannot continue the list, so it closes the list
        // and lands at the top level rather than nested inside it.
        let mut d = doc_with("hr_list", "- one\n- two\n");
        d.caret = "- one\n- tw".len(); // mid "two"
        d.insert_thematic_break();
        d.build_visual(80);
        let rule_at = d.source.find("---").unwrap();
        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
        assert!(
            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
                && n.span.start <= rule_at
                && rule_at < n.span.end),
            "the rule must not be nested inside the list"
        );
    }

    #[test]
    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
        // which is the document the gesture was actually asked for.
        let mut d = doc_with("hr_quote", "> hello\n");
        d.caret = 4; // inside the quoted text
        d.insert_thematic_break();
        assert_eq!(d.source, "> hello\n>\n> ---\n");
        d.build_visual(80);
        let rule_at = d.source.find("---").unwrap();
        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
        assert!(
            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
                && n.span.start <= rule_at
                && rule_at < n.span.end),
            "the rule belongs to the quote it was asked for"
        );
    }

    // ── typing against a block picture ────────────────────────────────────────

    /// A rendered-view document with the caret parked on one of the picture's two
    /// stops, and the map already built — the state a frontend is in between
    /// drawing a frame and the next keystroke.
    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
        let mut d = doc_in(View::Wysiwyg, name, src);
        d.build_visual_unwrapped();
        let start = src.find("![").unwrap();
        d.caret = match side {
            MediaStop::Before => start,
            MediaStop::After => start + "![](p.png)".len(),
        };
        d
    }

    /// The block media the map publishes, after rebuilding it — "is this still a
    /// picture, or has it become a line of text with an image in it?"
    fn media_count(d: &mut Doc) -> usize {
        d.build_visual_unwrapped();
        d.vmap.media.len()
    }

    #[test]
    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
        // The accident this prevents: tap the blank page under a photo (which
        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
        // paragraph with an *inline* image — the photo stops being drawn.
        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
        d.insert("xy");
        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
        assert_eq!(media_count(&mut d), 1, "still a picture");
    }

    #[test]
    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
        d.insert("xy");
        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
        assert_eq!(media_count(&mut d), 1);
    }

    #[test]
    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
        d.insert("x");
        assert_eq!(d.source, "x\n\n![](p.png)\n");
        assert_eq!(media_count(&mut d), 1);
    }

    #[test]
    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
        // The opened paragraph is part of the keystroke, not an edit the writer
        // made — so it undoes with the character, not a step later.
        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
        d.insert("x");
        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
        d.undo();
        assert_eq!(d.source, "hi\n\n![](p.png)\n");
    }

    #[test]
    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
        // ⌘V dissolves the picture exactly as a keystroke does.
        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
        d.paste("pasted");
        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
        assert_eq!(media_count(&mut d), 1);
    }

    #[test]
    fn typing_beside_an_inline_image_is_ordinary_editing() {
        // An inline image has no placeholder row and no stops of its own. Opening
        // a paragraph mid-sentence would be the bug, not the fix.
        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
        d.build_visual_unwrapped();
        d.caret = "see ![](p.png)".len();
        d.insert("!");
        assert_eq!(d.source, "see ![](p.png)! here\n");
    }

    #[test]
    fn source_view_types_raw_markup_against_an_image_untouched() {
        // Source view is for writing the markup itself; a break inserted behind
        // the writer's back there would be the editor arguing with them.
        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
        d.caret = "![](p.png)".len();
        d.insert("x");
        assert_eq!(d.source, "![](p.png)x\n");
    }

    #[test]
    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
        // A selection is replaced, not joined into, so there is nothing to
        // protect: the range takes the picture with it.
        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
        d.anchor = Some(d.caret);
        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
        d.insert("x");
        assert_eq!(d.source, "hi\n\nx\n");
    }

    #[test]
    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
        // What this actually cost: a real vault's photo, to one stray Backspace.
        // The caret past `![](p.png)` was deleting the closing paren — invisible
        // in the rendered view — and the photo became the text `![](p.png`.
        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
        d.backspace();
        assert_eq!(d.source, "hi\n");
        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
        d.undo();
        assert_eq!(
            d.source, "hi\n\n![](p.png)\n",
            "and comes back in one piece"
        );
    }

    #[test]
    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
        // Deleting the break here would join the picture to the paragraph above,
        // where it is an *inline* image and stops being drawn. Step over the
        // boundary; the next press deletes in the paragraph the caret reached.
        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
        d.backspace();
        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
        d.backspace();
        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
    }

    #[test]
    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
        // The mirror. A byte-step here eats the `!` and leaves a link.
        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
        d.delete_forward();
        assert_eq!(d.source, "hi\n\nbye\n");
        assert_eq!(media_count(&mut d), 0);
    }

    #[test]
    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
        let mut d = doc_at_picture(
            "pic_del_after",
            "hi\n\n![](p.png)\n\nbye\n",
            MediaStop::After,
        );
        d.delete_forward();
        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
        assert_eq!(
            d.caret,
            d.source.find("bye").unwrap(),
            "the caret stepped down to `bye`"
        );
    }

    #[test]
    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
        d.backspace();
        assert_eq!(d.source, "\n");
        assert_eq!(media_count(&mut d), 0);
    }

    #[test]
    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
        d.delete_word_back();
        assert_eq!(d.source, "hi there\n");

        // And in front of one it runs *through* the paragraph break into the
        // prose above, which merges the picture inline — so it steps out first,
        // and the second press deletes the word it was aimed at.
        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
        d.delete_word_back();
        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
        d.delete_word_back();
        assert_eq!(
            d.source, "hi \n\n![](p.png)\n",
            "the word above went, the picture stayed"
        );
        assert_eq!(media_count(&mut d), 1);
    }

    #[test]
    fn source_view_deletes_raw_markup_against_an_image_untouched() {
        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
        d.caret = "![](p.png)".len();
        d.backspace();
        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
    }

    #[test]
    fn image_destination_at_caret_reads_the_image_under_the_caret() {
        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
        d.caret = 3; // inside the image markup
        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
        // Past the image, the caret is in no image.
        d.caret = "![a cat](cat.png)".len();
        assert_eq!(d.image_destination_at_caret(), None);
    }

    #[test]
    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
        // The image is one placeholder row by default, and `set_media_rows` grows
        // it to the height the frontend measured: the label row plus blank
        // `decoration` fillers that hold the vertical space a raster is drawn into.
        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
        assert_eq!(d.vmap.media.len(), 1);
        let img_row = d.vmap.media[0].rows_span.start;
        assert_eq!(
            d.vmap.media[0].rows_span,
            img_row..img_row + 1,
            "default is one row"
        );

        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
        d.build_visual(80);
        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
        let span = d.vmap.media[0].rows_span.clone();
        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
        // The label row carries the mark and its glyphs; the three below are blank
        // decoration — drawn, but no caret and no text.
        assert!(
            d.vmap.rows[span.start].media.is_some(),
            "mark rides the first row"
        );
        for r in (span.start + 1)..span.end {
            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
            assert!(
                d.vmap.rows[r].media.is_none(),
                "only the first row is marked"
            );
        }
    }

    #[test]
    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
        // The extra rows are pure spacers: the caret's only homes stay the stop in
        // front of the image and the one just past it, so walking the document top
        // to bottom visits the same offsets whether the image is 1 row or 5.
        let body = "ab\n\n![x](p.png)\n\ncd\n";
        let stops_at = |rows: usize| -> Vec<usize> {
            let mut d = wysiwyg_doc("img_stops", body);
            if rows > 1 {
                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
                d.build_visual(80);
            }
            d.caret = 0;
            let mut seen = vec![d.caret];
            loop {
                d.move_right(false);
                if *seen.last().unwrap() == d.caret {
                    break;
                }
                seen.push(d.caret);
            }
            seen
        };
        assert_eq!(
            stops_at(1),
            stops_at(5),
            "reserving rows must not add stops"
        );
    }

    #[test]
    fn insert_link_repoints_the_link_at_a_bare_caret() {
        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
        d.caret = 3; // in the link's text, nothing selected
        d.insert_link("http://y.dev");
        assert_eq!(d.source, "[word](http://y.dev)\n");
        assert_eq!(d.selected_text(), Some("word"));
    }

    #[test]
    fn insert_link_on_an_empty_range_autolinks_a_url() {
        // A link with no text of its own is an autolink, and twig spells it —
        // `<…>` is the canonical form and needs no text typed into it, so the
        // caret lands after it rather than selecting a finished link.
        let mut d = doc_with("link_empty", "\n");
        d.caret = 0;
        d.insert_link("http://x.dev");
        assert_eq!(d.source, "<http://x.dev>\n");
        assert_eq!(d.selection(), None);
        assert_eq!(d.caret, 14);
    }

    #[test]
    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
        // in Markdown, so a destination that can't autolink doubles as the text
        // instead — which is then selected, ready to be typed over.
        let mut d = doc_with("link_rel", "\n");
        d.caret = 0;
        d.insert_link("./notes.md");
        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
        assert_eq!(d.selection(), Some((1, 11)));
        d.insert("Notes");
        assert_eq!(d.source, "[Notes](./notes.md)\n");
    }

    #[test]
    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
        // The autolink's text is its URL, so re-pointing replaces the whole
        // node — the caret must not splice a second link inside the first.
        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
        d.caret = 10;
        d.insert_link("https://y.dev");
        assert_eq!(d.source, "see <https://y.dev> ok\n");
    }

    #[test]
    fn code_language_reads_and_edits_through_the_fence() {
        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
        d.caret = 10; // inside the code body
        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
        assert!(d.caret_in_fenced_code());

        d.set_code_language("python");
        assert!(
            d.source.starts_with("```python\n"),
            "source: {:?}",
            d.source
        );
        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));

        // Clearing it leaves a bare fence and no label.
        d.set_code_language("");
        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
        assert_eq!(d.code_language_at_caret(), None);

        // A caret outside any code block edits nothing.
        let mut p = doc_with("code_lang_none", "just prose\n");
        assert!(!p.caret_in_fenced_code());
        p.set_code_language("rust");
        assert_eq!(p.source, "just prose\n");
    }

    #[test]
    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
        // Markdown's info string ends at whitespace, so `two words` would write
        // a fence that reads back with a different language than the one asked
        // for. twig refuses it; leaf reports that and leaves the source alone.
        // The old splice trimmed the ends and wrote whatever was left.
        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
        d.caret = 10;
        d.set_code_language("two words");
        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
        assert!(d.status.is_some(), "the refusal should be reported");
        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
    }

    #[test]
    fn link_destination_at_caret_reads_both_spellings() {
        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
        d.caret = 5;
        assert_eq!(
            d.link_destination_at_caret().as_deref(),
            Some("https://x.dev")
        );
        d.caret = 0;
        assert_eq!(d.link_destination_at_caret(), None);

        // An autolink has no `destination`; its text is the URL.
        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
        a.caret = 10;
        assert_eq!(
            a.link_destination_at_caret().as_deref(),
            Some("https://x.dev")
        );
        a.caret = 21;
        assert_eq!(a.link_destination_at_caret(), None);
    }

    #[test]
    fn locate_finds_the_block_a_declared_id_names() {
        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
        // verse. The locator has to land on the *verse*, which is the whole
        // reason a link carries one.
        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
                   {#v2}\nYea, I make a record in the language of my father.\n";
        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
        assert_eq!(
            d.source[v2.start..v2.end].trim_end(),
            "Yea, I make a record in the language of my father."
        );
        // The attribute line is not part of it: `start` is a place to put a
        // caret, and `{#v2}` is markup the caret has no business landing in.
        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
        assert_eq!(d.locate("v99"), None);
    }

    #[test]
    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
        // Markdown heading is literal text. So `#the-second-part` can only be
        // the heading's own words, which is the rule every Markdown renderer
        // already follows and therefore the one a link was authored against.
        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
        let mut d = doc_with("locate_md", src);
        let hit = d.locate("the-second-part").expect("the heading's slug");
        assert!(d.source[hit.start..].starts_with("## The Second Part"));
        // Bounded by the next heading that isn't under it, so a peek shows the
        // section rather than only its title.
        assert_eq!(
            &d.source[hit.start..hit.end],
            "## The Second Part\n\nbody\n\n"
        );

        // A subsection does not end its parent: `# Title` runs to `## Third`'s
        // sibling only because there is no other `#`, so it covers the lot.
        let title = d.locate("title").expect("the top heading");
        assert_eq!(title.end, d.source.len());
    }

    #[test]
    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
        // djot mints `Some-Heading-Here`; a link to it is written
        // `#some-heading-here` by nearly everything that writes links. Both
        // spellings are one question.
        let src = "## Some Heading Here\n\nbody\n";
        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
        let slugged = d.locate("some-heading-here").expect("the link's spelling");
        assert_eq!(exact, slugged);
        // The section, not the heading line — there is more to show than a title.
        assert_eq!(&d.source[exact.start..exact.end], src);
    }

    #[test]
    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
        assert_eq!(d.locate(""), None);
        assert_eq!(d.locate("   "), None);
        // All punctuation: it names nothing, and must not be read as "match the
        // first heading whose slug is also empty".
        assert_eq!(d.locate("!!!"), None);
    }

    #[test]
    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
        // The document's mistake, and the answer every other anchor
        // implementation gives — the alternative is for a link to mean whichever
        // of the two a walk happened to reach first.
        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
        let hit = d.locate("dup").expect("the first `{#dup}`");
        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
    }

    #[test]
    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
        // The button's whole job: a reference where the caret was, a definition
        // to give it meaning, and the caret waiting in the empty note so the
        // next keystroke is the note's first word.
        let mut d = doc_with("fn_insert", "A claim and more.\n");
        d.caret = 7; // just past "A claim"
        d.insert_footnote();
        assert!(
            d.source.starts_with("A claim[^1] and more."),
            "{:?}",
            d.source
        );
        assert!(
            d.source.contains("[^1]:"),
            "the definition too: {:?}",
            d.source
        );
        assert_eq!(d.status, None);

        let reference = d.source.find("[^1]").unwrap();
        let note = d
            .footnote_at(reference + 2)
            .expect("the reference just written");
        assert_eq!(note.label, "1");
        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
        // …and typing there is typing into the note, not near it.
        d.insert("the note");
        assert_eq!(
            d.footnote_at(reference + 2).and_then(|f| f.text),
            Some("the note".to_string())
        );
    }

    #[test]
    fn insert_footnote_numbers_past_the_notes_already_written() {
        // A second press must not hand back a label somebody else is using: twig
        // reuses a defined label rather than appending a rival definition, so a
        // repeat of `1` would quietly point the new reference at the old note.
        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
        d.caret = 7; // past `[^1]`, before " two."
        d.insert_footnote();
        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
        assert_eq!(d.source.matches("[^2]:").count(), 1);
    }

    #[test]
    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
        // `[^2]` with no definition is still a 2 that means something to whoever
        // wrote it — stepping over it would mint a note for their reference. A
        // word label takes no number, so it blocks none.
        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
        d.caret = d.source.find(" c").unwrap();
        d.insert_footnote();
        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
        assert!(
            d.source.starts_with("a[^2] b[^why][^1] c"),
            "{:?}",
            d.source
        );
    }

    #[test]
    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
        // A reference annotates the words before it. Consuming the selection —
        // which is what an insert normally does — would delete the very claim
        // the author selected in order to footnote.
        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
        d.anchor = Some(2);
        d.caret = 7; // "claim" selected
        d.insert_footnote();
        assert!(
            d.source.starts_with("A claim[^1] and more."),
            "{:?}",
            d.source
        );
    }

    #[test]
    fn a_note_just_written_still_knows_where_its_reference_is() {
        // The authoring loop in one test: press the button, type the note, ask to
        // go back. The caret ends at the note's last byte — which is the *end* of
        // the definition's span, the one offset the query used to exclude — so
        // this is where the round trip either works or doesn't.
        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
        d.caret = 7;
        d.insert_footnote();
        d.insert("the note");
        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
        let back = d
            .footnote_definition_at_caret()
            .expect("still in the note we just typed");
        assert_eq!(back.label, "1");
        // …and following it lands on the reference's label, where a reader's
        // return leg lands.
        assert_eq!(back.offset, Some(9));
        assert_eq!(&d.source[9..10], "1");
    }

    #[test]
    fn insert_footnote_takes_one_undo_for_both_halves() {
        // twig writes the pair as a single edit; the point of that is here.
        let before = "A claim and more.\n";
        let mut d = doc_with("fn_insert_undo", before);
        d.caret = 7;
        d.insert_footnote();
        assert_ne!(d.source, before);
        d.undo();
        assert_eq!(d.source, before, "one undo takes back both halves");
    }

    #[test]
    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
        // HTML is authorable — it spells the inline marks — and has no footnote.
        // The refusal says so rather than writing brackets that would render as
        // brackets.
        let src = "<p>A claim.</p>\n";
        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
        assert!(!Capabilities::of(Format::Html).footnote);
        d.caret = 5;
        d.insert_footnote();
        assert_eq!(d.source, src, "nothing written");
        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
    }

    #[test]
    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
        // The empty body is the one place this could go wrong: the definition
        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
        // byte early would draw up in the paragraph above the note it belongs to.
        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
        d.place_caret(7, false);
        d.insert_footnote();
        d.build_visual(80); // the frame a frontend draws after the edit
        assert_eq!(
            d.vmap.snap_to_stop(d.caret),
            d.caret,
            "the caret sits on a stop"
        );
        let (row, _) = d.caret_pos();
        assert!(
            drawn_rows(&d)[row].contains("[1]"),
            "the caret is on the note's row, not above it: {:?}",
            drawn_rows(&d)
        );
    }

    #[test]
    fn footnote_at_caret_resolves_a_reference_to_its_note() {
        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
        // blank line, as one has to.
        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
        d.caret = 9;
        let f = d
            .footnote_at_caret()
            .expect("the caret stands in a reference");
        assert_eq!(f.label, "1");
        assert_eq!(f.text.as_deref(), Some("the note"));
        // The offset points at the note's first word, not at the definition's
        // `[` — the marker is decoration with no caret stop on it.
        assert_eq!(f.offset, Some(29));
        assert_eq!(&d.source[29..37], "the note");
        // …and `end` closes the range, so a frontend can ask which rendered rows
        // the note occupies rather than re-deriving them from the text.
        assert_eq!(f.end, Some(37));
        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
    }

    /// Two definitions in a row: each is its own note, and neither reaches into
    /// the other.
    ///
    /// A djot definition's span used to run past the blank line into the first
    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
    /// offsets named the *next* note's rows too, showing a reader two footnotes
    /// when they had asked about one. twig 3.1 ends the span after the block's
    /// own last line; the test outlives the workaround leaf carried for it.
    #[test]
    fn footnote_at_stops_a_note_at_the_definition_after_it() {
        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
        for format in [Format::Markdown, Format::Djot] {
            let mut d = Doc::from_source(src.to_string(), format).unwrap();
            d.caret = 7;
            let f = d.footnote_at_caret().expect("a reference");
            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
            assert_eq!(
                &src[f.offset.unwrap()..f.end.unwrap()],
                "first note.",
                "in {format:?}"
            );
        }
    }

    /// The other side of that boundary: a blank line *inside* a definition is
    /// interior to it, and the note keeps its second paragraph.
    ///
    /// This is what the old body scan cost. It stopped at the first line not
    /// indented under the note — a blank line is not — so a two-paragraph note
    /// came back as its first paragraph, and "go to note" framed half of it.
    /// Reading the span twig gives is both simpler and right.
    #[test]
    fn footnote_at_keeps_a_notes_second_paragraph() {
        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
        d.caret = 7;
        let f = d.footnote_at_caret().expect("a reference");
        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
        // And it stops there — `After.` is the next block, not more note.
        assert_eq!(
            &src[f.offset.unwrap()..f.end.unwrap()],
            f.text.as_deref().unwrap()
        );
        assert!(!f.text.as_deref().unwrap().contains("After"));
    }

    #[test]
    fn footnote_at_bounds_a_note_whose_body_is_empty() {
        // `[^1]:` with nothing after it. The range is empty rather than
        // inverted, and still points inside the definition — which is what keeps
        // a frontend's row lookup from walking off into the block above.
        let src = "A claim[^1].\n\n[^1]:\n";
        let mut d = doc_with("fn_empty_body", src);
        d.caret = 9;
        let f = d.footnote_at_caret().expect("a reference");
        assert_eq!(f.text.as_deref(), Some(""));
        assert_eq!(f.offset, f.end, "an empty note is an empty range");
        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
    }

    #[test]
    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
        let mut d = doc_with(
            "fn_at_caret_none",
            "A claim[^1] and more.\n\n[^1]: the note\n",
        );
        d.caret = 2; // in the prose
        assert_eq!(d.footnote_at_caret(), None);
    }

    #[test]
    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
        // The two are deliberately separate: a reference names a note in this
        // document, a link names somewhere to leave for, and answering one with
        // the other is what made a reference click do nothing at all.
        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
        d.caret = 3; // the `1` of `[^1]`
        assert!(d.footnote_at_caret().is_some());
        assert_eq!(
            d.link_destination_at_caret(),
            None,
            "a reference is not a link"
        );

        d.caret = 10; // inside the link's label
        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
        assert_eq!(
            d.link_destination_at_caret().as_deref(),
            Some("https://x.dev")
        );
    }

    #[test]
    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
        // A `[^99]` the document never defines is a real state — a note deleted
        // out from under its reference — and the label is what lets a frontend
        // say so. `None` here would be indistinguishable from "not on a
        // reference", which is the wrong thing to tell a reader.
        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
        d.caret = 9;
        let f = d
            .footnote_at_caret()
            .expect("the reference is still a reference");
        assert_eq!(f.label, "99");
        assert_eq!(f.text, None);
        assert_eq!(f.offset, None);
    }

    #[test]
    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
        // Labels are not always numbers, and a note's body runs past its first
        // line — the indented continuation belongs to the note, so it comes back
        // with it (source bytes, verbatim, as documented).
        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
        let mut d = doc_with("fn_word_label", src);
        d.caret = 6;
        let f = d
            .footnote_at_caret()
            .expect("the caret stands in a reference");
        assert_eq!(f.label, "note");
        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
    }

    #[test]
    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
        // The point of the offset form: a pointer hovering a reference asks what
        // note it names, and must not drag the caret along to ask.
        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
        d.caret = 0;
        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
        assert_eq!(f.label, "1");
        assert_eq!(f.text.as_deref(), Some("the note"));
        assert_eq!(d.caret, 0, "asking must not move the caret");
        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
    }

    #[test]
    fn footnote_definition_at_caret_points_back_at_the_reference() {
        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
        // the caret can rest on — is at 9.
        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
        d.caret = 30; // inside the note's body
        let f = d
            .footnote_definition_at_caret()
            .expect("the caret stands in a definition");
        assert_eq!(f.label, "1");
        assert_eq!(f.offset, Some(9));
        assert_eq!(&d.source[7..11], "[^1]");
    }

    #[test]
    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
        // The two legs have to meet: wherever `footnote_at` sends the caret, the
        // definition query must answer for — otherwise arriving at a note leaves
        // the reader somewhere the way back isn't offered.
        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
        let mut d = doc_with("fn_def_marker", src);
        let landed = d.footnote_at(9).unwrap().offset.unwrap();
        assert_eq!(
            d.footnote_definition_at(landed).and_then(|f| f.offset),
            Some(9),
            "the note a reference sends you to offers the way back"
        );
    }

    #[test]
    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
        // The two queries answer for disjoint places, which is what lets one
        // gesture mean "down to the note" in one and "back up" in the other
        // without either having to remember which way the reader is going.
        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
        d.caret = 2; // prose
        assert_eq!(d.footnote_definition_at_caret(), None);
        d.caret = 9; // the reference
        assert_eq!(d.footnote_definition_at_caret(), None);
        assert!(
            d.footnote_at_caret().is_some(),
            "which is the reference's own query"
        );
    }

    #[test]
    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
        // note", which is false and leaves a frontend unable to explain why the
        // way back is missing.
        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
        let mut d = doc_with("fn_def_orphan", src);
        d.caret = src.find("orphan").unwrap();
        let f = d
            .footnote_definition_at_caret()
            .expect("an orphan is still a definition");
        assert_eq!(f.label, "2");
        assert_eq!(f.offset, None);
    }

    #[test]
    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
        // One label, cited twice. The first is where the reader most likely came
        // from, and the only answer that doesn't depend on how they got here.
        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
        let mut d = doc_with("fn_def_repeat", src);
        d.caret = src.find("the note").unwrap();
        let f = d.footnote_definition_at_caret().expect("a definition");
        assert_eq!(
            f.offset,
            Some(5),
            "the first `[^a]`'s label, not the second's"
        );
        assert_eq!(&src[3..7], "[^a]");
    }

    #[test]
    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
        // Down and back up, each leg found from the document rather than from a
        // memory of the other — so it still works for a reader who scrolled to
        // the notes instead of jumping there.
        //
        // `place_caret` rather than assigning `caret`, because that is what a
        // frontend calls: it snaps to a real caret stop, and a jump that lands
        // on a byte the caret can't rest on would arrive somewhere the return
        // leg no longer answers for. `build_map` first, since snapping is a
        // no-op until the map exists — which is exactly how this went unnoticed
        // when the offsets pointed at the `[^` markers.
        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
        d.build_map(None);
        d.place_caret(9, false);
        let down = d
            .footnote_at_caret()
            .expect("a reference")
            .offset
            .expect("a note");
        d.place_caret(down, false);
        let up = d
            .footnote_definition_at_caret()
            .expect("a definition")
            .offset
            .expect("a reference");
        d.place_caret(up, false);
        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
        assert_eq!(
            d.footnote_at_caret().expect("back on the reference").label,
            "1"
        );
    }

    #[test]
    fn insert_link_hands_the_destination_to_twig_raw() {
        // Escaping is twig's, and format-specific: Markdown ends a destination
        // at the first space and needs the `<…>` form, where djot would read
        // those angle brackets as part of the URL.
        let mut d = doc_with("link_space", "word\n");
        d.anchor = Some(0);
        d.caret = 4;
        d.insert_link("a b");
        assert_eq!(d.source, "[word](<a b>)\n");
    }

    #[test]
    fn insert_link_reports_a_destination_no_format_can_carry() {
        let mut d = doc_with("link_bad", "word\n");
        d.anchor = Some(0);
        d.caret = 4;
        d.insert_link("a\nb");
        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
        assert!(
            d.status.is_some(),
            "InvalidArgument should reach the status line"
        );
        assert!(!d.dirty);
    }

    #[test]
    fn insert_link_works_in_wysiwyg_view() {
        let mut d = wysiwyg_doc("link_wys", "word here\n");
        d.anchor = Some(0);
        d.caret = 4;
        d.insert_link("http://x.dev");
        assert_eq!(d.source, "[word](http://x.dev) here\n");
        assert_eq!(d.selected_text(), Some("word"));
        // The map the caret has to keep riding is rebuilt each frame; motion
        // over the fresh one must still land on a real stop (the debug_assert).
        d.build_visual(80);
        d.move_right(false);
        d.move_left(false);
    }

    #[test]
    fn click_maps_a_row_col_to_a_byte_offset() {
        let mut d = doc_with("click", "ab\ncd\n");
        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
        assert_eq!(d.caret, 4);
    }

    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
    // stop just as the `(row, col)` click path does, so the caret can never come
    // to rest in the blank gap between two paragraphs — where it would draw in one
    // place and type in another.
    #[test]
    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
        // caret stop (stops are 0,1,3,4).
        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
        d.place_caret(2, false);
        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
    }

    #[test]
    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
        d.place_caret(0, false); // anchor at the start of "A"
        d.place_caret(2, true); // drag into the gap
        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
        let (s, e) = d.selection().expect("a selection");
        assert!(
            d.vmap.is_stop(s) && d.vmap.is_stop(e),
            "selection {s}..{e} off a stop"
        );
    }

    #[test]
    fn place_caret_on_a_real_stop_is_left_untouched() {
        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
        d.place_caret(3, false); // the start of "B" — a genuine stop
        assert_eq!(d.caret, 3);
    }

    // An *empty paragraph* (two blank lines, an intentional blank line the user
    // opened) is a real caret stop, unlike the gap — a click into it must stay.
    #[test]
    fn place_caret_rests_in_an_empty_paragraph() {
        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
        assert!(d.vmap.is_stop(empty));
        d.place_caret(empty, false);
        assert_eq!(d.caret, empty);
    }

    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
        doc_in(View::Wysiwyg, name, body)
    }

    /// How many list items the source actually parses into — the check that a
    /// marker Leaf wrote is a marker the format agrees is one.
    fn list_items(doc: &mut Doc) -> usize {
        doc.editor
            .nodes()
            .unwrap()
            .iter()
            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
            .count()
    }

    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
    /// incremental (`build_spliced` / `build_cached`) path must always match.
    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
        reference_map_revealing(source, None)
    }

    /// [`reference_map`] with a reveal line — the ground truth for the
    /// `MarkupMode::Full` builds, where the map is a function of the caret's
    /// line as well as the text.
    fn reference_map_revealing(
        source: &str,
        reveal: Option<Range<usize>>,
    ) -> crate::wysiwyg::VisualMap {
        // The same parse `Doc` uses. With twig's plain defaults instead, the two
        // sides disagree on what the *document* is before the renderer is even
        // reached — a bare `:word` is a text directive to one and prose to the
        // other — and the mismatch reads as a splice bug that isn't one.
        let mut ed =
            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
        let nodes = ed.nodes().unwrap();
        crate::wysiwyg::build(
            &nodes,
            source,
            None,
            false,
            &std::collections::HashMap::new(),
            reveal,
        )
    }

    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
        if a.rows.len() != b.rows.len() {
            return true;
        }
        for (ra, rb) in a.rows.iter().zip(&b.rows) {
            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
                return true;
            }
            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
                if ga.ch != gb.ch || ga.src != gb.src {
                    return true;
                }
            }
        }
        false
    }

    #[test]
    fn incremental_build_matches_a_fresh_build_across_edits() {
        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
        // fast path, gated on twig's `dirty_range`) or falls back to
        // `build_cached`. After each edit the map must be byte-identical to a
        // from-scratch build — this is the correctness net under the splice.
        let docs = [
            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
            // A footnote definition is a root beside `doc`, merged back into the
            // top-level list by `wysiwyg::top_blocks`. The random edits below
            // make and unmake definitions as they go (a deleted `:` turns one
            // back into a paragraph, and vice versa), which is exactly the
            // structural churn the splice path has to notice and bail out of.
            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
        ];
        // A deterministic mix: mostly single characters (which stay inside one
        // block → splice), plus edits that reshape structure (a paragraph break,
        // a heading marker, a code fence → fallback), so both paths are exercised.
        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
        for src in docs {
            let mut d = wysiwyg_doc("diff", src);
            d.build_visual_unwrapped();
            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");

            for step in 0..60usize {
                let len = d.source.len();
                let raw = (step * 13 + 5) % (len + 1);
                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
                let pre = d.source.clone();
                let action;
                if step % 3 == 0 && pos < len {
                    let end = (pos + 1..=len)
                        .find(|&i| d.source.is_char_boundary(i))
                        .unwrap();
                    action = format!("delete [{pos},{end})");
                    d.edit(pos, end, "");
                } else {
                    let ins = inserts[step % inserts.len()];
                    action = format!("insert {ins:?} @ {pos}");
                    d.edit(pos, pos, ins);
                }
                d.build_visual_unwrapped();
                if maps_differ(&d.vmap, &reference_map(&d.source)) {
                    panic!(
                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
                        d.source
                    );
                }
            }
        }
    }

    #[test]
    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
        // The same correctness net as `incremental_build_matches_a_fresh_build_
        // across_edits`, under `MarkupMode::Full` — where the map depends on
        // the caret's *line* as well as the text, so the two caches have a new
        // way to be wrong. Both are exercised: the block cache can hand back
        // rows built for a line that is no longer the revealed one, and the
        // splice path can reuse a suffix that still has yesterday's line raw.
        //
        // Caret motion is interleaved with the edits deliberately, because a
        // caret that only ever moved with the edit would never cross a line
        // without also dirtying it — the case where a stale reveal survives.
        let docs = [
            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
        ];
        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
        for src in docs {
            let mut d = wysiwyg_doc("reveal_diff", src);
            d.set_markup_mode(MarkupMode::Full);

            for step in 0..60usize {
                let len = d.source.len();
                let raw = (step * 13 + 5) % (len + 1);
                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
                let pre = d.source.clone();
                let action;
                if step % 3 == 0 && pos < len {
                    let end = (pos + 1..=len)
                        .find(|&i| d.source.is_char_boundary(i))
                        .unwrap();
                    action = format!("delete [{pos},{end})");
                    d.edit(pos, end, "");
                } else {
                    let ins = inserts[step % inserts.len()];
                    action = format!("insert {ins:?} @ {pos}");
                    d.edit(pos, pos, ins);
                }
                // Walk the caret somewhere else in the document, independently
                // of where the edit landed.
                let want = (step * 29 + 11) % (d.source.len() + 1);
                d.caret = (want..=d.source.len())
                    .find(|&i| d.source.is_char_boundary(i))
                    .unwrap();
                d.build_visual_unwrapped();

                let want = reference_map_revealing(&d.source, d.reveal_line());
                if maps_differ(&d.vmap, &want) {
                    panic!(
                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
                        d.caret, d.source
                    );
                }
            }
        }
    }

    #[test]
    fn caret_motion_across_lines_rebuilds_only_under_full() {
        // The cache-key change has to earn its keep in both directions: `Full`
        // must rebuild when the caret changes line (or the reveal would never
        // move), and the hidden modes must *not* (or every arrow key would pay
        // for a feature they don't use). The existing `cache_motion` test pins
        // the second for the default mode; this pins the pair against a mode
        // change alone.
        let body = "*one* here\n\n*two* there\n";

        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
        full.set_markup_mode(MarkupMode::Full);
        caret_at(&mut full, "one");
        let before = full.revision();
        caret_at(&mut full, "two");
        assert_eq!(full.revision(), before, "motion is not an edit");
        assert!(
            drawn_rows(&full).iter().any(|r| r == "*two* there"),
            "the map followed the caret: {:?}",
            drawn_rows(&full)
        );

        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
        caret_at(&mut hidden, "one");
        let key = hidden.vmap_key.clone();
        caret_at(&mut hidden, "two");
        assert_eq!(
            hidden.vmap_key, key,
            "a hidden mode rebuilds nothing on motion"
        );
    }

    #[test]
    fn wysiwyg_down_crosses_a_paragraph_boundary() {
        // Regression: the blank separator row used to share the previous
        // paragraph's end offset, so Down got pinned at the boundary (while Up
        // still crossed). Both directions must step through it symmetrically.
        //
        // It's now stepped *over* rather than onto: the blank line between two
        // paragraphs is the boundary being drawn, not a line of the document, so
        // one press of Down crosses it. The goal column survives the crossing —
        // col 3 at the end of "abc" is col 3 at the end of "def".
        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
        d.caret = 3; // end of "abc" (row 0)
        d.move_down(false);
        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
        assert_eq!(d.caret, 8); // end of "def", col 3 kept
        d.move_up(false);
        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
        assert_eq!(d.caret, 3);
    }

    #[test]
    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
        // The second Up and the second Down here run off the ends of the
        // document, which is no longer a place a press is swallowed: they carry
        // the caret to the start and the end of the text. The claim in the
        // middle — that a Down retraces the Up that crossed the paragraph gap —
        // is the one this test is for, and it is asserted where it is made.
        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
        d.caret = 5; // start of "def"
        let start = d.caret_pos();
        d.move_up(false);
        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
        d.move_up(false);
        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
        d.move_down(false);
        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
        d.move_down(false);
        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
    }

    #[test]
    fn wysiwyg_new_paragraph_shows_before_typing() {
        // Regression: two Enters at the end of a paragraph produced trailing
        // newlines with no AST node, so the caret appeared stuck on the old line
        // until a character was typed. It must ride down onto the new line now.
        let mut d = doc_with("wys_newpara", "abc\n");
        d.view = View::Wysiwyg;
        d.caret = 3;
        d.insert("\n");
        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
        assert_eq!(d.source, "abc\n\n\n");
        d.build_visual(80);
        let (row, _) = d.caret_pos();
        assert!(
            row >= 2,
            "caret should have moved down to the new line, got row {row}"
        );
        assert!(
            d.vmap.num_rows() >= 3,
            "the blank lines should render as rows"
        );
    }

    #[test]
    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
        // The reported bug: Enter at the end of a paragraph that has another
        // paragraph below put the caret at the *start of the next paragraph* —
        // the empty paragraph it opened had no row, so the caret snapped onto
        // "World". It must now sit on its own empty line, with a blank spacer
        // above it (the paragraph gap).
        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
        d.caret = 5; // end of "Hello"
        d.newline();
        d.build_visual(80);
        let (row, col) = d.caret_pos();
        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
        assert_eq!(
            d.vmap.row_width(row),
            0,
            "caret's row must be empty, not 'World'"
        );
        assert!(
            row >= 2,
            "a blank spacer row should sit above the caret, got row {row}"
        );
        // The row above the caret is a real (empty) gap, and "Hello" stays put.
        assert_eq!(
            d.vmap.row_width(row - 1),
            0,
            "the row above the caret is a gap"
        );
        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
    }

    #[test]
    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
        // At the document end a single Enter must also show the paragraph gap —
        // a blank spacer row above the caret — so the layout already matches how
        // it will look once the new paragraph has text.
        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
        d.caret = 5; // end of "Hello", no trailing newline
        d.newline(); // source becomes "Hello\n\n"
        d.build_visual(80);
        let (row, col) = d.caret_pos();
        assert_eq!(col, 0);
        assert!(
            row >= 2,
            "caret should sit below a blank spacer, got row {row}"
        );
        assert_eq!(
            d.vmap.row_width(row - 1),
            0,
            "the row above the caret is a gap"
        );
    }

    #[test]
    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
        // The spacer is view-only: typing the new paragraph must not reflow the
        // caret onto a different row — the transient view already matched the
        // settled one.
        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
        d.caret = 5;
        d.newline();
        d.build_visual(80);
        let before = d.caret_pos();
        d.insert("New");
        d.build_visual(80);
        let after = d.caret_pos();
        assert_eq!(
            after.0, before.0,
            "typing must not move the caret to another row ({before:?} -> {after:?})"
        );
    }

    #[test]
    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
        let fm = "---\ntitle: hi\n---\n";
        let body = format!("{fm}# leaf\n\nbody\n");
        let mut d = wysiwyg_doc("wys_fm", &body);
        // Opening lifts the caret out of the now-hidden frontmatter.
        assert_eq!(
            d.caret,
            fm.len(),
            "caret should start at the first real block"
        );
        // Left at the content start can't step back into frontmatter.
        d.move_left(false);
        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
        // Doc-start lands on the content floor, not offset 0.
        d.move_doc_start(false);
        assert_eq!(d.caret, fm.len());
        // Select-all + copy never include the frontmatter bytes.
        d.select_all();
        let sel = d.selected_text().unwrap().to_string();
        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
        assert!(
            sel.starts_with("# leaf"),
            "selection should begin at content: {sel:?}"
        );
    }

    #[test]
    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
        // Backspace deletes `prev_boundary..caret` directly; at the first real
        // block that boundary is inside the hidden frontmatter, so it must be a
        // no-op rather than eating the closing `---`.
        let fm = "---\ntitle: hi\n---\n";
        let body = format!("{fm}leaf\n");
        let mut d = wysiwyg_doc("wys_fm_bs", &body);
        assert_eq!(d.caret, fm.len());
        d.backspace();
        assert_eq!(d.source, body, "backspace must not touch frontmatter");
        d.delete_word_back();
        assert_eq!(
            d.source, body,
            "word-delete must not touch frontmatter either"
        );
    }

    #[test]
    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
        // fenced div, really, since core parses these on for every document
        // now (`parse_extensions`). The container is a `directive` node, an
        // `is_block_container` kind like `block_quote`, so the caret works
        // inside its child paragraph exactly as it would inside a quote: typing
        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
        // untouched.
        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
        let mut d = wysiwyg_doc("wys_vis", body);
        d.caret = body.find("hello").unwrap() + "hello".len();
        d.insert("!");
        assert_eq!(
            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
            "typing inside the block edits its content in place"
        );
        assert!(
            d.source.contains(":::vis{.public .family}"),
            "opening fence survives"
        );
        assert!(d.source.contains(":::\nafter"), "closing fence survives");
    }

    #[test]
    fn source_view_still_reaches_frontmatter() {
        // The metadata is only *hidden*, never lost: the source view edits and
        // selects it in full, and it's always preserved on save.
        let fm = "---\ntitle: hi\n---\n";
        let body = format!("{fm}# leaf\n");
        let mut d = doc_with("src_fm", &body);
        d.select_all();
        let sel = d.selected_text().unwrap();
        assert!(
            sel.contains("title"),
            "source view should select everything"
        );
        d.move_doc_start(false);
        assert_eq!(d.caret, 0, "source view can reach offset 0");
    }

    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";

    #[test]
    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
        // The border and padding between two cells all share one source offset,
        // so a column-stepping caret would sit on `│` and then stall there
        // forever. Right must step: end of "Name" -> start of "Qty".
        let mut d = wysiwyg_doc("tbl_right", TABLE);
        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
        d.move_right(false);
        assert_eq!(
            d.caret,
            TABLE.find("Qty").unwrap(),
            "should land in the next cell"
        );
        let (r, c) = d.caret_pos();
        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
    }

    #[test]
    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
        let mut d = wysiwyg_doc("tbl_left", TABLE);
        d.caret = TABLE.find("Qty").unwrap();
        d.move_left(false);
        assert_eq!(
            d.caret,
            TABLE.find("Name").unwrap() + 4,
            "end of the previous cell"
        );
    }

    #[test]
    fn wysiwyg_down_steps_over_a_table_rule() {
        // Between the header and the first body row sits a `├───┼───┤` rule.
        // It's drawn but holds no caret, so one Down must reach "Pear".
        let mut d = wysiwyg_doc("tbl_down", TABLE);
        d.caret = TABLE.find("Name").unwrap();
        d.move_down(false);
        assert_eq!(
            d.caret,
            TABLE.find("Pear").unwrap(),
            "one Down reaches the body row"
        );
        d.move_down(false);
        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
    }

    #[test]
    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
        let mut d = wysiwyg_doc("tbl_tab", TABLE);
        d.caret = TABLE.find("Name").unwrap();
        // A hop lands with the destination cell's whole content selected, the
        // caret at its end — so typing replaces the cell like a form field.
        assert!(d.cell_hop(true));
        assert_eq!(
            d.selected_text(),
            Some("Qty"),
            "the target cell comes up selected"
        );
        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
        assert_eq!(d.selected_text(), Some("Pear"));
        assert!(d.cell_hop(false));
        assert_eq!(d.selected_text(), Some("Qty"));
    }

    #[test]
    fn tab_outside_a_table_is_not_a_cell_hop() {
        // `cell_hop` reports false so the frontend can indent as usual.
        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
        d.caret = 4;
        assert!(!d.cell_hop(true));
        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
    }

    #[test]
    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
        let mut d = wysiwyg_doc("tbl_edge", TABLE);
        d.caret = TABLE.rfind("12").unwrap(); // the final cell
        assert!(!d.cell_hop(true), "no cell after the last one");
        d.caret = TABLE.find("Name").unwrap();
        assert!(!d.cell_hop(false), "no cell before the first one");
    }

    #[test]
    fn wysiwyg_vertical_cell_motion_holds_the_column() {
        // Down/Up step to the cell above/below in the *same column*, not back to
        // the top-left the way a naive row/col motion over the picture would.
        let mut d = wysiwyg_doc("tbl_vert", TABLE);
        d.caret = TABLE.find("Qty").unwrap();
        // Each vertical hop selects the destination cell, holding the column.
        assert!(d.cell_move_vertical(true));
        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
        assert!(d.cell_move_vertical(true));
        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
        assert!(!d.cell_move_vertical(true), "no row below the last");
        assert!(d.cell_move_vertical(false));
        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
        assert!(d.cell_move_vertical(false));
        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
        assert!(!d.cell_move_vertical(false), "no row above the header");
    }

    #[test]
    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
        let mut d = wysiwyg_doc("tbl_grow", TABLE);
        d.caret = TABLE.rfind("12").unwrap();
        let rows_before = d.source.matches('\n').count();
        assert!(d.cell_tab(true), "acts as a table key");
        assert_eq!(
            d.source.matches('\n').count(),
            rows_before + 1,
            "a fresh row was appended"
        );
        assert!(d.caret_in_table(), "the caret entered the new row");
        // The caret sits in the new row's first cell — past the old last cell.
        assert!(d.caret > TABLE.rfind("12").unwrap());
    }

    #[test]
    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
        let mut d = wysiwyg_doc("tbl_ret", TABLE);
        d.caret = TABLE.find("Name").unwrap();
        assert!(d.cell_return(), "acts as a table key");
        assert_eq!(
            d.selected_text(),
            Some("Pear"),
            "Return drops one cell, selecting it"
        );
        // From the last row, Return appends a row and enters it.
        d.caret = TABLE.rfind("Fig").unwrap();
        let rows_before = d.source.matches('\n').count();
        assert!(d.cell_return());
        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
        assert!(d.caret_in_table());
    }

    #[test]
    fn return_and_tab_outside_a_table_decline() {
        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
        d.caret = 4;
        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
        assert!(!d.cell_tab(true), "no table: the frontend indents");
        assert!(
            !d.cell_line_break(),
            "no table: the frontend breaks the line"
        );
    }

    #[test]
    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
        let mut d = wysiwyg_doc("tbl_break", TABLE);
        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
        assert!(d.cell_line_break(), "acts as a table key");
        assert!(
            d.source.contains("Pear<br>"),
            "spelled as an inline <br>: {}",
            d.source
        );
        assert!(d.caret_in_table(), "still in the cell, past the break");
        // The break renders as a real line: the "Pear" cell now draws two lines,
        // so the table's picture is one row taller than a single-line table.
        d.build_visual(80);
        let table = &d.vmap.tables[0];
        let cell = &table.grid[1].cells[0]; // first body row, first column
        assert!(
            cell.glyphs.iter().any(|g| g.ch == '\n'),
            "the cell carries the break as a newline glyph for the frontend to split"
        );
    }

    #[test]
    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
        // back as structure — the whole point of routing through insert_line_break
        // instead of splicing raw `<br>` bytes.
        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
        d.caret = TABLE.find("Pear").unwrap() + 4;
        assert!(d.cell_line_break());
        let kinds: Vec<Kind> = d
            .editor
            .nodes()
            .unwrap()
            .iter()
            .map(|n| n.kind.clone())
            .collect();
        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
        assert!(
            !kinds.contains(&Kind::RawInline),
            "still raw HTML: {kinds:?}"
        );
    }

    #[test]
    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
        // The `<br>` draws as one newline glyph, so Backspace over it must take
        // all four bytes — a one-byte delete would strand a visible `<br` in the
        // cell (the reported bug).
        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
        d.caret = TABLE.find("Pear").unwrap() + 4;
        assert!(d.cell_line_break());
        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
        d.backspace(); // caret sits just past the break
        assert!(
            !d.source.contains("<br"),
            "no half-deleted <br left: {}",
            d.source
        );
        assert!(
            d.source.contains("| Pear |"),
            "the cell is back to one line: {}",
            d.source
        );
    }

    #[test]
    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
        d.caret = TABLE.find("Pear").unwrap() + 4;
        assert!(d.cell_line_break());
        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
        d.delete_forward();
        assert!(
            !d.source.contains("<br"),
            "no half-deleted <br: {}",
            d.source
        );
        assert!(
            d.source.contains("| Pear |"),
            "cell back to one line: {}",
            d.source
        );
    }

    #[test]
    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
        // still consumed (a real newline would split the one-line row), but the
        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
        d.caret = src.find("Pear").unwrap() + 4;
        assert!(d.caret_in_table(), "caret should be inside the djot table");
        assert!(
            d.cell_line_break(),
            "the key is consumed, not passed to the frontend"
        );
        assert_eq!(d.source, src, "the djot cell is left untouched");
        assert!(
            !d.source.contains("<br>"),
            "no non-idiomatic <br> spliced into djot"
        );
        assert!(
            d.status.is_some(),
            "the refusal is surfaced on the status line"
        );
    }

    #[test]
    fn typing_in_a_cell_edits_that_cell() {
        // Editing comes free once offsets map correctly: the caret is a source
        // offset, so a normal splice lands inside the pipe table.
        let mut d = wysiwyg_doc("tbl_type", TABLE);
        d.caret = TABLE.find("Pear").unwrap() + 4;
        d.insert("s");
        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
    }

    #[test]
    fn motion_and_delete_treat_an_emoji_as_one_character() {
        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
        // bytes, several codepoints. Right-arrow must clear it in one step, and
        // backspace must remove the whole cluster, not a stray joiner.
        let family = "👨‍👩‍👧";
        let mut d = doc_with("emoji", &format!("a{family}b\n"));
        d.caret = 1; // just after 'a', before the emoji
        d.move_right(false);
        assert_eq!(
            d.caret,
            1 + family.len(),
            "one step clears the whole cluster"
        );
        assert_eq!(&d.source[d.caret..d.caret + 1], "b");

        d.backspace(); // delete the emoji as a unit
        assert_eq!(d.source, "ab\n");
        assert_eq!(d.caret, 1);
    }

    #[test]
    fn motion_handles_a_combining_accent_as_one_character() {
        // "e" + U+0301 (combining acute) renders as one é.
        let mut d = doc_with("combining", "e\u{0301}x\n");
        d.caret = 0;
        d.move_right(false);
        assert_eq!(
            d.caret,
            "e\u{0301}".len(),
            "steps past base + combining mark"
        );
    }

    #[test]
    fn undo_then_redo_round_trips_an_edit() {
        let mut d = doc_with("undo", "hello\n");
        d.caret = 5;
        d.insert("!");
        assert_eq!(d.source, "hello!\n");
        d.undo();
        assert_eq!(d.source, "hello\n");
        assert_eq!(d.caret, 5, "undo restores the caret");
        d.redo();
        assert_eq!(d.source, "hello!\n");
    }

    #[test]
    fn a_run_of_typing_undoes_as_one_step() {
        let mut d = doc_with("coalesce", "\n");
        d.caret = 0;
        d.insert("a");
        d.insert("b");
        d.insert("c");
        assert_eq!(d.source, "abc\n");
        d.undo(); // the whole typed run, not just "c"
        assert_eq!(d.source, "\n");
        d.undo(); // nothing left — the run was one step
        assert_eq!(d.source, "\n");
        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
    }

    // ── IME composition ──────────────────────────────────────────────────────

    #[test]
    fn a_composition_run_undoes_as_one_step() {
        let mut d = doc_with("compose", "\n");
        d.caret = 0;
        // What an IME does: each step replaces the last one's provisional bytes.
        d.edit_composing(0, 0, "k");
        d.edit_composing(0, 1, "");
        d.edit_composing(0, 3, "かん");
        d.edit_composing(0, 6, ""); // the commit
        d.end_composition();
        assert_eq!(d.source, "\n");
        d.undo(); // the whole composition, not its last keystroke
        assert_eq!(d.source, "\n");
        assert_eq!(d.status.as_deref(), None, "the run was a single step");
    }

    #[test]
    fn two_compositions_are_two_undo_steps() {
        let mut d = doc_with("compose_two", "\n");
        d.caret = 0;
        d.edit_composing(0, 0, "");
        d.edit_composing(0, 3, "");
        d.end_composition();
        d.edit_composing(3, 3, "");
        d.edit_composing(3, 6, "");
        d.end_composition();
        assert_eq!(d.source, "蚊木\n");
        d.undo();
        assert_eq!(d.source, "\n", "only the second composition");
        d.undo();
        assert_eq!(d.source, "\n");
    }

    #[test]
    fn a_composition_does_not_fold_into_the_typing_around_it() {
        let mut d = doc_with("compose_typing", "\n");
        d.caret = 0;
        d.insert("a");
        d.insert("b");
        d.edit_composing(2, 2, "");
        d.edit_composing(2, 5, "");
        d.end_composition();
        d.insert("c");
        assert_eq!(d.source, "ab蚊c\n");
        d.undo();
        assert_eq!(d.source, "ab蚊\n");
        d.undo();
        assert_eq!(d.source, "ab\n");
        d.undo();
        assert_eq!(d.source, "\n");
    }

    #[test]
    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
        let mut d = doc_with("compose_spurious", "\n");
        d.caret = 0;
        d.insert("a");
        d.end_composition(); // an IME unmarking unprompted
        d.insert("b");
        assert_eq!(d.source, "ab\n");
        d.undo();
        assert_eq!(d.source, "\n", "still one typed run");
    }

    // ── the clipboard's rich flavor ──────────────────────────────────────────

    #[test]
    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
        let mut d = doc_with("sel_inline", "a **bold** c\n");
        d.anchor = Some(2);
        d.caret = 10; // `**bold**`, inside the paragraph
        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
    }

    #[test]
    fn a_whole_block_selection_keeps_its_paragraph() {
        let mut d = doc_with("sel_block", "a **bold** c\n");
        d.anchor = Some(0);
        d.caret = 12; // the entire paragraph
        assert_eq!(
            d.selection_html().as_deref(),
            Some("<p>a <strong>bold</strong> c</p>")
        );
    }

    #[test]
    fn a_multi_block_selection_keeps_its_structure() {
        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
        d.select_all();
        let html = d.selection_html().expect("renders");
        assert!(html.contains("<p>para</p>"), "{html:?}");
        assert!(html.contains("<li>one</li>"), "{html:?}");
    }

    #[test]
    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
        // The fragment `Head` is a paragraph standalone; the *document* says it
        // sits inside one block, so the wrapper is an artifact either way.
        let mut d = doc_with("sel_heading", "# Head line\n");
        d.anchor = Some(2);
        d.caret = 6;
        assert_eq!(d.selection_html().as_deref(), Some("Head"));
    }

    #[test]
    fn no_selection_publishes_no_html() {
        let mut d = doc_with("sel_none", "a b\n");
        d.caret = 1;
        assert_eq!(d.selection_html(), None);
    }

    #[test]
    fn pasting_html_converts_it_and_is_one_undo_step() {
        let mut d = doc_with("paste_html", "x\n");
        d.caret = 1;
        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
        assert_eq!(d.source, "xa **b** c\n");
        d.undo();
        assert_eq!(d.source, "x\n", "the whole paste, in one step");
    }

    #[test]
    fn pasting_html_replaces_the_selection() {
        let mut d = doc_with("paste_html_sel", "keep drop\n");
        d.anchor = Some(5);
        d.caret = 9;
        assert!(d.paste_html("<em>new</em>"));
        assert_eq!(d.source, "keep *new*\n");
    }

    #[test]
    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
        let mut d = doc_with("paste_html_bad", "x\n");
        d.caret = 1;
        // twig builds no table from HTML; raw `<table>` in prose is worse than
        // the plain flavor the caller still holds.
        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
        assert_eq!(d.source, "x\n", "declined edits nothing");
    }

    #[test]
    fn copy_then_paste_round_trips_through_the_html_flavor() {
        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
        d.select_all();
        let html = d.selection_html().expect("renders");
        let mut into = doc_with("clip_round_dst", "\n");
        into.caret = 0;
        assert!(into.paste_html(&html));
        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
    }

    #[test]
    fn moving_the_caret_starts_a_new_undo_group() {
        let mut d = doc_with("break", "\n");
        d.caret = 0;
        d.insert("a");
        d.insert("b"); // "ab\n", caret at 2
        d.move_left(false); // breaks the run
        d.insert("X"); // "aXb\n"
        assert_eq!(d.source, "aXb\n");
        d.undo();
        assert_eq!(
            d.source, "ab\n",
            "first undo removes only the post-move insert"
        );
        d.undo();
        assert_eq!(d.source, "\n", "second undo removes the earlier run");
    }

    #[test]
    fn undo_reverses_a_format_toggle() {
        let mut d = doc_with("fmt_undo", "a word b\n");
        d.anchor = Some(2);
        d.caret = 6;
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "a **word** b\n");
        d.undo();
        assert_eq!(d.source, "a word b\n");
    }

    #[test]
    fn undo_back_to_the_saved_state_clears_dirty() {
        let mut d = doc_with("dirty_undo", "hello\n");
        assert!(!d.dirty);
        d.caret = 5;
        d.insert("!");
        assert!(d.dirty);
        d.undo();
        assert!(
            !d.dirty,
            "undoing to the saved source is not a modification"
        );
    }

    #[test]
    fn a_new_edit_invalidates_redo() {
        let mut d = doc_with("redo_inv", "\n");
        d.caret = 0;
        d.insert("a");
        d.undo();
        d.insert("b"); // diverges — the redo of "a" is now gone
        d.redo();
        assert_eq!(d.source, "b\n");
    }

    #[test]
    fn undo_on_empty_history_is_a_no_op() {
        let mut d = doc_with("undo_empty", "hi\n");
        d.undo();
        assert_eq!(d.source, "hi\n");
        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
    }

    #[test]
    fn a_one_character_paste_is_its_own_undo_step() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "paste_step", "ab\n");
            d.caret = 0;
            d.insert("x");
            d.insert("y"); // a run of typing
            d.paste("z"); // one character, but pasted — not part of that run
            assert_eq!(d.source, "xyzab\n");
            d.undo();
            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
            assert_eq!(d.caret, 2, "and hands back the caret it found");
            d.undo();
            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
        }
    }

    #[test]
    fn the_same_character_typed_still_joins_the_run() {
        // The other half of the pair: `z` is a keystroke here and a paste above,
        // and the two undo differently. Nothing about the *string* says which —
        // which is why provenance has to come from the door the caller uses.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "typed_run", "ab\n");
            d.caret = 0;
            d.insert("x");
            d.insert("y");
            d.insert("z");
            d.undo();
            assert_eq!(d.source, "ab\n", "one run, one step");
        }
    }

    #[test]
    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "undo_caret", "hello world\n");
            d.caret = 11; // standing at the end of "world", away from the edit
            d.edit(0, 5, "goodbye");
            assert_eq!(d.source, "goodbye world\n");
            d.undo();
            assert_eq!(d.source, "hello world\n");
            // The undone edit ends at offset 5; the user was at 11.
            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
        }
    }

    #[test]
    fn undo_restores_the_selection_the_edit_replaced() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "undo_sel", "a word b\n");
            d.anchor = Some(2);
            d.caret = 6; // "word" selected
            d.insert("X");
            assert_eq!(d.source, "a X b\n");
            d.undo();
            assert_eq!(d.source, "a word b\n");
            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
        }
    }

    #[test]
    fn redo_restores_the_caret_the_edit_left_behind() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "redo_caret", "hello world\n");
            d.caret = 11;
            d.edit(0, 5, "goodbye");
            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
            d.undo();
            d.redo();
            assert_eq!(d.source, "goodbye world\n");
            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
        }
    }

    #[test]
    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "run_caret", "hi\n");
            d.caret = 2;
            d.insert("a");
            d.insert("b");
            d.insert("c");
            assert_eq!(d.source, "hiabc\n");
            d.undo();
            assert_eq!(d.source, "hi\n");
            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
            d.redo();
            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
        }
    }

    #[test]
    fn undo_restores_the_caret_across_a_format_toggle() {
        // A toggle reaches twig without going through `splice`, so it has to
        // record its own step — miss it and every stack depth below it is off by
        // one, and undo starts handing back another edit's caret.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "fmt_caret", "a word b\n");
            d.caret = 8;
            d.anchor = Some(2);
            d.caret = 6;
            d.toggle(InlineKind::Strong);
            assert_eq!(d.source, "a **word** b\n");
            d.undo();
            assert_eq!(d.source, "a word b\n");
            assert_eq!(
                d.selection(),
                Some((2, 6)),
                "the toggled selection comes back"
            );
        }
    }

    #[test]
    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
        // The drift that would never announce itself: twig drops its redo stack
        // on any fresh edit, so a leaf redo entry that outlives it would restore
        // a caret from the timeline that edit abandoned.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "redo_trunc", "hello world\n");
            d.caret = 11;
            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
            d.undo();
            assert_eq!(d.caret, 11);
            d.caret = 0;
            d.insert("X"); // diverges: A's redo is gone from twig
            assert_eq!(d.source, "Xhello world\n");

            d.redo();
            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
            d.undo();
            assert_eq!(d.source, "hello world\n");
            assert_eq!(
                d.caret, 0,
                "the surviving step's caret, not the dropped one"
            );
        }
    }

    #[test]
    fn indent_and_outdent_move_the_caret_line_with_its_text() {
        for view in [View::Source, View::Wysiwyg] {
            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
            // Indentation the caret is standing *in* collapses to the line start
            // rather than dragging the caret into the text.
            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
            // A line with none to give back is left exactly as it was.
            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
            // Less than a full level gives back what it has.
            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
            // A tab is one level however many spaces it isn't.
            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
        }
    }

    #[test]
    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
        // Why the level is two spaces and not the four both frontends type
        // today. Four is markdown's indented-code-block marker, so a Tab on a
        // paragraph would silently restyle it as code — a width that changes
        // what the document *means* isn't an indent. Pinned because the number
        // is the kind of thing a later list-aware pass would reach for.
        let mut d = doc_with("indent_kind", "hello\n");
        d.caret = 2;
        d.indent();
        assert_eq!(d.source, "  hello\n");
        assert!(
            d.nodes().iter().any(|n| n.kind == Kind::Para),
            "still prose after a Tab"
        );
        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));

        // The four-space level this replaces, for contrast: same text, and twig
        // reparses the paragraph into a code block.
        let mut wide = doc_with("indent_kind_4", "    hello\n");
        wide.build_visual(80);
        assert!(
            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
            "four spaces is a code block, not an indented paragraph"
        );
    }

    #[test]
    fn indent_nests_a_list_item_under_its_parent() {
        // Tab indents a list item by its own marker width, landing its marker at
        // the parent's content column so twig reparses it as a nested list.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
            d.caret = 6; // on the second item
            d.indent();
            assert_eq!(d.source, "- a\n  - b\n");
            let lists = d
                .nodes()
                .iter()
                .filter(|n| n.kind == Kind::BulletList)
                .count();
            assert_eq!(lists, 2, "the indented item is a nested list");
        }
    }

    #[test]
    fn indent_nests_an_ordered_item_at_its_marker_width() {
        // An ordered marker `1. ` is three columns wide, so a two-space step
        // (which nests a bullet) leaves it flat. Regression: Tab must use the
        // marker width, three, so the item actually nests — and the source
        // renumbers so the sub-list restarts at 1 and the outer list resumes.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
            d.caret = d.source.find('b').unwrap();
            d.indent();
            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
            let lists = d
                .nodes()
                .iter()
                .filter(|n| n.kind == Kind::OrderedList)
                .count();
            assert_eq!(lists, 2, "the indented item is a nested ordered list");
        }
    }

    #[test]
    fn indent_leaves_a_lists_first_item_put() {
        // The first item of a list has no sibling above it to nest under, so Tab
        // is a no-op there — the marker stays at column zero rather than being
        // shoved into indentation twig can't read as a sub-list.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
            d.caret = 1; // on the FIRST item
            d.indent();
            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
            // The sibling below still nests, proving the guard is per-item.
            d.caret = d.source.find('b').unwrap();
            d.indent();
            assert_eq!(d.source, "- a\n  - b\n");
        }
    }

    #[test]
    fn hidden_mode_keeps_typed_markup_literal() {
        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
        // twig escapes what would open markup, so the source is `\*hi\*` and the
        // AST is a plain string. Formatting is the commands' job in this mode.
        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
        d.insert("*hi*");
        assert_eq!(d.source, "\\*hi\\*");
        assert!(
            d.nodes()
                .iter()
                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
        );
    }

    #[test]
    fn hidden_mode_escapes_a_line_start_block_marker() {
        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
        d.insert("# hi");
        assert_eq!(d.source, "\\# hi");
        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
    }

    #[test]
    fn authoring_modes_keep_typed_markup_live() {
        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
        // (no escape), the same as source view — escaping is `None`'s alone, and
        // it's the axis, not the reveal, that decides.
        for (view, mode) in [
            (View::Wysiwyg, MarkupMode::Shortcuts),
            (View::Wysiwyg, MarkupMode::Full),
            (View::Source, MarkupMode::None),
        ] {
            let mut d = doc_in(view, "live_markup", "");
            d.set_markup_mode(mode);
            d.insert("*hi*");
            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
        }
    }

    #[test]
    fn hidden_mode_overwrite_undoes_in_one_step() {
        // Typing over a selection escapes the replacement *and* stays a single
        // undo — the selection-delete and the literal insert fold together, so
        // one undo brings the whole selection back, like a plain overwrite.
        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
        d.anchor = Some(2);
        d.caret = 6; // "word"
        d.insert("*");
        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
        d.undo();
        assert_eq!(d.source, "a word b\n");
        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
    }

    #[test]
    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
        // the whole visual character, never stranding the hidden `\`.
        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
        d.insert("*");
        assert_eq!(d.source, "\\*");
        d.backspace();
        assert_eq!(d.source, "", "the escape backslash went with the *");
        // A *literal* backslash (source view, no escape) is an ordinary char.
        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
        s.caret = 3; // after `b`
        s.backspace();
        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
    }

    #[test]
    fn hidden_mode_leaves_structural_markup_alone() {
        // Enter continues a bullet list by writing a real `- ` marker (an
        // `insert_raw`, not the typing path), so Hidden mode's escaping never
        // touches it — the list keeps working.
        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
        d.caret = 6;
        d.newline();
        d.insert("two");
        assert_eq!(d.source, "- item\n- two\n");
    }

    #[test]
    fn markup_mode_defaults_to_none_and_round_trips() {
        // Diaryx's default is the clean `None` surface; a markup-fluent
        // frontend can climb the ladder, and the choice sticks.
        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
            d.set_markup_mode(mode);
            assert_eq!(d.markup_mode(), mode);
        }
    }

    #[test]
    fn full_mode_reveals_only_the_caret_line() {
        // The mode's whole claim: the caret's line shows its raw delimiters and
        // every other line stays resolved. Two paragraphs with identical markup
        // so the only difference between the rows is where the caret is.
        let mut d = doc_in(
            View::Wysiwyg,
            "reveal_caret_line",
            "*one* here\n\n*two* there\n",
        );
        d.set_markup_mode(MarkupMode::Full);

        caret_at(&mut d, "one");
        let rows = drawn_rows(&d);
        assert!(
            rows.iter().any(|r| r == "*one* here"),
            "caret's line raw: {rows:?}"
        );
        assert!(
            rows.iter().any(|r| r == "two there"),
            "other line resolved: {rows:?}"
        );

        // Move to the other paragraph: the reveal follows, and the line just
        // left goes back to being resolved.
        caret_at(&mut d, "two");
        let rows = drawn_rows(&d);
        assert!(
            rows.iter().any(|r| r == "*two* there"),
            "caret's line raw: {rows:?}"
        );
        assert!(
            rows.iter().any(|r| r == "one here"),
            "left line resolved: {rows:?}"
        );
    }

    #[test]
    fn hidden_modes_never_reveal_wherever_the_caret_is() {
        // The two rungs below `Full` share a rendering: delimiters stay hidden
        // even under the caret. `Shortcuts` differing from `None` only in what
        // typing does is exactly the point of splitting the axes.
        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
            d.set_markup_mode(mode);
            caret_at(&mut d, "one");
            let rows = drawn_rows(&d);
            assert!(
                rows.iter().any(|r| r == "one here"),
                "{mode:?} hides: {rows:?}"
            );
            assert!(
                !rows.iter().any(|r| r.contains('*')),
                "{mode:?} shows no `*`: {rows:?}"
            );
        }
    }

    #[test]
    fn revealed_delimiters_are_the_authors_own_spelling() {
        // Delimiters are re-read from the source rather than synthesized per
        // kind, so a line comes back spelled the way it was written: `_em_` does
        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
        d.set_markup_mode(MarkupMode::Full);
        caret_at(&mut d, "em");
        let rows = drawn_rows(&d);
        assert!(
            rows.iter().any(|r| r == body.trim_end()),
            "the revealed line is its own source: {rows:?}"
        );
    }

    #[test]
    fn revealed_heading_shows_its_hashes() {
        // The `# ` marker is a block-level prefix, not an inline delimiter, so
        // it takes its own path — but it reveals on the same rule.
        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
        d.set_markup_mode(MarkupMode::Full);

        caret_at(&mut d, "Title");
        assert!(
            drawn_rows(&d).iter().any(|r| r == "# Title"),
            "{:?}",
            drawn_rows(&d)
        );

        caret_at(&mut d, "body");
        let rows = drawn_rows(&d);
        assert!(
            rows.iter().any(|r| r == "Title"),
            "hashes hidden again: {rows:?}"
        );
    }

    #[test]
    fn revealed_delimiters_are_caret_stops() {
        // A delimiter that is drawn but can't be reached is worse than one
        // that's hidden: the mode exists so the markup can be *edited*. Every
        // revealed byte must be somewhere the caret can stand.
        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
        d.set_markup_mode(MarkupMode::Full);
        caret_at(&mut d, "em");
        let opener = d.source.find('*').unwrap();
        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
        assert!(
            d.vmap.is_stop(opener + 3),
            "the closing `*` is a caret stop"
        );
    }

    #[test]
    fn setext_heading_reveals_nothing_across_its_newline() {
        // A setext heading's underline is on another line, so it is not the
        // caret line's to reveal — and emitting it would inject a `\n` glyph
        // that splits the row where the author wrote no break.
        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
        d.set_markup_mode(MarkupMode::Full);
        caret_at(&mut d, "Title");
        let rows = drawn_rows(&d);
        assert!(
            rows.iter().any(|r| r == "Title"),
            "title renders alone: {rows:?}"
        );
        assert!(
            !rows.iter().any(|r| r.contains('=')),
            "no underline leaks in: {rows:?}"
        );
    }

    #[test]
    fn markup_mode_axes_split_the_ladder() {
        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
        // that authors markup but still hides it, and it's the only rung where
        // the two axes disagree.
        assert!(!MarkupMode::None.authors());
        assert!(!MarkupMode::None.reveals_caret_line());
        assert!(MarkupMode::Shortcuts.authors());
        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
        assert!(MarkupMode::Full.authors());
        assert!(MarkupMode::Full.reveals_caret_line());
    }

    #[test]
    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
        // nested bullet and `hello` stays prose: the file round-trips instead of
        // hiding a heading the user never asked for.
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
            d.indent();
            assert_eq!(d.source, "- hello\n  * \n");
            assert!(
                d.nodes().iter().all(|n| n.kind != Kind::Heading),
                "no heading"
            );
            // And it's genuinely a nested list, not a flat one.
            assert_eq!(
                d.nodes()
                    .iter()
                    .filter(|n| n.kind == Kind::BulletList)
                    .count(),
                2
            );
        }
    }

    #[test]
    fn indenting_a_dash_item_with_content_keeps_its_dash() {
        // With content, `- x` can't be a setext underline, so there's nothing to
        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
        d.caret = d.source.find('x').unwrap();
        d.indent();
        assert_eq!(d.source, "- hello\n  - x\n");
    }

    #[test]
    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
        // The dash→`*` repair coalesces into the Tab, so a single undo restores
        // the whole pre-Tab state rather than stranding a half-collapsed doc.
        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
        d.caret = d.source.find("- \n").unwrap() + 2;
        d.indent();
        assert_eq!(d.source, "- hello\n  * \n");
        d.undo();
        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
    }

    #[test]
    fn indent_leaves_a_nested_lists_first_item_put_too() {
        // The guard is about siblings, not depth: the first item of an *inner*
        // list (already nested under `a`) still has nothing before it at its own
        // level, so Tab can't take it deeper.
        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
        d.caret = d.source.find('b').unwrap();
        d.indent();
        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
        // But `c` (a sibling of `b`) nests under `b`.
        d.caret = d.source.find('c').unwrap();
        d.indent();
        assert_eq!(d.source, "- a\n  - b\n    - c\n");
    }

    #[test]
    fn backspace_at_a_nested_item_start_outdents_it() {
        // Backspace with the caret right after a nested item's marker gives back
        // one level of nesting, the mirror of Tab — and renumbers the flattened
        // ordered list back to a clean run.
        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
        d.backspace();
        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
    }

    #[test]
    fn backspace_at_a_top_level_item_start_strips_the_marker() {
        // At the outermost level there's no nesting left to give back, so the same
        // keystroke drops the bullet and leaves a plain paragraph.
        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
        d.caret = d.source.find('b').unwrap(); // right after `- `
        d.backspace();
        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
    }

    #[test]
    fn backspace_mid_item_still_deletes_a_character() {
        // The list behaviour is armed only at the item's content start; anywhere
        // else Backspace is the ordinary character delete.
        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
        d.backspace();
        assert_eq!(d.source, "- b\n");
    }

    #[test]
    fn backspace_at_a_heading_start_strips_the_marker() {
        // The `# ` is markup the rich view hides, so Backspace over it takes the
        // whole marker and leaves a paragraph. Deleting a byte of it instead left
        // `#Title` — no longer a heading, with the hash now literal text the user
        // never typed and has to delete again.
        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
        d.caret = d.source.find('T').unwrap(); // right after `## `
        d.backspace();
        assert_eq!(d.source, "Title\n");
        assert_eq!(
            d.caret, 0,
            "the caret stays with the text it was in front of"
        );
    }

    #[test]
    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
        // Only the heading's own marker goes — the quote (or list) it sits in is
        // untouched, exactly as un-heading it should be.
        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
        d.caret = d.source.find('T').unwrap();
        d.backspace();
        assert_eq!(d.source, "> Title\n");
    }

    #[test]
    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
        // behind would surface the same stray hash the marker delete just avoided.
        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
        d.caret = d.source.find('T').unwrap();
        d.backspace();
        assert_eq!(d.source, "Title\n");
        // And it's one edit: a single undo puts the whole heading back.
        d.undo();
        assert_eq!(d.source, "# Title #\n");
    }

    #[test]
    fn backspace_mid_heading_still_deletes_a_character() {
        // The heading behaviour is armed only at the content's start; anywhere
        // else Backspace is the ordinary character delete.
        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
        d.caret = d.source.find('b').unwrap();
        d.backspace();
        assert_eq!(d.source, "# b\n");
    }

    #[test]
    fn source_view_backspace_still_edits_the_heading_marker_literally() {
        // In source view the `# ` is text on the screen the user is deleting a
        // byte of, so it keeps its literal meaning — the same split the list
        // ladder and Enter draw between the two views.
        let mut d = doc_with("bsp_head_src", "# Title\n");
        d.caret = d.source.find('T').unwrap();
        d.backspace();
        assert_eq!(d.source, "#Title\n");
    }

    #[test]
    fn outdent_unnests_an_ordered_item_in_one_press() {
        // Shift+Tab gives back exactly the marker width the indent added, so a
        // nested ordered item unnests in a single press, and the flattened list
        // renumbers back to a clean 1, 2, 3.
        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
        d.caret = d.source.find('b').unwrap();
        d.outdent();
        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
        let lists = d
            .nodes()
            .iter()
            .filter(|n| n.kind == Kind::OrderedList)
            .count();
        assert_eq!(lists, 1, "back to one flat list");
    }

    #[test]
    fn table_insert_row_adds_a_row_below_the_caret() {
        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
        d.caret = d.source.find('1').unwrap(); // in the body row
        d.table_insert_row(true);
        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
    }

    #[test]
    fn table_insert_and_delete_column_at_the_caret() {
        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
        d.caret = d.source.find('a').unwrap(); // column 0
        d.table_insert_column(true); // add a column to the right of `a`
        assert_eq!(
            d.source,
            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
        );
        d.caret = d.source.find('b').unwrap(); // now the third column
        d.table_delete_column();
        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
    }

    // ── ragged formats ───────────────────────────────────────────────────────
    // No format spells every gesture. HTML writes the inline marks as a tag pair
    // and no heading, list, quote or link; Markdown spells three of the eight
    // marks; djot spells all eight and no in-cell break. leaf asks twig per
    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
    // op discover the fact on its own — one of them didn't.

    /// An HTML document in the rich view, ready for a gesture.
    fn html_doc(body: &str) -> Doc {
        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
        d.view = View::Wysiwyg;
        d.build_visual(80);
        d
    }

    #[test]
    fn a_table_gesture_leaves_an_html_table_alone() {
        // The regression this guard exists for. twig's table editor consults no
        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
        // HTML `<table>` as a *pipe table* and reported success: the whole
        // element replaced by `| a | b |`, silently, on one press of a toolbar
        // button. Every grid op went the same way.
        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
        // A table of named operations, which is what it looks like.
        #[allow(clippy::type_complexity)]
        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
            ("delete row", &|d: &mut Doc| d.table_delete_row()),
            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
            ("delete column", &|d: &mut Doc| d.table_delete_column()),
            ("align", &|d: &mut Doc| {
                d.table_set_alignment(Alignment::Right)
            }),
            ("move row", &|d: &mut Doc| d.table_move_row(true)),
            ("move column", &|d: &mut Doc| d.table_move_column(true)),
        ];
        for (name, op) in ops {
            let mut d = html_doc(src);
            d.caret = d.source.find('a').unwrap();
            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
            op(&mut d);
            assert_eq!(d.source, src, "{name} rewrote an HTML table");
            assert!(
                !d.dirty,
                "{name} marked the document dirty without editing it"
            );
            assert!(d.status.is_some(), "{name} refused without saying why");
        }
    }

    #[test]
    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
        // A heading is a wrapping tag pair carrying its level in both ends, a
        // quote wraps a range rather than prefixing each line, a link's
        // destination lives in an attribute — different *shapes*, not a
        // different alphabet, so twig spells none of them and neither does leaf.
        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
        // A table of named operations, which is what it looks like.
        #[allow(clippy::type_complexity)]
        let ops: [(&str, &dyn Fn(&mut Doc)); 9] = [
            ("heading", &|d: &mut Doc| d.toggle_heading(2)),
            ("paragraph", &|d: &mut Doc| {
                d.set_block(BlockKind::Paragraph)
            }),
            ("quote", &|d: &mut Doc| d.toggle_blockquote()),
            ("list", &|d: &mut Doc| d.toggle_list(false)),
            ("task item", &|d: &mut Doc| d.toggle_task_item()),
            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
            ("link", &|d: &mut Doc| d.insert_link("https://example.dev")),
            ("image", &|d: &mut Doc| d.insert_image("pic.png", "alt")),
            ("video", &|d: &mut Doc| {
                d.insert_media(MediaKind::Video, "clip.mp4", "")
            }),
        ];
        for (name, op) in ops {
            let mut d = html_doc(src);
            let at = d.source.find("Hello").unwrap();
            d.caret = at;
            d.anchor = Some(at + 5); // a selection, for the ops that want one
            op(&mut d);
            assert_eq!(d.source, src, "{name} edited an HTML document");
            assert!(
                !d.dirty,
                "{name} marked the document dirty without editing it"
            );
            let status = d.status.as_deref().unwrap_or("");
            assert!(
                status.contains("html"),
                "{name}: the refusal should name the format, got {status:?}"
            );
        }
    }

    #[test]
    fn html_spells_the_inline_marks_and_the_rule() {
        // The other half, and why one per-document flag stopped being enough:
        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
        // already emits and the parser reads straight back as the same mark —
        // and the rule button writes an `<hr>`. Refusing these on the old
        // "HTML is parse-only" reading would now be leaf's own limitation.
        let mut d = html_doc("<p>Hello world</p>\n");
        let at = d.source.find("world").unwrap();
        d.caret = at;
        d.anchor = Some(at + 5);
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
        assert!(d.dirty);
        assert_eq!(d.status, None, "a supported gesture reports nothing");

        // And off again — the toggle reverses, which is the property that makes
        // authoring in HTML worth offering rather than a one-way trip.
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "<p>Hello world</p>\n");

        let mut d = html_doc("<p>Hello world</p>\n");
        d.caret = d.source.find("world").unwrap();
        d.insert_thematic_break();
        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
    }

    #[test]
    fn a_mark_the_format_cannot_spell_arms_nothing() {
        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
        // sticky mark for the next text typed. Guarding only the twig call
        // leaves that path live, promising a highlight Markdown will never spell
        // and then swallowing the error inside `insert`. Markdown carries the
        // case now that HTML spells `<mark>`: `==mark==` is djot's alone.
        let mut d = doc_with("mark", "Hello world\n");
        d.view = View::Wysiwyg;
        d.build_visual(80);
        d.caret = d.source.find("world").unwrap();
        d.toggle(InlineKind::Mark);
        assert!(d.pending_marks.is_empty(), "no mark should be armed");
        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
        d.insert("X");
        assert_eq!(d.source, "Hello Xworld\n");
    }

    #[test]
    fn html_documents_still_take_typed_text() {
        // The guard covers *markup* gestures and must not touch plain editing:
        // twig's splicer is language-neutral, and typing into an HTML document
        // is the thing that does work today.
        let mut d = html_doc("<p>Hello world</p>\n");
        d.caret = d.source.find("world").unwrap();
        d.insert("big ");
        assert_eq!(d.source, "<p>Hello big world</p>\n");
        assert!(d.dirty);
        d.backspace();
        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
        d.undo();
        d.undo();
        assert_eq!(d.source, "<p>Hello world</p>\n");
    }

    #[test]
    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
        // `authorable` only separates "there is a door in" from "there is not",
        // and HTML is on the near side of that line — which is exactly why a
        // toolbar must not be built from it.
        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
        assert!(html.authorable());
        assert!(
            !Doc::from_source("<r>x</r>".into(), Format::Xml)
                .unwrap()
                .authorable()
        );

        let caps = html.capabilities();
        assert!(caps.bold && caps.italic && caps.code && caps.mark);
        assert!(caps.thematic_break && caps.cell_line_break);
        assert!(!caps.heading && !caps.blockquote && !caps.bullet_list);
        assert!(!caps.task && !caps.link && !caps.image && !caps.code_language);
        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
        // twig's table editor would happily re-emit as `| a | b |`.
        assert!(!caps.table);

        // The two lightweight formats spell everything leaf offers — and still
        // differ from each other, which is the other half of why one boolean
        // can't serve.
        for fmt in [Format::Markdown, Format::Djot] {
            let caps = Capabilities::of(fmt);
            assert!(
                caps.heading && caps.blockquote && caps.ordered_list,
                "{fmt:?}"
            );
            assert!(
                caps.task && caps.link && caps.image && caps.table,
                "{fmt:?}"
            );
        }
        assert!(Capabilities::of(Format::Djot).mark);
        assert!(!Capabilities::of(Format::Markdown).mark);
        assert!(Capabilities::of(Format::Markdown).cell_line_break);
        assert!(!Capabilities::of(Format::Djot).cell_line_break);

        // A parse-only format answers no to every one of them, so the coarse
        // predicate and the record agree there.
        let caps = Capabilities::of(Format::Xml);
        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
    }

    #[test]
    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
        // The guard exists to name the *document's* format rather than twig's
        // internals, so the message has to survive being one leaf writes itself.
        // Checked against the gesture twig also refuses, since that is the pair
        // most at risk of drifting apart.
        let mut d = html_doc("<p>Hello</p>\n");
        d.caret = d.source.find("Hello").unwrap();
        d.set_code_language("zig");
        assert_eq!(
            d.status.as_deref(),
            Some("code language: not supported in html")
        );
        assert!(!d.dirty);
    }

    #[test]
    fn table_set_alignment_respells_the_delimiter() {
        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
        d.caret = d.source.find('b').unwrap();
        d.table_set_alignment(Alignment::Right);
        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
    }

    #[test]
    fn each_empty_table_cell_has_its_own_editable_home() {
        // Regression: an empty cell has no twig content_span, so both cells of a
        // `|  |  |` row collapsed onto the row's start (before the first `│`).
        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
        // tell the cells apart. Each empty cell must now have a distinct home
        // inside it.
        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
        let (c0, c1) = {
            let cells = &d.vmap.tables[0].grid[1].cells;
            (cells[0].start, cells[1].start)
        };
        assert!(
            c0 < c1,
            "the two empty cells have distinct homes: {c0} < {c1}"
        );
        d.caret = c0;
        d.insert("x");
        assert_eq!(
            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
            "typed inside the cell"
        );
    }

    #[test]
    fn arrows_step_into_each_empty_table_cell() {
        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
        let (c0, c1) = {
            let cells = &d.vmap.tables[0].grid[1].cells;
            (cells[0].start, cells[1].start)
        };
        d.caret = d.source.find('b').unwrap(); // in the header's second cell
        let mut seen = std::collections::HashSet::new();
        for _ in 0..6 {
            d.move_right(false);
            seen.insert(d.caret);
        }
        assert!(
            seen.contains(&c0),
            "right arrow reaches the first empty cell"
        );
        assert!(
            seen.contains(&c1),
            "right arrow reaches the second empty cell"
        );
    }

    #[test]
    fn table_op_off_a_table_is_a_no_op_with_a_status() {
        let mut d = doc_with("tbl_none", "just text\n");
        d.caret = 3;
        d.table_insert_row(true);
        assert_eq!(d.source, "just text\n", "nothing changed");
        assert!(d.status.is_some(), "a status explains why");
        assert!(!d.caret_in_table());
    }

    #[test]
    fn enter_in_an_ordered_list_renumbers_the_following_items() {
        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
        // the renumber pass keeps them sequential, matching what the view draws.
        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
        d.caret = d.source.find('a').unwrap() + 1; // end of item a
        d.newline();
        d.insert("x");
        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
    }

    #[test]
    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "outdent_noop", "hello\n");
            d.caret = 2;
            d.outdent();
            assert_eq!(d.source, "hello\n");
            assert!(!d.dirty, "a no-op is not a modification");
            d.undo();
            assert_eq!(
                d.status.as_deref(),
                Some("nothing to undo"),
                "spends no undo step"
            );
            assert_eq!(d.source, "hello\n");
        }
    }

    #[test]
    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
            d.anchor = Some(0);
            d.caret = 7; // through "two"
            d.indent();
            assert_eq!(
                d.source, "  one\n\n  two\n",
                "the blank line keeps no trailing pad"
            );
            // Selected, so a second Tab lands on the same lines rather than on
            // whatever the shifted offsets now cover.
            assert_eq!(d.selection(), Some((0, 12)));
            d.indent();
            assert_eq!(d.source, "    one\n\n    two\n");
        }
    }

    #[test]
    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
            d.anchor = Some(0);
            d.caret = 15;
            d.outdent();
            assert_eq!(d.source, "two\none\nnone\n");
        }
    }

    #[test]
    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
        for view in [View::Source, View::Wysiwyg] {
            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
            d.anchor = Some(0);
            d.caret = 7;
            d.indent();
            assert_eq!(d.source, "  one\n\n  two\n");
            d.undo();
            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
            assert_eq!(
                d.selection(),
                Some((0, 7)),
                "with the selection it was aimed at"
            );
            d.redo();
            assert_eq!(d.source, "  one\n\n  two\n");
            assert_eq!(
                d.selection(),
                Some((0, 12)),
                "redo replays the caret the indent placed, not the one splice left"
            );
        }
    }

    #[test]
    fn vertical_motion_keeps_the_column() {
        let mut d = doc_with("move", "abcd\nef\n");
        d.caret = 3; // "abc|d" on row 0, col 3
        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
        assert_eq!(d.caret, 7); // just after "ef"
    }

    // ── goal column ──────────────────────────────────────────────────────────

    #[test]
    fn vertical_motion_goal_column_survives_a_short_line() {
        // Regression: re-deriving the column from the clamped position on
        // every step permanently forgets it once a short line clamps it.
        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
        assert_eq!(
            g("abcd|ef\nxy\nghijkl\n", |d| {
                d.move_down(false); // clamps to end of "xy"
                d.move_down(false); // restores col 4 on the long line
            }),
            "abcdef\nxy\nghij|kl\n"
        );
    }

    #[test]
    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
        assert_eq!(d.goal_col, None);
        d.caret = 4; // row 0, col 4
        d.move_down(false); // clamps into "xy"; goal stays the original col
        assert_eq!(d.goal_col, Some(4));
        assert_eq!(d.caret_pos(), (1, 2));

        // A horizontal motion drops the goal column...
        d.move_left(false);
        assert_eq!(d.goal_col, None);

        // ...so the next vertical motion picks up the *new* column (1), not
        // the stale one (4).
        d.move_down(false);
        assert_eq!(d.goal_col, Some(1));
        assert_eq!(d.caret_pos(), (2, 1));
    }

    #[test]
    fn editing_clears_the_goal_column() {
        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
        d.caret = 4;
        d.move_down(false);
        assert_eq!(d.goal_col, Some(4));
        d.insert("Z");
        assert_eq!(d.goal_col, None);
    }

    #[test]
    fn vertical_motion_on_an_empty_document_is_a_no_op() {
        let mut d = doc_with("empty_vert", "");
        d.move_down(false);
        assert_eq!(d.caret, 0);
        d.move_up(false);
        assert_eq!(d.caret, 0);
    }

    // ── the document's edges ─────────────────────────────────────────────────

    #[test]
    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
        // The reproduction, and the disagreement: Down on the last line ran to
        // the end of the document in the source view — by accident, an
        // out-of-range row clamping to the end of the string — and did nothing
        // whatever in the view leaf opens in. One rule now, in both.
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
            d.caret = 1;
            d.move_down(false);
            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
            d.move_up(false);
            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
        }
    }

    #[test]
    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
        // Down off the bottom is a motion like any other, so it latches a goal
        // column — and Up comes back to the column the caret left, not to the
        // one the document's end happened to be in.
        for (view, tag) in VIEWS {
            let gap = if view == View::Source { "\n" } else { "\n\n" };
            let src = format!("abcdef{gap}ghijkl");
            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
            d.caret = 2; // row 0, col 2
            d.move_down(false);
            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
            d.move_down(false);
            assert_eq!(
                d.caret,
                src.len(),
                "{tag}: Down off the bottom reaches the end"
            );
            d.move_up(false);
            assert_eq!(
                d.caret_pos().1,
                2,
                "{tag}: Up returns to the column Down left"
            );
        }
    }

    #[test]
    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
        // Up that did nothing still armed a goal column, and the next Down aimed
        // at a column the caret had never been in.
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
            d.caret = 0;
            d.move_up(false);
            assert_eq!(d.caret, 0, "{tag}: already at the start");
            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");

            d.caret = d.source.len();
            d.move_down(false);
            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
            assert_eq!(
                d.goal_col, None,
                "{tag}: a no-op Down latched a goal column"
            );
        }
    }

    // ── soft wrap ────────────────────────────────────────────────────────────
    // Every other test here builds the map at 80 columns, where no fixture is
    // long enough to fold. A wrap is where one offset belongs to two rows at
    // once, and it broke everything that asks the caret what row it is on.

    /// The wrapped fixture these cases share, folded at 12 columns into
    /// `one two ` / `three four ` / `five six ` / `seven eight`.
    fn wrapped_doc(name: &str) -> Doc {
        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
        d.build_visual(12);
        d
    }

    #[test]
    fn home_and_end_work_from_a_wrapped_row() {
        // The reproduction: offset 19 is the `f` of "five", the first character
        // of the third row — and also the offset the second row ends at. It
        // resolved to the *second* row, so End aimed at a place the caret was
        // already in and did nothing, while Home walked backwards onto a row the
        // caret had left.
        let mut d = wrapped_doc("wrap_home_end");
        d.caret = 19;
        assert_eq!(
            d.caret_pos(),
            (2, 0),
            "the wrap boundary opens the third row"
        );
        d.move_end(false);
        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
        d.move_home(false);
        assert_eq!(d.caret, 19, "Home left the row the caret was on");
    }

    #[test]
    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
        // The row's end is the last offset that is only ever its own: the offset
        // past it opens the row below, and aiming there would send a second
        // press on to *that* row's end, and a third to the next — End walking
        // down the paragraph rather than sitting where it landed.
        let mut d = wrapped_doc("wrap_end_twice");
        d.caret = 12; // inside "three", on the second row
        d.move_end(false);
        assert_eq!(
            d.caret, 18,
            "the end of `three four`, before the space the wrap ate"
        );
        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
        d.move_end(false);
        assert_eq!(d.caret, 18, "a second End moved the caret");
        d.move_home(false);
        assert_eq!(d.caret, 8, "Home takes the row's own start");
    }

    #[test]
    fn vertical_motion_crosses_a_soft_wrap() {
        // Down aimed at the row below's column 0, an offset that resolved *up*
        // to the row above's end — so it landed on the offset it already had and
        // the caret could never leave a paragraph's first row.
        let mut d = wrapped_doc("wrap_down");
        d.caret = 0;
        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
            d.move_down(false);
            assert_eq!(d.caret, want, "Down stalled");
            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
        }
        d.move_down(false);
        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");

        // ...and back up, one row per press. The goal column is the end of the
        // last row, past every other row's width, so each press clamps to the
        // row's own last offset rather than to the one that opens the next.
        let mut d = wrapped_doc("wrap_up");
        d.caret = 39;
        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
            d.move_up(false);
            assert_eq!(d.caret, want, "Up stalled");
            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
        }
    }

    #[test]
    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
        // The kills take the same line Home and End do, so in WYSIWYG they take
        // the visual row — and a soft wrap has no newline in it to delete, so
        // nothing is joined by reaching the end of one.
        let mut d = wrapped_doc("wrap_kill");
        d.caret = 19; // the `f` of "five", opening the third row
        d.delete_to_line_end();
        // The space the wrap ate goes with the row it was drawn on: sparing it
        // would leave "four  seven", two spaces where the row had been.
        assert_eq!(d.source, "one two three four seven eight");

        // Backwards from the row's last caret position — which is *before* that
        // space, so this one survives, being on the far side of the caret.
        let mut d = wrapped_doc("wrap_kill_back");
        d.caret = 27;
        d.delete_to_line_start();
        assert_eq!(d.source, "one two three four  seven eight");
    }

    // ── document start / end ────────────────────────────────────────────────

    #[test]
    fn move_doc_start_and_end_jump_to_the_edges() {
        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
        assert_eq!(
            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
            "|hello\nworld\n"
        );
        assert_eq!(
            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
            "hello\nworld\n|"
        );
        // Already at the edge: a no-op.
        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
    }

    #[test]
    fn move_doc_start_and_end_extend_the_selection() {
        assert_eq!(
            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
                .move_doc_end(true)),
            "hello wor[ld\n|]"
        );
        assert_eq!(
            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
                .move_doc_start(true)),
            "[|hello wor]ld\n"
        );
    }

    #[test]
    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
        let mut d = doc_with("empty_edges", "");
        d.move_doc_end(false);
        assert_eq!(d.caret, 0);
        d.move_doc_start(false);
        assert_eq!(d.caret, 0);
    }

    // ── arrow collapses an active selection ─────────────────────────────────

    #[test]
    fn arrow_collapses_selection_to_its_near_edge() {
        let mut d = doc_with("collapse", "hello world\n");

        // Forward selection (anchor before caret): Right -> end, Left -> start.
        d.anchor = Some(2);
        d.caret = 7;
        d.move_right(false);
        assert_eq!((d.caret, d.anchor), (7, None));

        d.anchor = Some(2);
        d.caret = 7;
        d.move_left(false);
        assert_eq!((d.caret, d.anchor), (2, None));

        // Backward selection (anchor after caret): edges are the same
        // regardless of which end the caret started on.
        d.anchor = Some(7);
        d.caret = 2;
        d.move_right(false);
        assert_eq!((d.caret, d.anchor), (7, None));

        d.anchor = Some(7);
        d.caret = 2;
        d.move_left(false);
        assert_eq!((d.caret, d.anchor), (2, None));
    }

    #[test]
    fn arrow_with_extend_keeps_growing_the_selection() {
        let mut d = doc_with("collapse_extend", "hello world\n");
        d.anchor = Some(2);
        d.caret = 7;
        d.move_right(true); // extend: no collapse, caret steps one further
        assert_eq!((d.caret, d.anchor), (8, Some(2)));
    }

    #[test]
    fn arrow_without_a_selection_moves_one_character_as_before() {
        let mut d = doc_with("no_collapse", "hello\n");
        d.caret = 2;
        d.move_right(false);
        assert_eq!(d.caret, 3);
        d.move_left(false);
        assert_eq!(d.caret, 2);
    }

    /// Press Right until it stops, collecting the offsets walked through. Every
    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
    /// two stops sharing one source offset can't be moved between, so the caret
    /// stalls on the first of them and the walk never reaches the rest.
    fn walk_right(d: &mut Doc) -> Vec<usize> {
        let mut seen = vec![d.caret];
        for _ in 0..2000 {
            let before = d.caret;
            d.move_right(false);
            if d.caret == before {
                break;
            }
            seen.push(d.caret);
        }
        seen
    }

    #[test]
    fn the_caret_crosses_a_soft_break() {
        // A newline inside a paragraph is a `soft_break`, which twig gives no
        // span of its own — the space it renders as used to borrow the offset of
        // the character before it, and a caret can't move without changing
        // offset. Right must walk clean off the end of the first line.
        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
        d.caret = 0;
        let seen = walk_right(&mut d);
        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
    }

    #[test]
    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
        // The paragraph holds one soft break. Folded (the default) it lays out as
        // a single reflowed row; Preserve re-lays it as a row per source line.
        // The setter must invalidate the cached map for the change to show, and
        // again on the way back — so a round trip returns to the folded layout.
        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
        d.build_visual(80);
        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");

        d.set_line_flow(LineFlow::Preserve);
        d.build_visual(80);
        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");

        d.set_line_flow(LineFlow::Fold);
        d.build_visual(80);
        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
    }

    #[test]
    fn the_caret_still_crosses_a_preserved_soft_break() {
        // Preserve renders the soft break as a row boundary rather than a space,
        // but the caret must still reach every offset — the break's own offset is
        // the first row's end stop, so Right walks clean off the end of line one
        // onto line two, exactly as it does when the break is folded.
        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
        d.set_line_flow(LineFlow::Preserve);
        d.build_visual(80);
        d.caret = 0;
        let seen = walk_right(&mut d);
        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
    }

    #[test]
    fn the_caret_walks_a_code_block() {
        // Every glyph of a code block used to map to the block's start, so the
        // whole block was a single offset and the caret couldn't move inside it.
        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
        let mut d = wysiwyg_doc("code_walk", src);
        d.caret = 0;
        let seen = walk_right(&mut d);
        // The fences are markup: hidden, and no caret stop. The code between
        // them is reached a character at a time.
        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
        for off in code.clone() {
            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
        }
        assert!(seen.contains(&code.end), "no stop after the last line");
    }

    #[test]
    fn the_caret_walks_an_indented_code_block() {
        // An indented block's text has the four-space indent stripped, so it
        // isn't a verbatim slice and its lines have to be re-found. The caret
        // lands on the code, never in the indent.
        let src = "    indented\n    code\n";
        let mut d = wysiwyg_doc("indent_code_walk", src);
        d.caret = 0;
        let seen = walk_right(&mut d);
        assert!(seen.contains(&src.find("indented").unwrap()));
        assert!(seen.contains(&src.find("code").unwrap()));
        assert!(
            !seen.contains(&0) || seen[0] == 0,
            "the caret starts where it was put"
        );
        // Nothing in the stripped indent is a stop.
        for off in [1, 2, 3] {
            assert!(!seen.contains(&off), "landed in the indent at {off}");
        }
    }

    #[test]
    fn the_caret_leaves_a_tight_heading() {
        // "# H" with text directly under it: the heading row's end and the
        // separator row's end are the same offset. Right used to find the
        // separator's copy, set the caret to where it already was, and stop.
        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
        d.caret = 2; // the "H"
        let seen = walk_right(&mut d);
        assert!(
            seen.len() > 2,
            "Right stalled at the heading's end: {seen:?}"
        );
        assert!(
            seen.contains(&8),
            "never reached the end of \"text\": {seen:?}"
        );
    }

    #[test]
    fn the_caret_skips_the_gap_between_two_paragraphs() {
        // The blank line between two paragraphs is the boundary itself. The
        // caret used to be able to sit on it, and typing there landed in the
        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
        // soft break, so the text visibly snapped back up.
        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
        d.caret = 1; // the end of "A"
        d.move_right(false);
        assert_eq!(d.caret, 3, "Right stopped in the gap");
        d.insert("x");
        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
    }

    #[test]
    fn down_from_a_paragraph_lands_on_the_next_one() {
        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
        d.caret = 0;
        d.move_down(false);
        assert_eq!(d.caret, 3, "Down stopped in the gap");
    }

    #[test]
    fn clicking_the_gap_lands_on_real_text() {
        // A click can still *reach* the gap — it's drawn, so it's clickable.
        // It has to resolve to somewhere the caret can be.
        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
        d.click(1, 0, false); // the gap row
        assert!(
            d.caret == 1 || d.caret == 3,
            "click left the caret in the gap at {}",
            d.caret
        );
        d.insert("x");
        // Either edge of the boundary is a fair place to land; inside it isn't.
        assert!(
            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
            "click in the gap typed into the boundary: {:?}",
            d.source
        );
    }

    #[test]
    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
        // Enter inserts a paragraph break, which leaves a blank line spare on
        // either side of a new one. That middle line is a real empty paragraph:
        // the caret lands there, and typing makes a paragraph rather than
        // extending a neighbour.
        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
        d.caret = 1;
        d.newline();
        assert_eq!(d.source, "A\n\n\n\nB\n");
        d.build_visual(80);
        let (row, _) = d.caret_pos();
        assert!(
            d.vmap.row_is_navigable(row),
            "the caret landed on a gap row"
        );
        d.insert("x");
        assert_eq!(
            d.source, "A\n\nx\n\nB\n",
            "the new paragraph merged into a neighbour"
        );
    }

    #[test]
    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
        let mut d = wysiwyg_doc("gap_eof", "A\n");
        d.caret = 1;
        d.newline();
        d.build_visual(80);
        let (row, _) = d.caret_pos();
        assert!(
            d.vmap.row_is_navigable(row),
            "the caret landed on a gap row"
        );
        d.insert("x");
        assert!(
            d.source.starts_with("A\n\n") && d.source.contains('x'),
            "typing at the end merged into A: {:?}",
            d.source
        );
    }

    #[test]
    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
        // A paragraph broken over two source lines is one paragraph. Selecting
        // it must not stop at the newline inside it — that newline is markup the
        // rich-text view exists to hide.
        let src = "one two\nthree four\n\nnext\n";
        let mut d = wysiwyg_doc("triple_para", src);
        d.select_block_at(2);
        assert_eq!(
            d.selected_text(),
            Some("one two\nthree four"),
            "stopped at the soft break"
        );
    }

    #[test]
    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
        // The reader scrolls down past the caret's row. Nothing moved the
        // caret, so the view must stay where it was put — the old code revealed
        // the caret every frame, which dragged the view straight back and made
        // the document unscrollable past the caret.
        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
        d.caret = 0;
        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
        d.scroll = 4; // the wheel
        d.follow_caret(0, 3, 9);
        assert_eq!(
            d.scroll, 4,
            "the wheel was overruled by a caret that never moved"
        );
    }

    #[test]
    fn moving_the_caret_brings_the_view_back_to_it() {
        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
        d.caret = 0;
        d.follow_caret(0, 3, 9);
        d.scroll = 6; // scrolled away
        d.move_right(false); // ...and now the caret moves
        let (row, _) = d.caret_pos();
        d.follow_caret(row, 3, 9);
        assert!(
            d.scroll <= row && row < d.scroll + 3,
            "caret row {row} off screen at scroll {}",
            d.scroll
        );
    }

    #[test]
    fn scrolling_stops_at_the_last_row() {
        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
        d.caret = 0;
        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
        d.scroll = 999; // the wheel, spun hard
        d.follow_caret(0, 3, 3);
        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
    }

    #[test]
    fn every_cell_of_a_wide_table_is_reachable() {
        // A table whose cells are far wider than the surface: the columns are
        // cut to fit and the text wraps inside them, so no cell hangs off the
        // right edge where the caret can never go.
        let src = "| Ingredient | Notes |\n|---|---|\n\
                   | flour milled coarse | sift it twice before folding it in |\n";
        let mut d = wysiwyg_doc("wide_table_walk", src);
        d.build_visual(30);
        d.caret = 0;
        let seen = walk_right(&mut d);
        for word in ["Ingredient", "Notes", "coarse", "folding"] {
            let at = src.find(word).unwrap();
            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
        }
    }

    // ── view parity ──────────────────────────────────────────────────────────
    // `doc_with` pins the source view, so everything above tests a view users
    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
    // deletion golden cases through *both*, plus the WYSIWYG cases the two
    // can't share: where the source carries markup the rendered text is a
    // different string, and the views agreeing would itself be the bug.

    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];

    /// Run `action` in both views on one `|`-marked fixture and assert they
    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
    /// source verbatim, so the two views are looking at the same text and any
    /// disagreement is one of them having lost the plot.
    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
        let (src, caret) = parse_caret(marked);
        let run = |view: View, tag: &str| {
            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
            d.caret = caret;
            action(&mut d);
            render_caret(&d)
        };
        let source = run(VIEWS[0].0, VIEWS[0].1);
        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
        source
    }

    #[test]
    fn word_motion_agrees_across_the_views_on_plain_prose() {
        let g = both_views;
        assert_eq!(
            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
            "hello |world"
        );
        assert_eq!(
            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
            "|hello world"
        );
        assert_eq!(
            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
            "hello| world"
        );
        assert_eq!(
            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
            "hello world|"
        );
        assert_eq!(
            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
            "foo|.bar"
        );
        assert_eq!(
            g("par_ext", "hello |world", |d| d.move_word_right(true)),
            "hello [world|]"
        );
    }

    #[test]
    fn word_deletion_agrees_across_the_views_on_plain_prose() {
        let g = both_views;
        assert_eq!(
            g("par_db", "hello world|", |d| d.delete_word_back()),
            "hello |"
        );
        assert_eq!(
            g("par_df", "hello |world", |d| d.delete_word_forward()),
            "hello |"
        );
        assert_eq!(
            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
            "|bar baz"
        );
        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
    }

    #[test]
    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
        let g = both_views;
        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
    }

    #[test]
    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
        // The reproduction: the stop table was built one stop per `char`, so
        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
        // source view, which steps by grapheme, can't reach and backspace can't
        // survive. The two views must land on the same offset.
        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
            d.caret = 1;
            d.move_right(false);
            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");

            // ...and the edit that used to sever a joiner off the front of it.
            d.backspace();
            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
            assert_eq!(d.caret, 1);
        }
    }

    #[test]
    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
            d.caret = 0;
            d.move_right(false);
            assert_eq!(
                d.caret,
                "e\u{0301}".len(),
                "{tag} stopped on the combining mark"
            );
        }
    }

    #[test]
    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
        // The general form: whatever route the caret takes through a document
        // full of clusters, it never lands between the codepoints of one — so no
        // motion-then-backspace sequence can leave a dangling joiner behind.
        use unicode_segmentation::UnicodeSegmentation;

        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
        let mut d = wysiwyg_doc("cluster_walk", src);
        d.caret = 0;
        let boundaries: Vec<usize> = src
            .grapheme_indices(true)
            .map(|(i, _)| i)
            .chain(std::iter::once(src.len()))
            .collect();
        for off in walk_right(&mut d) {
            assert!(
                boundaries.contains(&off),
                "Right stopped at {off}, inside a grapheme cluster"
            );
        }
    }

    #[test]
    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
        // The reproduction: ⌥→ from inside the opening `**` computed its
        // boundary over the raw source and landed on byte 8 — inside the
        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
        // "bold". The caret drew past the bold word and sat inside it.
        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
        d.caret = 2;
        d.move_word_right(false);
        assert!(
            d.vmap.is_stop(d.caret),
            "landed at {}, not a caret stop",
            d.caret
        );
        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
        // The rendered row is "a bold c": column 6 is the space just past "bold",
        // and now the caret is really there rather than only drawn there.
        assert_eq!(d.caret_pos(), (0, 6));

        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
        d.move_word_left(false);
        assert_eq!(d.caret, 4);
        assert_eq!(d.caret_pos(), (0, 2));
    }

    #[test]
    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
        // inside the closing `**`, and left "a ** c\n" — delimiters with no
        // opener. Glyph space covers the word alone, which would leave
        // "a **** c": markup wrapped around nothing. The word and the styling
        // that was only ever the word's go together.
        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
        d.caret = 10;
        d.delete_word_back();
        assert_eq!(d.source, "a  c\n");
        assert_eq!(d.caret, 2);

        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
        d.caret = 4; // the "b"
        d.delete_word_forward();
        assert_eq!(d.source, "a  c\n");
    }

    #[test]
    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
        let src = "a ***bold*** c\n";
        let mut d = wysiwyg_doc("wys_word_del_nest", src);
        d.caret = src.find(" c").unwrap();
        d.delete_word_back();
        assert_eq!(
            d.source, "a  c\n",
            "the emph inside the strong empties it too"
        );

        let src = "a `code` c\n";
        let mut d = wysiwyg_doc("wys_word_del_code", src);
        d.caret = src.find(" c").unwrap();
        d.delete_word_back();
        assert_eq!(d.source, "a  c\n");
    }

    #[test]
    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
        // Only an *emptied* node goes. Take one word of two and the `**` still
        // has a job to do — over the word that's left, with the space the delete
        // pushed against the opening delimiter moved out in front of it, or the
        // run would be no run at all (`** words**` is literal asterisks — see
        // the mark-edge rule on `splice`).
        let src = "a **two words** c\n";
        let mut d = wysiwyg_doc("wys_word_del_partial", src);
        d.caret = src.find(" words").unwrap();
        d.delete_word_back();
        assert_eq!(d.source, "a  **words** c\n");
    }

    #[test]
    fn source_view_word_motion_still_walks_the_markup() {
        // The other half of the decision: in the source view the `**` are
        // characters like any other — they're on the screen, so word motion has
        // to stop at them and a word-delete has to leave them behind. Only
        // WYSIWYG hides them, so only WYSIWYG steps over them.
        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
        assert_eq!(
            g("src_word_motion", "a |**bold** c\n", |d| d
                .move_word_right(false)),
            "a **bold|** c\n"
        );
        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
        assert_eq!(
            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
            "a **| c\n"
        );
    }

    #[test]
    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
        // The single invariant both bugs violated: the caret draws and edits at
        // the same place only when it's on a stop. `debug_assert_on_a_stop`
        // makes the same claim in-place; this pins it from the outside, over a
        // document with every kind of thing the map has to be careful about.
        // At two widths: the wide one every other test builds at, where no
        // fixture folds, and one narrow enough that they all do. A soft wrap is
        // where an offset stops being on exactly one row, and testing only the
        // width that never wraps is how the caret came to be pinned at the first
        // one Down reached.
        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
        // A table of named operations, which is what it looks like.
        #[allow(clippy::type_complexity)]
        let motions: [(&str, fn(&mut Doc)); 8] = [
            ("right", |d| d.move_right(false)),
            ("left", |d| d.move_left(false)),
            ("word_right", |d| d.move_word_right(false)),
            ("word_left", |d| d.move_word_left(false)),
            ("down", |d| d.move_down(false)),
            ("up", |d| d.move_up(false)),
            ("home", |d| d.move_home(false)),
            ("end", |d| d.move_end(false)),
        ];
        for width in [80, 12] {
            let mut d = wysiwyg_doc("stop_invariant", src);
            d.build_visual(width);
            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
            assert!(stops.len() > 20, "fixture should have plenty of stops");
            for start in stops {
                for (name, motion) in &motions {
                    d.caret = start;
                    d.anchor = None;
                    motion(&mut d);
                    assert!(
                        d.vmap.is_stop(d.caret),
                        "{name} from {start} at width {width} landed at {} — not a caret stop",
                        d.caret
                    );
                }
            }
        }
    }

    #[test]
    fn no_wysiwyg_motion_is_a_dead_end() {
        // Down held to the bottom of a document reaches the bottom, and Up held
        // to the top reaches the top — from anywhere, at a width that wraps. The
        // invariant above says a motion lands somewhere legal; this one says it
        // gets somewhere at all, which is what a caret pinned at a wrap boundary
        // was quietly failing to do while every assertion around it held.
        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
                   - item one two three four five\n\nlast\n";
        for width in [80, 12] {
            let mut d = wysiwyg_doc("no_dead_end", src);
            d.build_visual(width);
            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
            let (first, last) = (stops[0], stops[stops.len() - 1]);
            for &start in &stops {
                for (name, motion, want) in [
                    (
                        "down",
                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
                        last,
                    ),
                    ("up", |d: &mut Doc| d.move_up(false), first),
                ] {
                    d.caret = start;
                    d.anchor = None;
                    d.goal_col = None;
                    // Every row, plus the presses the edges take, plus slack.
                    for _ in 0..d.vmap.num_rows() + 4 {
                        motion(&mut d);
                    }
                    assert_eq!(
                        d.caret, want,
                        "{name} held from {start} at width {width} never arrived"
                    );
                }
            }
        }
    }
    // ── display columns ──────────────────────────────────────────────────────
    // A `col` is a terminal cell, not a character. The two are the same number
    // for the ASCII the fixtures above are written in, which is how they came
    // apart in the first place: `你` is one character drawn in two cells, so a
    // column counted in characters names a cell the text isn't in — one earlier
    // for every wide character to its left.

    #[test]
    fn a_wide_character_is_two_columns_wide() {
        // The reproduction: `你` is one char and two cells, so the caret just
        // past it drew at column 1 — inside the character it had already left.
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
            d.caret = "".len();
            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
            d.caret = "你好".len();
            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
        }
    }

    #[test]
    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
        // two-cell — measuring six cells one at a time, but the character they
        // spell is drawn in two. Width belongs to the cluster, not the glyph,
        // and the frontends measure it the same way.
        let family = "👨‍👩‍👧";
        for (view, tag) in VIEWS {
            let src = format!("a{family}b\n");
            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
            d.caret = 1 + family.len();
            assert_eq!(
                d.caret_pos(),
                (0, 3),
                "{tag}: 'a' is one cell, the family two"
            );
        }
    }

    #[test]
    fn both_cells_of_a_wide_character_mean_the_character() {
        // Clicking the far half of `好` is still clicking `好`: half a character
        // is not a place the caret can be, so it comes to rest at the
        // character's start — the column it would have been drawn at anyway.
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
            for col in [2, 3] {
                d.caret = 0;
                d.click(0, col, false);
                assert_eq!(d.caret, "".len(), "{tag}: click at col {col}");
                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
            }
            // Past the last cell is the line's end, as it is for ASCII.
            d.click(0, 9, false);
            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
        }
    }

    #[test]
    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
        // The mapping is only a mapping if it inverts: the cell the caret is
        // drawn in has to be the cell that brings it back to the same offset.
        // Over a fixture where a character may be one cell or two, and one
        // codepoint or five.
        use unicode_segmentation::UnicodeSegmentation;

        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";

        let mut d = doc_in(View::Source, "roundtrip_source", src);
        // Every offset the source view's caret can occupy: it steps by grapheme
        // cluster, so those are its boundaries.
        for (off, _) in src
            .grapheme_indices(true)
            .chain(std::iter::once((src.len(), "")))
        {
            d.caret = off;
            let (row, col) = d.caret_pos();
            d.click(row, col, false);
            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
        }

        // And in WYSIWYG, where the offsets the caret can occupy are the map's
        // stops rather than every boundary.
        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
        assert!(stops.len() > 20, "fixture should have plenty of stops");
        for off in stops {
            d.caret = off;
            let (row, col) = d.caret_pos();
            d.click(row, col, false);
            assert_eq!(
                d.caret, off,
                "wysiwyg: {off} → ({row}, {col}) → {}",
                d.caret
            );
        }
    }

    #[test]
    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
        // Down from under `世` lands under the glyph in that cell, not two
        // characters further along the line. The goal is a column, so a line of
        // wide characters and a line of ASCII line up the way they're drawn.
        //
        // The gap differs by view: a bare newline inside a paragraph is a soft
        // break, which WYSIWYG draws as a space on a single row. The views share
        // a grid only where the source's lines are the renderer's rows too.
        for (view, tag) in VIEWS {
            let gap = if view == View::Source { "\n" } else { "\n\n" };
            let src = format!("你好世{gap}abcdef\n");
            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
            d.caret = "你好".len();
            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
            d.move_down(false);
            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
            assert!(
                d.source[d.caret..].starts_with('e'),
                "{tag}: landed on the wrong glyph"
            );
        }
    }

    #[test]
    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
        // Down from column 3 onto `你好`, whose characters start at columns 0
        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
        // between the cells of one character, so the caret rests on it — and on
        // its start, which is the only offset there that is a caret stop.
        for (view, tag) in VIEWS {
            let gap = if view == View::Source { "\n" } else { "\n\n" };
            let src = format!("abcdef{gap}你好\n");
            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
            let line = src.find('').unwrap();
            d.caret = 3;
            d.move_down(false);
            assert_eq!(d.caret, line + "".len(), "{tag}: landed off `好`'s start");
            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
        }
    }

    #[test]
    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
        // The column the cell's text is laid out in is measured in cells, so the
        // caret walking that text has to be too — the two agreeing is the whole
        // point of the grid staying square.
        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
        let at = d.source.find("").unwrap();
        d.caret = at;
        let (row, col) = d.caret_pos();
        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
        // cells further along.
        assert_eq!(col, 2, "the cell's first character");
        d.move_right(false);
        assert_eq!(
            d.caret_pos(),
            (row, 4),
            "`好` is drawn past `你`'s two cells"
        );
        assert_eq!(d.caret, at + "".len());
    }

    // ── active inline marks ───────────────────────────────────────────────────

    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
        let (src, caret) = parse_caret(marked);
        let mut d = doc_in(view, name, &src);
        d.caret = caret;
        d.active_inline_marks().iter().collect()
    }

    /// The marks over the selection `[start, end)`.
    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
        let mut d = doc_in(view, name, src);
        d.anchor = Some(start);
        d.caret = end;
        d.active_inline_marks().iter().collect()
    }

    #[test]
    fn a_caret_in_a_mark_reports_it() {
        for (view, tag) in VIEWS {
            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
            // Plain text under no mark lights nothing — the toolbar's resting state.
            assert_eq!(m("a| **bold** b"), [], "{tag}");
            assert!(m("plain t|ext").is_empty(), "{tag}");
        }
    }

    #[test]
    fn nested_marks_all_report() {
        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
        // the ancestor chain is a chain, and every mark on it is in force.
        for (view, tag) in VIEWS {
            assert_eq!(
                marks(
                    view,
                    &format!("marks_nested_{tag}"),
                    "**bold and *bo|th*** end"
                ),
                [InlineKind::Strong, InlineKind::Emph],
                "{tag}"
            );
        }
    }

    #[test]
    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
        // the first byte of its text and the byte after its last — both inside
        // the mark's span, both places typing lands inside the bold. The offset
        // past the closing delimiter is the next text, and reports nothing.
        let src = "a **bold** b";
        let inner_start = src.find("bold").unwrap(); // 4
        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
            for off in [2, 3, inner_start, inner_end, 9] {
                d.caret = off;
                assert!(
                    d.active_inline_marks().contains(InlineKind::Strong),
                    "{tag}: offset {off} is inside the strong span"
                );
            }
            for off in [0, 1, 10, 11, 12] {
                d.caret = off;
                assert!(
                    !d.active_inline_marks().contains(InlineKind::Strong),
                    "{tag}: offset {off} is outside the strong run"
                );
            }
        }
    }

    #[test]
    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
        // Regression: twig resolves an offset that is one node's end and the
        // next one's start to the node that *starts* there, so `**bold**|\n`
        // isn't bold. With nothing following there's no tie to break and the
        // chain still ended at the mark, which made a trailing `\n` — not the
        // text — decide whether the caret after a bold word reported bold. It's
        // the offset past the mark either way, and typing there is plain either
        // way. A blank document typed into is exactly this shape.
        for (view, tag) in VIEWS {
            let m = |name: String, marked| marks(view, &name, marked);
            assert_eq!(
                m(format!("marks_eob_{tag}"), "**bold**|"),
                [],
                "{tag}: no trailing newline"
            );
            assert_eq!(
                m(format!("marks_eol_{tag}"), "**bold**|\n"),
                [],
                "{tag}: with one"
            );
            // And the last offset that *is* in the mark still is.
            assert_eq!(
                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
                [InlineKind::Strong],
                "{tag}"
            );
        }
    }

    #[test]
    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
        let src = "a **bold** b";
        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
        for (view, tag) in VIEWS {
            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
            // The whole bold word, and a slice of it.
            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
            // Ending exactly at the closing delimiter's start is still all-bold:
            // an exclusive end sits *past* the last selected character, so the
            // question is asked of the character, not the boundary.
            assert_eq!(
                m(b, d_ + 2),
                [InlineKind::Strong],
                "{tag}: through the close"
            );
            // Half in, half out: Bold lit here would claim a press turns it off.
            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
        }
    }

    #[test]
    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
        // Both ends are bold, but the space between them isn't — two runs are two
        // nodes, which is exactly what the node id catches and a kind-only
        // comparison would not.
        let src = "**one** **two**";
        for (view, tag) in VIEWS {
            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
        }
    }

    #[test]
    fn marks_read_the_document_as_it_is_edited() {
        // The point of asking twig every frame instead of caching: the answer has
        // to follow the toggle that changed it.
        let mut d = wysiwyg_doc("marks_live", "one two\n");
        d.anchor = Some(0);
        d.caret = 3;
        assert!(d.active_inline_marks().is_empty(), "plain to start");
        d.toggle(InlineKind::Strong);
        assert_eq!(d.source, "**one** two\n");
        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
        assert!(d.active_inline_marks().contains(InlineKind::Strong));
        d.toggle(InlineKind::Strong);
        assert!(d.active_inline_marks().is_empty(), "and off again");
    }

    #[test]
    fn a_link_is_not_an_inline_mark() {
        // `link`/`str` are inline nodes, but nothing on the inline toolbar
        // toggles them — a set with a "link mark" in it would have no button.
        for (view, tag) in VIEWS {
            assert_eq!(
                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
                [],
                "{tag}"
            );
        }
    }

    // ── blank documents ───────────────────────────────────────────────────────

    #[test]
    fn a_blank_document_is_untitled_empty_and_markdown() {
        let mut d = Doc::blank().unwrap();
        assert!(d.is_untitled());
        assert_eq!(d.path, PathBuf::new());
        assert_eq!(
            d.file_name(),
            "untitled",
            "the header has to show something"
        );
        assert_eq!(d.format_name(), "markdown");
        assert_eq!(d.source, "");
        assert!(!d.dirty, "nothing typed yet is nothing to lose");
        assert_eq!(d.disk_state(), DiskState::Untitled);
        // And it's a document you can be in: the default view renders it.
        d.build_visual(80);
        assert_eq!(d.caret, 0);
    }

    #[test]
    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
        let mut d = Doc::blank().unwrap();
        d.insert("hello");
        assert!(d.dirty);
        d.save();
        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
        assert!(d.dirty, "it must not come away believing it saved");
        assert!(d.is_untitled(), "and it still has no file");
    }

    #[test]
    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
        let p = temp_path("blank_save_as");
        let mut d = Doc::blank().unwrap();
        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
        // be kept literal (`\#`); this test is about save-as, not escaping (which
        // has its own test), so it types nothing that escaping would touch.
        d.insert("hi");
        d.save_as(p.clone());
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
        assert!(!d.is_untitled());
        assert!(!d.dirty);
        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
        assert_eq!(
            d.disk_state(),
            DiskState::Unchanged,
            "the watermark is stamped"
        );
        // And ⌘S is a plain save from here on.
        d.insert("!");
        d.save();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
        let _ = std::fs::remove_file(&p);
    }

    // ── save as ───────────────────────────────────────────────────────────────

    /// A unique path in the temp dir that no fixture wrote — a Save As target.
    fn temp_path(name: &str) -> PathBuf {
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut p = std::env::temp_dir();
        p.push(format!("leaf_test_target_{name}_{seq}.md"));
        let _ = std::fs::remove_file(&p);
        p
    }

    #[test]
    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
        let mut d = doc_with("save_as_move", "original\n");
        let old = d.path.clone();
        let new = temp_path("save_as_move");
        d.insert("edited: ");
        d.save_as(new.clone());

        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
        assert_eq!(
            std::fs::read_to_string(&old).unwrap(),
            "original\n",
            "Save As doesn't touch the file it came from"
        );
        assert_eq!(d.path, new, "the document moved");
        assert!(!d.dirty);
        assert_eq!(
            d.status.as_deref(),
            Some(&*format!("saved {}", d.file_name()))
        );

        // Every later save follows it, which is the whole difference from a copy.
        d.caret = 0;
        d.insert("re-");
        d.save();
        assert_eq!(
            std::fs::read_to_string(&new).unwrap(),
            "re-edited: original\n"
        );
        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
        let _ = std::fs::remove_file(&new);
    }

    #[test]
    fn save_as_overwrites_an_existing_target() {
        // The picker already asked; asking again down here is the same question
        // twice, and the second one has no way to be answered.
        let new = temp_path("save_as_over");
        std::fs::write(&new, "theirs\n").unwrap();
        let mut d = doc_with("save_as_over", "ours\n");
        d.save_as(new.clone());
        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
        let _ = std::fs::remove_file(&new);
    }

    #[test]
    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
        let mut d = doc_with("save_as_fail", "body\n");
        let old = d.path.clone();
        d.insert("x");
        // A directory that doesn't exist: the write can't land.
        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
        d.save_as(bad);

        assert_eq!(
            d.path, old,
            "the document must not move to a file that isn't there"
        );
        assert!(d.dirty, "and must not believe it saved");
        assert!(
            d.status.as_deref().unwrap().starts_with("save failed:"),
            "the same failure a plain save reports, got {:?}",
            d.status
        );
        // The original is still the document's file, and still saveable.
        d.save();
        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
        assert!(!d.dirty);
    }

    #[test]
    fn save_as_renames_without_reparsing_the_format() {
        // `.dj` on the name doesn't make the buffer djot: it was parsed as
        // Markdown and still is, and saying otherwise would be a conversion the
        // user never asked for (and an undo history thrown away to do it).
        let mut d = doc_with("save_as_format", "**b**\n");
        let mut new = temp_path("save_as_format");
        new.set_extension("dj");
        d.save_as(new.clone());
        assert_eq!(d.format_name(), "markdown");
        let _ = std::fs::remove_file(&new);
    }

    // ── external change / reload ──────────────────────────────────────────────

    #[test]
    fn an_untouched_file_reports_unchanged() {
        let mut d = doc_with("disk_clean", "body\n");
        assert_eq!(d.disk_state(), DiskState::Unchanged);
        // Editing the buffer is not editing the file.
        d.insert("x");
        assert_eq!(d.disk_state(), DiskState::Unchanged);
        assert!(d.dirty);
        // Saving re-stamps the watermark rather than reporting our own bytes back.
        d.save();
        assert_eq!(d.disk_state(), DiskState::Unchanged);
    }

    #[test]
    fn a_file_written_underneath_reports_changed() {
        let mut d = doc_with("disk_changed", "body\n");
        std::fs::write(&d.path, "someone else\n").unwrap();
        assert_eq!(d.disk_state(), DiskState::Changed);
        // Dirty *and* changed is the clobber: both halves are readable, and
        // leaf-core takes neither side.
        d.insert("x");
        assert!(d.dirty && d.disk_state() == DiskState::Changed);
        // Saving anyway is allowed — the frontend asked, or chose not to.
        d.save();
        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
        assert_eq!(d.disk_state(), DiskState::Unchanged);
    }

    #[test]
    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
        // The hash is what makes this honest: the file was written (a fresh
        // mtime), and nothing about the document is stale.
        let d = doc_with("disk_same_bytes", "body\n");
        std::fs::write(&d.path, "body\n").unwrap();
        assert_eq!(d.disk_state(), DiskState::Unchanged);
    }

    #[test]
    fn a_deleted_file_reports_missing() {
        let mut d = doc_with("disk_missing", "body\n");
        std::fs::remove_file(&d.path).unwrap();
        assert_eq!(d.disk_state(), DiskState::Missing);
        // A save recreates it, and the document is whole again.
        d.save();
        assert_eq!(d.disk_state(), DiskState::Unchanged);
        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
    }

    #[test]
    fn reload_replaces_the_document_with_the_file() {
        for (view, tag) in VIEWS {
            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
            d.insert("edited ");
            assert!(d.dirty);
            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
            d.reload();

            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
            assert!(!d.dirty, "{tag}: the file is what we have");
            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
            assert_eq!(
                d.status.as_deref(),
                Some(&*format!("reloaded {}", d.file_name()))
            );
            // The reloaded tree is live, not the old parse.
            d.caret = d.source.find("three").unwrap();
            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
        }
    }

    #[test]
    fn reload_clamps_the_caret_and_drops_the_selection() {
        let mut d = doc_with("reload_caret", "a long first line\n");
        d.caret = 12;
        d.anchor = Some(4);
        std::fs::write(&d.path, "short\n").unwrap();
        d.reload();
        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
        assert_eq!(
            d.anchor, None,
            "a selection over bytes that changed is a lie"
        );
        assert!(d.selection().is_none());

        // A caret the file still has room for stays put.
        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
        d.caret = 2;
        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
        d.reload();
        assert_eq!(d.caret, 2);
    }

    #[test]
    fn reload_drops_the_undo_history() {
        // twig's stack belongs to the buffer, and these are different bytes:
        // replaying a step recorded against the old ones would corrupt the file.
        let mut d = doc_with("reload_undo", "body\n");
        d.insert("x");
        std::fs::write(&d.path, "replaced\n").unwrap();
        d.reload();
        d.undo();
        assert_eq!(
            d.source, "replaced\n",
            "an undo must not resurrect the old buffer"
        );
        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
    }

    #[test]
    fn a_reload_that_cant_read_leaves_the_document_alone() {
        let mut d = doc_with("reload_gone", "body\n");
        d.insert("x");
        std::fs::remove_file(&d.path).unwrap();
        d.reload();
        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
        assert!(d.dirty);
        assert!(
            d.status.as_deref().unwrap().starts_with("reload failed:"),
            "{:?}",
            d.status
        );

        // And an untitled document has nothing to reload from.
        let mut d = Doc::blank().unwrap();
        d.insert("typed");
        d.reload();
        assert_eq!(d.source, "typed");
        assert_eq!(d.status.as_deref(), Some("no file to reload"));
    }
}