writ 0.17.0

A hybrid markdown editor combining raw text editing with live inline rendering
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
mod action;
mod theme;

pub use action::Direction;
pub use theme::EditorTheme;

use crate::buffer::Buffer;
use crate::cursor::{Cursor, Selection, grapheme_column, offset_at_column, prev_grapheme_boundary};
use crate::marker::{LineMarkers, MarkerKind, OrderedMarker, UnorderedMarker};
use crate::table::{RowKind, TableCell, TableInfo, row_kind_at_line};

/// Context about the line at the cursor, used by smart editing actions.
struct LineContext {
    /// The current line's markers.
    line: LineMarkers,
}

/// Cached tab cycle states for a specific line.
#[derive(Clone, Default)]
struct TabCycleCache {
    /// The line index this cache is for.
    line_idx: usize,
    /// The cached cycle states.
    states: Vec<String>,
}

/// Ascend from `node` (inclusive) through its parents, returning the first node
/// whose kind is `kind`.
fn ancestor_of_kind<'a>(node: tree_sitter::Node<'a>, kind: &str) -> Option<tree_sitter::Node<'a>> {
    let mut current = Some(node);
    while let Some(n) = current {
        if n.kind() == kind {
            return Some(n);
        }
        current = n.parent();
    }
    None
}

/// Byte indices of unescaped `|` characters in `s` (a `|` is escaped when preceded
/// by an odd number of backslashes).
fn unescaped_pipe_indices(s: &str) -> Vec<usize> {
    let bytes = s.as_bytes();
    let mut out = Vec::new();
    for i in 0..bytes.len() {
        if bytes[i] == b'|' {
            let mut backslashes = 0;
            let mut j = i;
            while j > 0 && bytes[j - 1] == b'\\' {
                backslashes += 1;
                j -= 1;
            }
            if backslashes % 2 == 0 {
                out.push(i);
            }
        }
    }
    out
}

/// Column count of a candidate pipe-header row: split the trimmed line on its
/// unescaped pipes and drop the empty leading/trailing segments the surrounding
/// pipes produce. `pipes` are byte indices into `trimmed`.
/// Cell contents of a pipe row (segments between pipes), dropping the empty leading/
/// trailing segments produced by the outer `|` bars. Index 0 is the cell after the
/// leading pipe (i.e. between `pipes[0]` and `pipes[1]` for a bounded row).
fn pipe_row_cells<'a>(trimmed: &'a str, pipes: &[usize]) -> Vec<&'a str> {
    let mut segs: Vec<&str> = Vec::with_capacity(pipes.len() + 1);
    let mut start = 0;
    for &p in pipes {
        segs.push(&trimmed[start..p]);
        start = p + 1;
    }
    segs.push(&trimmed[start..]);
    if segs.first().is_some_and(|s| s.is_empty()) {
        segs.remove(0);
    }
    if segs.last().is_some_and(|s| s.is_empty()) {
        segs.pop();
    }
    segs
}

fn pipe_row_ncols(trimmed: &str, pipes: &[usize]) -> usize {
    pipe_row_cells(trimmed, pipes).len()
}

/// Whether a trimmed line is a GFM table delimiter row (only `| - : ` chars, with
/// at least one `-`).
fn looks_like_delimiter_row(trimmed: &str) -> bool {
    !trimmed.is_empty()
        && trimmed.contains('-')
        && trimmed
            .chars()
            .all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t'))
}

/// Core editing state that can be used without GPUI context.
/// This contains the buffer and selection, and all editing logic.
pub struct EditorState {
    pub buffer: Buffer,
    pub selection: Selection,
    /// Cached tab cycle states to avoid recalculating mid-cycle.
    tab_cycle_cache: Option<TabCycleCache>,
    /// Sticky vertical-movement goal: `(grapheme_column, offset_it_landed_at)`. Reused by
    /// the next Up/Down only if the cursor is still at that offset, so passing through a
    /// short line doesn't lose the original column; any other move invalidates it for free.
    goal_column: Option<(usize, usize)>,
}

impl EditorState {
    pub fn new(content: &str) -> Self {
        let buffer: Buffer = content.parse().unwrap_or_default();
        Self {
            buffer,
            selection: Selection::new(0, 0),
            tab_cycle_cache: None,
            goal_column: None,
        }
    }

    pub fn cursor(&self) -> Cursor {
        self.selection.cursor()
    }

    pub fn text(&self) -> String {
        self.buffer.text()
    }

    /// Set cursor position by byte offset.
    pub fn set_cursor(&mut self, offset: usize) {
        let offset = offset.min(self.buffer.len_bytes());
        self.selection = Selection::new(offset, offset);
    }

    /// Collapse the selection onto a single cursor.
    fn set_cursor_to(&mut self, c: Cursor) {
        self.selection = Selection::new(c.offset, c.offset);
    }

    /// Compute the cursor after moving one step in `direction`. Vertical moves keep a
    /// sticky goal column (`&mut self` to read/update it); other moves leave it stale,
    /// and it self-invalidates because the cursor no longer sits at its landing offset.
    pub fn cursor_in_direction(&mut self, direction: Direction) -> Cursor {
        let c = self.cursor();
        if matches!(direction, Direction::Up | Direction::Down) {
            let line = self.buffer.byte_to_line(c.offset);
            let column = match self.goal_column {
                Some((col, at)) if at == c.offset => col,
                _ => grapheme_column(&self.buffer, c.offset),
            };
            let offset = if direction == Direction::Up {
                if line == 0 {
                    Cursor::start().offset
                } else {
                    offset_at_column(&self.buffer, line - 1, column)
                }
            } else if line >= self.buffer.line_count().saturating_sub(1) {
                Cursor::end(&self.buffer).offset
            } else {
                offset_at_column(&self.buffer, line + 1, column)
            };
            self.goal_column = Some((column, offset));
            return Cursor { offset };
        }
        match direction {
            Direction::Left => c.move_left(&self.buffer),
            Direction::Right => c.move_right(&self.buffer),
            Direction::LineStart => c.move_to_line_start(&self.buffer),
            Direction::LineEnd => c.move_to_line_end(&self.buffer),
            Direction::DocStart => Cursor::start(),
            Direction::DocEnd => Cursor::end(&self.buffer),
            Direction::Up | Direction::Down => unreachable!("handled above"),
        }
    }

    /// Move cursor left by one character.
    pub fn move_left(&mut self) {
        let c = self.cursor_in_direction(Direction::Left);
        self.set_cursor_to(c);
    }

    /// Move cursor right by one character.
    pub fn move_right(&mut self) {
        let c = self.cursor_in_direction(Direction::Right);
        self.set_cursor_to(c);
    }

    /// Move cursor up by one line.
    pub fn move_up(&mut self) {
        let c = self.cursor_in_direction(Direction::Up);
        self.set_cursor_to(c);
    }

    /// Move cursor down by one line.
    pub fn move_down(&mut self) {
        let c = self.cursor_in_direction(Direction::Down);
        self.set_cursor_to(c);
    }

    /// Move cursor to start of current line.
    pub fn move_to_line_start(&mut self) {
        self.set_cursor_to(self.cursor().move_to_line_start(&self.buffer));
    }

    /// Move cursor to end of current line.
    pub fn move_to_line_end(&mut self) {
        self.set_cursor_to(self.cursor().move_to_line_end(&self.buffer));
    }

    /// Insert text at the current cursor position.
    pub fn insert_text(&mut self, text: &str) {
        // Clear tab cycle cache since content is changing
        self.tab_cycle_cache = None;
        let cursor_before = self.cursor().offset;
        let insert_pos = if !self.selection.is_collapsed() {
            let range = self.selection.range();
            self.buffer.delete(range.clone(), cursor_before);
            range.start
        } else {
            cursor_before
        };
        self.buffer.insert(insert_pos, text, insert_pos);
        let new_pos = insert_pos + text.len();
        self.selection = Selection::new(new_pos, new_pos);

        // After inserting, propagate checkbox state if this line has a checkbox.
        // This handles the case where tab cycling created an incomplete checkbox line
        // (e.g., "- [ ] ") and typing content makes it parseable by tree-sitter.
        self.propagate_checkbox_after_edit();
        // Growing a table header's column count grows the rest of the table to match.
        // Only for single-line inserts (typing) — a multi-line paste isn't a column edit.
        if !text.contains('\n') {
            self.maybe_sync_table_columns(insert_pos);
        }
    }

    fn find_line_at(&self, byte_pos: usize) -> Option<(usize, LineMarkers)> {
        let idx = self.buffer.byte_to_line(byte_pos);
        if idx < self.buffer.line_count() {
            Some((idx, self.buffer.line_markers(idx)))
        } else {
            None
        }
    }

    /// Check if the cursor is inside a code block (between opening and closing fences,
    /// or after an opening fence with no closing fence yet).
    pub fn cursor_in_code_block(&self) -> bool {
        let Some(tree) = self.buffer.tree() else {
            return false;
        };

        let cursor_offset = self.cursor().offset;
        let root = tree.block_tree().root_node();

        // Find the deepest node at the cursor position and walk up looking for fenced_code_block
        let Some(node) = root.descendant_for_byte_range(cursor_offset, cursor_offset) else {
            return false;
        };

        ancestor_of_kind(node, "fenced_code_block").is_some()
    }

    /// Get context about the line at the cursor.
    /// Returns None if the cursor is not on a valid line.
    fn line_context(&self) -> Option<LineContext> {
        let cursor_offset = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor_offset);
        if line_idx >= self.buffer.line_count() {
            return None;
        }
        let line = self.buffer.line_markers(line_idx);

        Some(LineContext { line })
    }

    /// Auto-insert space after `>` if it just became a blockquote marker.
    /// Returns true if a space was inserted.
    pub fn maybe_complete_blockquote_marker(&mut self) -> bool {
        let cursor_pos = self.cursor().offset;
        if cursor_pos == 0 {
            return false;
        }

        if self.buffer.byte_at(cursor_pos - 1) != Some(b'>') {
            return false;
        }

        if self.buffer.byte_at(cursor_pos) == Some(b' ') {
            return false;
        }

        let line_idx = self.buffer.byte_to_line(cursor_pos);
        if line_idx >= self.buffer.line_count() {
            return false;
        }
        let line = self.buffer.line_markers(line_idx);

        let has_blockquote = line
            .markers
            .iter()
            .any(|m| matches!(m.kind, MarkerKind::BlockQuote));

        if !has_blockquote {
            return false;
        }

        self.insert_text(" ");
        true
    }

    /// After typing ` or ~, check if we just completed "```" or "~~~" at line start
    /// and auto-insert the closing fence.
    pub fn maybe_complete_code_fence(&mut self) {
        let cursor_pos = self.cursor().offset;
        if cursor_pos < 3 {
            return;
        }

        // Check we just typed 3 of the same fence character
        let fence_char = self.buffer.byte_at(cursor_pos - 1);
        if fence_char != Some(b'`') && fence_char != Some(b'~') {
            return;
        }
        if self.buffer.byte_at(cursor_pos - 2) != fence_char
            || self.buffer.byte_at(cursor_pos - 3) != fence_char
        {
            return;
        }

        // Check this is at the start of a line (possibly after blockquote markers)
        let line_idx = self.buffer.byte_to_line(cursor_pos);
        let line_start = self.buffer.line_to_byte(line_idx);
        let before_fence = self.buffer.slice_cow(line_start..(cursor_pos - 3));
        let trimmed = before_fence.trim();

        // Allow only whitespace or blockquote markers before the fence
        if !trimmed.is_empty() && !trimmed.chars().all(|c| c == '>') {
            return;
        }

        // Insert newline + closing fence, cursor stays after opening fence
        let closing = if fence_char == Some(b'`') {
            "\n```"
        } else {
            "\n~~~"
        };
        self.buffer.insert(cursor_pos, closing, cursor_pos);
    }

    /// Try to insert a space. Returns false if space should be ignored
    /// (at line start, or at blockquote content start outside code blocks).
    pub fn try_insert_space(&mut self) -> bool {
        if self.cursor_in_code_block() {
            self.insert_text(" ");
            return true;
        }

        let cursor = self.cursor();
        let line_start = cursor.move_to_line_start(&self.buffer).offset;

        if cursor.offset == line_start || self.cursor_at_blockquote_content_start() {
            return false;
        }

        self.insert_text(" ");
        true
    }

    /// Check if cursor is at the content start of a blockquote-only line.
    /// Used to prevent inserting spaces/tabs at the "beginning" of blockquote content.
    fn cursor_at_blockquote_content_start(&self) -> bool {
        let cursor_pos = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor_pos);
        if line_idx >= self.buffer.line_count() {
            return false;
        }
        let line = self.buffer.line_markers(line_idx);

        if !line.is_blockquote_only() {
            return false;
        }

        if let Some(marker_range) = line.marker_range() {
            cursor_pos == marker_range.end
        } else {
            false
        }
    }

    /// Tab: cycle forward through nesting states based on tree-sitter context.
    pub fn tab(&mut self) {
        if self.table_cell_nav(true) {
            return;
        }
        let Some((states, current_idx, prefix_end)) = self.get_tab_cycle_state() else {
            return;
        };

        if states.len() <= 1 {
            return;
        }

        let next_idx = (current_idx + 1) % states.len();
        self.set_line_prefix(&states[next_idx], prefix_end);

        // After changing structure, propagate checkbox state if this line has a checkbox
        self.propagate_checkbox_after_edit();
    }

    /// Shift+Tab: cycle backward through nesting states.
    fn shift_tab_cycle(&mut self) {
        let Some((states, current_idx, prefix_end)) = self.get_tab_cycle_state() else {
            return;
        };

        if states.len() <= 1 {
            return;
        }

        let prev_idx = if current_idx == 0 {
            states.len() - 1
        } else {
            current_idx - 1
        };
        self.set_line_prefix(&states[prev_idx], prefix_end);

        // After changing structure, propagate checkbox state if this line has a checkbox
        self.propagate_checkbox_after_edit();
    }

    /// Get tab cycle states, using cache if available for current line.
    /// Returns (states, current_idx, prefix_end) where prefix_end is where the prefix ends.
    fn get_tab_cycle_state(&mut self) -> Option<(Vec<String>, usize, usize)> {
        let cursor_offset = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor_offset);
        let line_start = self.buffer.line_to_byte(line_idx);

        // Get current line's checkbox state to pass to state builder
        let current_checkbox = self.buffer.line_markers(line_idx).checkbox();

        // Reuse the cache only when it's for this line; otherwise (wrong line or no
        // cache) rebuild and store.
        let states = if self
            .tab_cycle_cache
            .as_ref()
            .is_some_and(|c| c.line_idx == line_idx)
        {
            self.tab_cycle_cache.as_ref().unwrap().states.clone()
        } else {
            let states = self.build_cycle_states_from_tree(cursor_offset, current_checkbox);
            self.tab_cycle_cache = Some(TabCycleCache {
                line_idx,
                states: states.clone(),
            });
            states
        };

        if states.len() <= 1 {
            return None;
        }

        // Find which state matches the current line's prefix
        // We check if the line starts with each state (longest match wins)
        let line_end = self
            .buffer
            .line_to_byte(line_idx + 1)
            .min(self.buffer.len_bytes());
        let line_text = self.buffer.slice_cow(line_start..line_end);

        let mut best_match: Option<(usize, &str)> = None;
        for (idx, state) in states.iter().enumerate() {
            if line_text.starts_with(state)
                && (best_match.is_none() || state.len() > best_match.unwrap().1.len())
            {
                best_match = Some((idx, state));
            }
        }

        let (current_idx, prefix_end) = match best_match {
            Some((idx, state)) => (idx, line_start + state.len()),
            None => (0, line_start), // Default to empty prefix at index 0
        };

        Some((states, current_idx, prefix_end))
    }

    /// Build tab cycle states by walking up the tree-sitter parse tree.
    /// The cycle is determined by context ABOVE the current line, not by current line content.
    /// If `checkbox_state` is Some, task list markers will use that state instead of the parent's.
    pub fn build_cycle_states_from_tree(
        &self,
        cursor_offset: usize,
        checkbox_state: Option<bool>,
    ) -> Vec<String> {
        let Some(tree) = self.buffer.tree() else {
            return vec![String::new()];
        };

        let root = tree.block_tree().root_node();
        let cursor_line_idx = self.buffer.byte_to_line(cursor_offset);

        let line_start = self.buffer.line_to_byte(cursor_line_idx);
        let lookup_offset = if line_start > 0 { line_start - 1 } else { 0 };
        let node = root.descendant_for_byte_range(lookup_offset, lookup_offset);

        let Some(node) = node else {
            return vec![String::new()];
        };

        let context_node = if self.is_in_error_node(node) {
            self.find_context_from_error(node).unwrap_or(node)
        } else {
            node
        };

        let mut nodes_to_process: Vec<tree_sitter::Node> = Vec::new();
        let mut blockquote_prefix = String::new();
        let mut current = Some(context_node);

        while let Some(n) = current {
            if n.kind() == "block_quote" {
                if let Some(marker_node) = n
                    .children(&mut n.walk())
                    .find(|c| c.kind() == "block_quote_marker")
                {
                    let marker_text = self
                        .buffer
                        .slice_cow(marker_node.start_byte()..marker_node.end_byte());
                    blockquote_prefix = format!("{}{}", marker_text, blockquote_prefix);
                }
            } else if n.kind() == "list_item" {
                nodes_to_process.push(n);
            }
            current = n.parent();
        }

        let mut list_levels: Vec<(usize, String, usize, bool)> = Vec::new();

        for n in nodes_to_process {
            let mut marker_text = String::new();
            let mut list_marker_len = 0;
            let mut marker_start = 0;
            let mut is_ordered = false;

            for child in n.children(&mut n.walk()) {
                match child.kind() {
                    "list_marker_minus" | "list_marker_plus" | "list_marker_star" => {
                        marker_start = child.start_byte();
                        let text = self.buffer.slice_cow(child.start_byte()..child.end_byte());
                        list_marker_len = text.len();
                        marker_text.push_str(&text);
                    }
                    "list_marker_dot" | "list_marker_parenthesis" => {
                        marker_start = child.start_byte();
                        let text = self.buffer.slice_cow(child.start_byte()..child.end_byte());
                        list_marker_len = text.len();
                        marker_text.push_str(&text);
                        is_ordered = true;
                    }
                    "task_list_marker_checked" | "task_list_marker_unchecked" => {
                        // Use the current line's checkbox state if provided.
                        // If None (line has no checkbox yet), default to unchecked.
                        let checkbox_text = match checkbox_state {
                            Some(true) => "[x]",
                            Some(false) | None => "[ ]",
                        };
                        marker_text.push_str(checkbox_text);
                        marker_text.push(' ');
                    }
                    _ => {}
                }
            }

            if !marker_text.is_empty() {
                let line_idx = self.buffer.byte_to_line(marker_start);
                let line_start = self.buffer.line_to_byte(line_idx);
                let absolute_indent = marker_start - line_start;
                let indent = absolute_indent.saturating_sub(blockquote_prefix.len());
                list_levels.push((indent, marker_text, list_marker_len, is_ordered));
            }
        }

        if list_levels.is_empty() && blockquote_prefix.is_empty() {
            return vec![String::new()];
        }

        list_levels.reverse();

        let mut states = Vec::new();

        if !blockquote_prefix.is_empty() {
            states.push(blockquote_prefix.clone());
        }

        for (indent, marker, list_marker_len, is_ordered) in &list_levels {
            let sibling_marker = if *is_ordered {
                Self::increment_ordered_marker(marker)
            } else {
                marker.clone()
            };
            states.push(format!(
                "{}{}{}",
                blockquote_prefix,
                " ".repeat(*indent),
                sibling_marker
            ));

            states.push(format!(
                "{}{}",
                blockquote_prefix,
                " ".repeat(indent + list_marker_len)
            ));
        }

        if let Some((deepest_indent, deepest_marker, list_marker_len, is_ordered)) =
            list_levels.last()
        {
            let deeper_indent = deepest_indent + list_marker_len;
            let nested_marker = if *is_ordered {
                Self::reset_ordered_marker(deepest_marker)
            } else {
                deepest_marker.clone()
            };
            states.push(format!(
                "{}{}{}",
                blockquote_prefix,
                " ".repeat(deeper_indent),
                nested_marker
            ));
        }

        states.push(String::new());
        states
    }

    /// Split an ordered marker (`1.`, `10)`) into its number and the suffix after the digits
    /// (`.`/`)`). `None` when there's no leading digit run.
    fn split_ordered_marker(marker: &str) -> Option<(usize, &str)> {
        let num_end = marker
            .find(|c: char| !c.is_ascii_digit())
            .unwrap_or(marker.len());
        if num_end == 0 {
            return None;
        }
        let num = marker[..num_end].parse().unwrap_or(1);
        Some((num, &marker[num_end..]))
    }

    fn increment_ordered_marker(marker: &str) -> String {
        match Self::split_ordered_marker(marker) {
            Some((num, suffix)) => format!("{}{suffix}", num + 1),
            None => marker.to_string(),
        }
    }

    fn reset_ordered_marker(marker: &str) -> String {
        match Self::split_ordered_marker(marker) {
            Some((_, suffix)) => format!("1{suffix}"),
            None => marker.to_string(),
        }
    }

    fn is_in_error_node(&self, node: tree_sitter::Node) -> bool {
        ancestor_of_kind(node, "ERROR").is_some()
    }

    fn find_context_from_error<'a>(
        &self,
        node: tree_sitter::Node<'a>,
    ) -> Option<tree_sitter::Node<'a>> {
        let mut current = Some(node);
        while let Some(n) = current {
            if n.kind() == "ERROR" {
                if let Some(prev) = n.prev_sibling() {
                    return self.find_last_list_item(prev);
                }
                return None;
            }
            current = n.parent();
        }
        None
    }

    fn find_last_list_item<'a>(
        &self,
        node: tree_sitter::Node<'a>,
    ) -> Option<tree_sitter::Node<'a>> {
        let mut result: Option<tree_sitter::Node<'a>> = None;
        if node.kind() == "list_item" {
            result = Some(node);
        }
        let child_count = node.child_count();
        for i in (0..child_count).rev() {
            if let Some(child) = node.child(i as u32)
                && let Some(found) = self.find_last_list_item(child)
            {
                return Some(found);
            }
        }
        result
    }

    /// Find the list_item node containing the given byte offset.
    fn list_item_at(&self, byte_offset: usize) -> Option<tree_sitter::Node<'_>> {
        let tree = self.buffer.tree()?;
        let root = tree.block_tree().root_node();
        let node = root.descendant_for_byte_range(byte_offset, byte_offset)?;

        ancestor_of_kind(node, "list_item")
    }

    /// Find the checkbox marker among a list_item's direct children, if any.
    /// Returns (checkbox_byte_offset, is_checked).
    fn direct_checkbox(&self, list_item: tree_sitter::Node) -> Option<(usize, bool)> {
        let mut cursor = list_item.walk();
        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                match child.kind() {
                    "task_list_marker_checked" => return Some((child.start_byte(), true)),
                    "task_list_marker_unchecked" => return Some((child.start_byte(), false)),
                    _ => {}
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
        None
    }

    /// Find all checkboxes nested within a list_item node.
    /// Returns Vec of (checkbox_byte_offset, is_checked).
    fn find_nested_checkboxes(&self, list_item_node: tree_sitter::Node) -> Vec<(usize, bool)> {
        let mut checkboxes = Vec::new();
        let mut cursor = list_item_node.walk();

        loop {
            let node = cursor.node();
            match node.kind() {
                "task_list_marker_checked" => {
                    checkboxes.push((node.start_byte(), true));
                }
                "task_list_marker_unchecked" => {
                    checkboxes.push((node.start_byte(), false));
                }
                _ => {}
            }

            if cursor.goto_first_child() {
                continue;
            }
            if cursor.goto_next_sibling() {
                continue;
            }
            loop {
                if !cursor.goto_parent() {
                    return checkboxes;
                }
                if cursor.node().id() == list_item_node.id() {
                    return checkboxes;
                }
                if cursor.goto_next_sibling() {
                    break;
                }
            }
        }
    }

    /// Build full nested context markers by walking up the tree-sitter tree.
    /// Returns markers from outermost to innermost (e.g., `> - [x] - [ ]`).
    /// The `(list_marker, checkbox)` markers of a `list_item` node (each `None` if
    /// absent), from its direct children. Ordered/unordered marker style and the ordinal
    /// number are read off the marker token.
    fn list_item_markers(
        &self,
        item: tree_sitter::Node,
    ) -> (Option<MarkerKind>, Option<MarkerKind>) {
        let mut list_marker: Option<MarkerKind> = None;
        let mut checkbox: Option<MarkerKind> = None;
        let mut cursor = item.walk();
        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                match child.kind() {
                    "task_list_marker_checked" => {
                        checkbox = Some(MarkerKind::Checkbox { checked: true });
                    }
                    "task_list_marker_unchecked" => {
                        checkbox = Some(MarkerKind::Checkbox { checked: false });
                    }
                    "list_marker_minus" => {
                        list_marker = Some(MarkerKind::ListItem {
                            ordered: false,
                            unordered_marker: Some(UnorderedMarker::Minus),
                            ordered_marker: None,
                            number: None,
                        });
                    }
                    "list_marker_star" => {
                        list_marker = Some(MarkerKind::ListItem {
                            ordered: false,
                            unordered_marker: Some(UnorderedMarker::Star),
                            ordered_marker: None,
                            number: None,
                        });
                    }
                    "list_marker_plus" => {
                        list_marker = Some(MarkerKind::ListItem {
                            ordered: false,
                            unordered_marker: Some(UnorderedMarker::Plus),
                            ordered_marker: None,
                            number: None,
                        });
                    }
                    "list_marker_dot" | "list_marker_parenthesis" => {
                        let marker_text =
                            self.buffer.slice_cow(child.start_byte()..child.end_byte());
                        let number = marker_text
                            .trim()
                            .chars()
                            .take_while(|c| c.is_ascii_digit())
                            .collect::<String>()
                            .parse::<u32>()
                            .ok();
                        let ordered_marker = Some(if child.kind() == "list_marker_dot" {
                            OrderedMarker::Dot
                        } else {
                            OrderedMarker::Parenthesis
                        });
                        list_marker = Some(MarkerKind::ListItem {
                            ordered: true,
                            unordered_marker: None,
                            ordered_marker,
                            number,
                        });
                    }
                    _ => {}
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
        (list_marker, checkbox)
    }

    pub fn build_nested_context(&self, cursor_offset: usize) -> Vec<MarkerKind> {
        let Some(tree) = self.buffer.tree() else {
            return Vec::new();
        };

        let root = tree.block_tree().root_node();

        // Handle edge case: cursor at end of file
        let lookup_offset = if cursor_offset > 0
            && root
                .descendant_for_byte_range(cursor_offset, cursor_offset)
                .map(|n| n.kind() == "document")
                .unwrap_or(true)
        {
            cursor_offset - 1
        } else {
            cursor_offset
        };

        let Some(node) = root.descendant_for_byte_range(lookup_offset, lookup_offset) else {
            return Vec::new();
        };

        // Walk up from current node, collecting context from each relevant ancestor
        let mut markers_reversed = Vec::new();
        let mut current = Some(node);

        while let Some(n) = current {
            match n.kind() {
                "block_quote" => {
                    markers_reversed.push(MarkerKind::BlockQuote);
                }
                "list_item" => {
                    // Reversed order (checkbox then list_marker); the whole vec is
                    // reversed at the end, yielding list_marker then checkbox (i.e. "- [x]").
                    let (list_marker, checkbox) = self.list_item_markers(n);
                    if let Some(cb) = checkbox {
                        markers_reversed.push(cb);
                    }
                    if let Some(lm) = list_marker {
                        markers_reversed.push(lm);
                    }
                }
                "fenced_code_block" => {
                    // Find info_string for language
                    let mut cursor = n.walk();
                    let mut language = None;
                    if cursor.goto_first_child() {
                        loop {
                            let child = cursor.node();
                            if child.kind() == "info_string" {
                                language = Some(
                                    self.buffer
                                        .slice_cow(child.start_byte()..child.end_byte())
                                        .to_string(),
                                );
                                break;
                            }
                            if !cursor.goto_next_sibling() {
                                break;
                            }
                        }
                    }
                    markers_reversed.push(MarkerKind::CodeBlockFence {
                        language,
                        is_opening: true,
                    });
                }
                _ => {}
            }
            current = n.parent();
        }

        // Reverse to get outermost-to-innermost order
        markers_reversed.reverse();
        markers_reversed
    }

    /// Find the parent list_item's checkbox, if any.
    /// Returns (checkbox_byte_offset, is_checked).
    fn find_parent_checkbox(&self, list_item_start: usize) -> Option<(usize, bool)> {
        let our_list_item = self.list_item_at(list_item_start)?;

        // Walk up to find parent list_item, then read its direct checkbox
        let parent = ancestor_of_kind(our_list_item.parent()?, "list_item")?;
        self.direct_checkbox(parent)
    }

    /// Find all sibling checkboxes (same nesting level).
    /// Returns Vec of (checkbox_byte_offset, is_checked).
    fn find_sibling_checkboxes(&self, list_item_start: usize) -> Vec<(usize, bool)> {
        let our_list_item = match self.list_item_at(list_item_start) {
            Some(n) => n,
            None => return Vec::new(),
        };

        // Get parent list node
        let parent_list = match our_list_item.parent() {
            Some(p) if p.kind() == "list" => p,
            _ => return Vec::new(),
        };

        // Iterate all list_item children and collect their (direct) checkboxes
        let mut siblings = Vec::new();
        let mut cursor = parent_list.walk();
        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                if child.kind() == "list_item"
                    && let Some(cb) = self.direct_checkbox(child)
                {
                    siblings.push(cb);
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
        siblings
    }

    /// Set the line prefix, replacing current markers up to prefix_end.
    /// Preserves any content after prefix_end and adjusts cursor position.
    fn set_line_prefix(&mut self, new_prefix: &str, prefix_end: usize) {
        let cursor_offset = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor_offset);
        let line_start = self.buffer.line_to_byte(line_idx);

        let old_prefix_len = prefix_end - line_start;
        let new_prefix_len = new_prefix.len();
        let len_diff = new_prefix_len as isize - old_prefix_len as isize;

        // Delete old prefix
        if prefix_end > line_start {
            self.buffer.delete(line_start..prefix_end, cursor_offset);
        }

        // Insert new prefix
        if !new_prefix.is_empty() {
            self.buffer.insert(line_start, new_prefix, line_start);
        }

        // Adjust cursor: if cursor was after prefix, shift by the length difference
        // If cursor was in the prefix area, move to end of new prefix
        let new_cursor = if cursor_offset >= prefix_end {
            (cursor_offset as isize + len_diff) as usize
        } else {
            line_start + new_prefix_len
        };
        self.selection = Selection::new(new_cursor, new_cursor);
    }

    /// Resolve the table (if any) whose row occupies `line_idx`, plus that line's
    /// role in it. Mirrors `RenderSnapshot::table_row_at_line` but works off the
    /// buffer directly so editor input can query it.
    fn table_context_at_line(&self, line_idx: usize) -> Option<(&TableInfo, RowKind)> {
        if line_idx >= self.buffer.line_count() {
            return None;
        }
        let line_start = self.buffer.line_to_byte(line_idx);
        let table = self
            .buffer
            .parsed()
            .tables
            .iter()
            .find(|t| line_start >= t.block.start && line_start < t.block.end)?;
        // Line-number match (not byte containment) — the twin of `table_row_at_line`, so a
        // tree-sitter error-recovery row starting mid-line still resolves (else Tab cell-nav
        // and row insertion silently no-op while the grid still renders).
        let kind = row_kind_at_line(table, line_idx, |b| self.buffer.byte_to_line(b))?;
        Some((table, kind))
    }

    /// The table context at the cursor's line, cloned so callers can mutate the
    /// buffer afterward without holding a borrow.
    fn table_context_at_cursor(&self) -> Option<(TableInfo, RowKind)> {
        let line_idx = self.buffer.byte_to_line(self.cursor().offset);
        self.table_context_at_line(line_idx)
            .map(|(t, k)| (t.clone(), k))
    }

    /// Insert a new empty body row (`|  |  |…`, `ncols` cells) after `line_idx`,
    /// keeping any trailing newline. Returns the offset of the new row's first
    /// cell's typing position (just after its `| `).
    fn insert_table_row_after_line(&mut self, line_idx: usize, ncols: usize) -> usize {
        let content_end = self.line_content_end(line_idx);
        let row = format!("|{}", "  |".repeat(ncols));
        self.set_cursor(content_end);
        self.insert_text(&format!("\n{row}"));

        // First cell typing position = new_row_start (content_end + 1) + "| " (2).
        // Computed directly, not from a reparse: an all-empty trailing row + newline
        // momentarily parses with an ERROR node, so the model may not see it yet.
        content_end + 3
    }

    /// Smart-Enter table creation: on a "lone pipe-header row" (a bounded pipe row
    /// not yet part of a table), complete it into a real GFM table by inserting a
    /// delimiter row and one empty body row, landing the cursor in the first body
    /// cell. Returns true if it fired.
    pub fn maybe_create_table(&mut self) -> bool {
        if self.cursor_in_code_block() {
            return false;
        }
        let cursor = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor);
        if line_idx >= self.buffer.line_count() {
            return false;
        }

        // Only when the cursor sits at the end of the line.
        if cursor != self.cursor().move_to_line_end(&self.buffer).offset {
            return false;
        }
        // Not already inside a table.
        if self.table_context_at_cursor().is_some() {
            return false;
        }

        let line_start = self.buffer.line_to_byte(line_idx);
        let ncols = {
            let line_text = self.buffer.slice_cow(line_start..cursor);
            let trimmed = line_text.trim();
            let pipes = unescaped_pipe_indices(trimmed);
            if pipes.is_empty() {
                return false;
            }
            let ncols = pipe_row_ncols(trimmed, &pipes);
            // Only a properly-bounded header row `| … |` triggers creation, so prose or
            // list lines that merely contain a pipe never become tables.
            let bounded = trimmed.starts_with('|') && trimmed.ends_with('|');
            if ncols == 0 || !bounded {
                return false;
            }
            ncols
        };

        // Don't fire if the next line is already a delimiter row.
        if line_idx + 1 < self.buffer.line_count() {
            let next_start = self.buffer.line_to_byte(line_idx + 1);
            let next_end = if line_idx + 2 < self.buffer.line_count() {
                self.buffer.line_to_byte(line_idx + 2).saturating_sub(1)
            } else {
                self.buffer.len_bytes()
            };
            let next_text = self.buffer.slice_cow(next_start..next_end);
            if looks_like_delimiter_row(next_text.trim()) {
                return false;
            }
        }

        let delim = format!("|{}", " --- |".repeat(ncols));
        let body = format!("|{}", "  |".repeat(ncols));
        self.insert_text(&format!("\n{delim}\n{body}"));

        // Land in the first body cell (just after its "| "). Computed directly from
        // the inserted layout: header end + "\n" + delimiter + "\n" + "| ".
        let body_start = cursor + 1 + delim.len() + 1;
        self.set_cursor(body_start + 2);
        true
    }

    /// Caret landing offset for entering `cell` via Tab/Shift+Tab: the first content
    /// char for a non-empty cell, or a spot one space in past the opening `|` for an
    /// empty cell. An empty cell's trimmed content range collapses onto the closing-pipe
    /// boundary, so landing at `content.start` would sit the caret on that pipe; instead
    /// walk back to the opening `|` and land strictly between the two pipes.
    fn table_cell_landing(&self, cell: &TableCell) -> usize {
        if cell.content.start < cell.content.end {
            return cell.content.start;
        }
        let closing = cell.content.start;
        let mut open = closing;
        while open > 0 && self.buffer.byte_at(open - 1) != Some(b'|') {
            open -= 1;
        }
        // `open` is now just past the opening `|` (or 0 if none found); keep the caret
        // inside the cell (below the closing pipe, at or past the opening one).
        (open + 1).min(closing.saturating_sub(1)).max(open)
    }

    /// Cell navigation for Tab/Shift+Tab when the cursor is inside a table.
    /// Returns false (letting the caller fall back to list cycling) when not in a
    /// table. Forward: next cell → next row's first cell → append a new row at the
    /// last cell of the last row. Backward: previous cell → previous row's last
    /// cell; the header's first cell is a no-op.
    fn table_cell_nav(&mut self, forward: bool) -> bool {
        let cursor = self.cursor().offset;
        let Some((table, kind)) = self.table_context_at_cursor() else {
            return false;
        };

        let nrows = 1 + table.body.len();
        let cells_of = |row_pos: usize| -> &Vec<TableCell> {
            if row_pos == 0 {
                &table.header.cells
            } else {
                &table.body[row_pos - 1].cells
            }
        };

        let row_pos = match kind {
            RowKind::Header => Some(0),
            RowKind::Body(i) => Some(i + 1),
            RowKind::Delimiter => None,
        };

        // Some(offset) → move there; None → append a new row.
        let target: Option<usize> = match row_pos {
            None => {
                if forward {
                    // Delimiter row: forward goes to the first body cell (None → append).
                    table
                        .body
                        .first()
                        .and_then(|r| r.cells.first())
                        .map(|c| self.table_cell_landing(c))
                } else {
                    Some(
                        table
                            .header
                            .cells
                            .last()
                            .map_or(cursor, |c| self.table_cell_landing(c)),
                    )
                }
            }
            Some(row_pos) => {
                let cells = cells_of(row_pos);
                let cell_idx = cells
                    .iter()
                    .position(|c| c.content.end >= cursor)
                    .unwrap_or(cells.len().saturating_sub(1));
                if forward {
                    if cell_idx + 1 < cells.len() {
                        Some(self.table_cell_landing(&cells[cell_idx + 1]))
                    } else if row_pos + 1 < nrows {
                        cells_of(row_pos + 1)
                            .first()
                            .map(|c| self.table_cell_landing(c))
                    } else {
                        None
                    }
                } else if cell_idx > 0 {
                    Some(self.table_cell_landing(&cells[cell_idx - 1]))
                } else if row_pos > 0 {
                    cells_of(row_pos - 1)
                        .last()
                        .map(|c| self.table_cell_landing(c))
                } else {
                    Some(cursor)
                }
            }
        };

        match target {
            Some(off) => self.set_cursor(off),
            None => {
                let anchor = table
                    .body
                    .last()
                    .map(|r| r.line.start)
                    .unwrap_or(table.delimiter_line.start);
                let anchor_line = self.buffer.byte_to_line(anchor);
                let off = self.insert_table_row_after_line(anchor_line, table.ncols);
                self.set_cursor(off);
            }
        }
        true
    }

    /// Shift+Enter inside a table: add an empty body row below the current one
    /// (header/delimiter rows insert as the first body row) and land in its first
    /// cell. Returns true if it fired.
    fn maybe_add_table_row(&mut self) -> bool {
        let line_idx = self.buffer.byte_to_line(self.cursor().offset);
        let Some((table, kind)) = self.table_context_at_cursor() else {
            return false;
        };
        let anchor_line = match kind {
            RowKind::Body(_) => line_idx,
            RowKind::Header | RowKind::Delimiter => {
                self.buffer.byte_to_line(table.delimiter_line.start)
            }
        };
        let off = self.insert_table_row_after_line(anchor_line, table.ncols);
        self.set_cursor(off);
        true
    }

    /// Backspace convenience: if the caret sits in an all-empty table body row (e.g. one
    /// just added with Shift+Enter/Tab that you changed your mind about), remove the whole
    /// row in one press and land at the end of the previous row. Returns true if it fired.
    fn maybe_remove_empty_table_row(&mut self) -> bool {
        let Some((table, RowKind::Body(i))) = self.table_context_at_cursor() else {
            return false;
        };
        // Only when every cell is empty — otherwise backspace deletes a character normally.
        if !table.body[i]
            .cells
            .iter()
            .all(|c| c.content.start >= c.content.end)
        {
            return false;
        }
        let line_idx = self.buffer.byte_to_line(self.cursor().offset);
        let line_start = self.buffer.line_to_byte(line_idx);
        // First body row must still have a real row above it (header/delimiter), so
        // `line_start` is never 0 — the caret lands at the previous line's content end.
        let line_end = if line_idx + 1 < self.buffer.line_count() {
            self.buffer.line_to_byte(line_idx + 1)
        } else {
            self.buffer.len_bytes()
        };
        // Delete the row's line plus its own trailing newline, leaving the previous row's
        // newline intact so it joins cleanly with whatever followed the table.
        let cursor = self.cursor().offset;
        self.buffer.delete(line_start..line_end, cursor);
        let landing = line_start.saturating_sub(1);
        self.selection = Selection::new(landing, landing);
        true
    }

    /// When the caret's line is a table header that has gained a column (more cells than
    /// its delimiter row on the next line), append matching empty cells to the delimiter
    /// and every following body row so the whole table grows the column. Additive only —
    /// deleting a header column never removes body data.
    ///
    /// Detected on the RAW lines, not the parsed table: a header wider than its delimiter
    /// isn't a valid GFM table, so tree-sitter stops recognizing it the instant you type
    /// the new column — we have to spot the mismatch ourselves and heal it back to a table.
    /// Called after `insert_text`; a no-op away from that exact situation.
    /// Byte offset of the end of line `l`'s content (before its trailing newline), or
    /// `len_bytes` for the last line. Insertions land here to append to the line.
    fn line_content_end(&self, l: usize) -> usize {
        if l + 1 < self.buffer.line_count() {
            self.buffer.line_to_byte(l + 1).saturating_sub(1)
        } else {
            self.buffer.len_bytes()
        }
    }

    /// A line's text (including its trailing newline, if any).
    fn line_str(&self, l: usize) -> String {
        let ls = self.buffer.line_to_byte(l);
        let le = if l + 1 < self.buffer.line_count() {
            self.buffer.line_to_byte(l + 1)
        } else {
            self.buffer.len_bytes()
        };
        self.buffer.slice_cow(ls..le).into_owned()
    }

    fn maybe_sync_table_columns(&mut self, insert_pos: usize) {
        let hl = self.buffer.byte_to_line(self.cursor().offset);
        let dl = hl + 1;
        if dl >= self.buffer.line_count() {
            return;
        }
        let hls = self.buffer.line_to_byte(hl);
        let header_line = self.line_str(hl);
        let header = header_line.trim();
        let hpipes = unescaped_pipe_indices(header);
        // A bounded pipe row followed by a delimiter row is the header-of-a-table signal.
        if hpipes.is_empty() || !header.starts_with('|') {
            return;
        }
        let delim = self.line_str(dl);
        if !looks_like_delimiter_row(delim.trim()) {
            return;
        }
        let target = pipe_row_ncols(header, &hpipes);
        let delim_trim = delim.trim();
        if target <= pipe_row_ncols(delim_trim, &unescaped_pipe_indices(delim_trim)) {
            return; // header no wider than the delimiter → nothing to grow
        }

        // Which column the user added. Base guess: the cell just left of the edit position
        // (`hp` pipes precede it), which is right when the name was typed before the pipe
        // (`X |`). Inserting a bare `|` instead leaves an empty cell on the *other* side, so
        // prefer a lone empty header cell — but ONLY when it's adjacent to the edit (at the
        // base column or one past it). Requiring adjacency stops a *pre-existing* empty cell
        // (e.g. `| A |  | C |` then appending `D`) from stealing the insert position.
        let hp = unescaped_pipe_indices(&header_line)
            .iter()
            .filter(|&&p| hls + p < insert_pos)
            .count();
        let positional = hp.saturating_sub(1);
        let hcells = pipe_row_cells(header, &hpipes);
        let empties: Vec<usize> = hcells
            .iter()
            .enumerate()
            .filter(|(_, c)| c.trim().is_empty())
            .map(|(i, _)| i)
            .collect();
        let col = match empties.as_slice() {
            [e] if *e == positional || *e == positional + 1 => *e,
            _ => positional,
        };

        // The delimiter, then every following body row (until a blank / pipe-less line).
        let mut rows: Vec<(usize, bool)> = vec![(dl, true)];
        let mut l = dl + 1;
        while l < self.buffer.line_count() {
            let t = self.line_str(l);
            if t.trim().is_empty() || !t.contains('|') {
                break;
            }
            rows.push((l, false));
            l += 1;
        }

        // For each short row, insert the missing cell(s) at column `col`: right after that
        // row's `col`-th pipe (0-indexed), so the new cell lands at the same position as
        // the header's. If the row has no pipe there (shorter/unbounded), append at the end.
        let mut edits: Vec<(usize, String)> = Vec::new();
        for (line, is_delim) in rows {
            let text = self.line_str(line);
            let trimmed = text.trim();
            let cells = pipe_row_ncols(trimmed, &unescaped_pipe_indices(trimmed));
            if cells >= target {
                continue;
            }
            let ls = self.buffer.line_to_byte(line);
            let pipes: Vec<usize> = unescaped_pipe_indices(&text)
                .iter()
                .map(|p| ls + p)
                .collect();
            let cell = if is_delim { " --- |" } else { "   |" };
            let body = cell.repeat(target - cells);
            let (off, ins) = if col < pipes.len() {
                (pipes[col] + 1, body) // right after the col-th pipe
            } else {
                // Append at content end, opening a pipe first if the row lacks a trailing one.
                let content_end = self.line_content_end(line);
                let ins = if trimmed.ends_with('|') {
                    body
                } else {
                    format!("|{body}")
                };
                (content_end, ins)
            };
            edits.push((off, ins));
        }

        // Apply bottom-up so earlier offsets stay valid. Every edit is below the caret (in
        // the header), so the caret's byte position is unchanged.
        edits.sort_by_key(|(off, _)| std::cmp::Reverse(*off));
        let cursor = self.cursor().offset;
        for (off, ins) in edits {
            self.buffer.insert(off, &ins, cursor);
        }
    }

    /// Smart enter: creates paragraph break or exits container on empty line.
    /// Enter: just insert a raw newline. No magic.
    pub fn enter(&mut self) {
        self.insert_text("\n");
    }

    /// Shift+Enter: continue container (add markers from current line).
    /// In code blocks, copies leading whitespace for indentation.
    pub fn shift_enter(&mut self) {
        if self.maybe_create_table() {
            return;
        }
        if self.maybe_add_table_row() {
            return;
        }
        // In code blocks, copy leading whitespace from current line
        if self.cursor_in_code_block() {
            let indent = self.current_line_leading_whitespace();
            self.insert_text("\n");
            if !indent.is_empty() {
                self.insert_text(&indent);
            }
            return;
        }

        let Some(ctx) = self.line_context() else {
            self.insert_text("\n");
            return;
        };

        let continuation = ctx.line.continuation_rope(self.buffer.rope());
        self.insert_text("\n");
        if !continuation.is_empty() {
            self.insert_text(&continuation);
        }
    }

    /// Get leading whitespace (spaces/tabs) from the current line.
    fn current_line_leading_whitespace(&self) -> String {
        let cursor = self.cursor();
        let line_start = cursor.move_to_line_start(&self.buffer).offset;
        let line_end = cursor.move_to_line_end(&self.buffer).offset;
        let line_text = self.buffer.slice_cow(line_start..line_end);

        line_text
            .chars()
            .take_while(|c| *c == ' ' || *c == '\t')
            .collect()
    }

    /// Shift+Alt+Enter: create indented continuation (for nested paragraphs).
    /// For lists: newline + indent (no list marker)
    /// For blockquotes alone: newline + indent (exits blockquote)
    /// For nested (e.g. `> - item`): newline + outer markers + indent
    pub fn shift_alt_enter(&mut self) {
        let indent = {
            let Some(ctx) = self.line_context() else {
                self.insert_text("\n");
                return;
            };

            let has_list = ctx
                .line
                .markers
                .iter()
                .any(|m| matches!(m.kind, MarkerKind::ListItem { .. }));
            let has_blockquote = ctx
                .line
                .markers
                .iter()
                .any(|m| matches!(m.kind, MarkerKind::BlockQuote));

            if has_blockquote && !has_list {
                "  ".to_string()
            } else {
                ctx.line.nested_paragraph_indent(self.buffer.rope())
            }
        };

        self.insert_text("\n");
        if !indent.is_empty() {
            self.insert_text(&indent);
        }
    }

    /// Shift+Tab: cycle backward through nesting states.
    pub fn shift_tab(&mut self) {
        if self.table_cell_nav(false) {
            return;
        }
        self.shift_tab_cycle();
    }

    fn backspace_range_with_type(
        &self,
        cursor_pos: usize,
    ) -> Option<(std::ops::Range<usize>, bool)> {
        let (_, line) = self.find_line_at(cursor_pos)?;

        for marker in &line.markers {
            if cursor_pos == marker.range.end {
                let is_indent = matches!(marker.kind, MarkerKind::Indent);
                return Some((marker.range.clone(), is_indent));
            }
        }

        None
    }

    /// If cursor is at end of an opening code fence and the code block contains
    /// only whitespace, return the full block range to delete.
    fn find_empty_code_block_range(&self, cursor_pos: usize) -> Option<std::ops::Range<usize>> {
        let tree = self.buffer.tree()?;
        let root = tree.block_tree().root_node();

        // Find the node at cursor position (look slightly before since cursor is at end of fence)
        let node = root.descendant_for_byte_range(cursor_pos.saturating_sub(1), cursor_pos)?;

        // Walk up to find fenced_code_block
        let code_block = ancestor_of_kind(node, "fenced_code_block")?;

        let block_start = code_block.start_byte();
        let block_end = code_block.end_byte();

        // Find where content starts (after first line / opening fence)
        let block_text = self.buffer.slice_cow(block_start..block_end);
        let first_newline = block_text.find('\n')?;
        let content_start = block_start + first_newline + 1;

        // Check if content (between opening fence and end) is only whitespace + closing fence
        let content = self.buffer.slice_cow(content_start..block_end);
        let trimmed = content.trim();

        if trimmed == "```" || trimmed == "~~~" {
            // Don't include trailing newline after closing fence
            let mut end = block_end;
            if self.buffer.byte_at(end.saturating_sub(1)) == Some(b'\n') {
                end -= 1;
            }
            Some(block_start..end)
        } else {
            None
        }
    }

    /// Delete backward (backspace). Simple: delete one unit.
    /// Markers and indents are atomic - deleted as a whole.
    pub fn delete_backward(&mut self) {
        // Clear tab cycle cache since content is changing
        self.tab_cycle_cache = None;
        if !self.selection.is_collapsed() {
            self.delete_selection();
            self.propagate_checkbox_after_edit();
            return;
        }

        if self.cursor().offset == 0 {
            return;
        }

        // One backspace removes a just-added (still-empty) table row wholesale.
        if self.maybe_remove_empty_table_row() {
            self.propagate_checkbox_after_edit();
            return;
        }

        let cursor_pos = self.cursor().offset;

        if let Some((marker_range, _is_indent)) = self.backspace_range_with_type(cursor_pos) {
            // Check if we're deleting an opening code fence of an empty code block
            if let Some(block_range) = self.find_empty_code_block_range(cursor_pos) {
                // Delete the entire empty code block
                self.buffer.delete(block_range.clone(), cursor_pos);
                self.selection = Selection::new(block_range.start, block_range.start);
                self.propagate_checkbox_after_edit();
                return;
            }

            // Otherwise just delete the marker
            self.buffer.delete(marker_range.clone(), cursor_pos);
            self.selection = Selection::new(marker_range.start, marker_range.start);
            self.propagate_checkbox_after_edit();
            return;
        }

        // One grapheme cluster back, not one byte — so a codepoint or an emoji/combining
        // cluster is deleted whole rather than split.
        let new_pos = prev_grapheme_boundary(&self.buffer, cursor_pos);
        self.buffer.delete(new_pos..cursor_pos, cursor_pos);
        self.selection = Selection::new(new_pos, new_pos);
        self.propagate_checkbox_after_edit();
    }

    fn delete_selection(&mut self) {
        let range = self.selection.range();
        let cursor_before = self.cursor().offset;
        self.buffer.delete(range.clone(), cursor_before);
        self.selection = Selection::new(range.start, range.start);
    }

    /// Delete the character after the cursor, or the selection if active.
    pub fn delete_forward(&mut self) {
        // Clear tab cycle cache since content is changing
        self.tab_cycle_cache = None;
        if !self.selection.is_collapsed() {
            self.delete_selection();
        } else if self.cursor().offset < self.buffer.len_bytes() {
            let cursor_before = self.cursor().offset;
            let next = self.cursor().move_right(&self.buffer);
            self.buffer
                .delete(cursor_before..next.offset, cursor_before);
        }
        self.propagate_checkbox_after_edit();
    }

    pub fn handle_click(&mut self, buffer_offset: usize, shift_held: bool, click_count: usize) {
        if shift_held {
            self.selection = self.selection.extend_to(buffer_offset);
        } else {
            match click_count {
                2 => {
                    self.selection = Selection::select_word_at(buffer_offset, &self.buffer);
                }
                3 => {
                    self.selection = Selection::select_line_at(buffer_offset, &self.buffer);
                }
                _ => {
                    let off = self.snap_out_of_list_prefix(buffer_offset);
                    self.selection = Selection::new(off, off);
                }
            }
        }
    }

    /// A list item's leading marker whitespace (indent + bullet, before the checkbox or
    /// content) is structural, not text: a click there snaps to the nearer of the line
    /// start or the content boundary, so the caret can't land mid-prefix in a space.
    fn snap_out_of_list_prefix(&self, offset: usize) -> usize {
        let line = self.buffer.byte_to_line(offset);
        let markers = self.buffer.line_markers(line);
        if !markers
            .markers
            .iter()
            .any(|m| matches!(m.kind, MarkerKind::ListItem { .. }))
        {
            return offset;
        }
        let Some(prefix) = markers.marker_range() else {
            return offset;
        };
        if offset > prefix.start && offset < prefix.end {
            if offset - prefix.start <= prefix.end - offset {
                prefix.start
            } else {
                prefix.end
            }
        } else {
            offset
        }
    }

    pub fn handle_drag(&mut self, buffer_offset: usize) {
        self.selection = self.selection.extend_to(buffer_offset);
    }

    /// Toggle a checkbox on the given line, propagating to children and parents.
    /// Byte offset of the checkbox marker (`[ ]` / `[x]` / `[X]`) within `line`,
    /// given its checked state. `None` if the pattern isn't present in the text.
    fn checkbox_byte_offset(&self, line: &LineMarkers, is_checked: bool) -> Option<usize> {
        let line_text = self.buffer.slice_cow(line.range.clone());
        let pattern = if is_checked { "[x]" } else { "[ ]" };
        // Checked boxes may use an uppercase X.
        let relative = line_text
            .find(pattern)
            .or_else(|| is_checked.then(|| line_text.find("[X]")).flatten())?;
        Some(line.range.start + relative)
    }

    pub fn toggle_checkbox(&mut self, line_number: usize) {
        // Capture pre-toggle state so the whole cascade (child + parent + all
        // strikethrough edits) collapses to a single undo entry at the end.
        let head_before = self.buffer.undo_head();
        let cursor_before = self.cursor().offset;
        let text_before = self.buffer.text();

        let (is_checked, checkbox_byte_start) = {
            if line_number >= self.buffer.line_count() {
                return;
            }
            let line = self.buffer.line_markers(line_number);

            let Some(is_checked) = line.checkbox() else {
                return;
            };

            let Some(checkbox_byte_start) = self.checkbox_byte_offset(&line, is_checked) else {
                return;
            };
            (is_checked, checkbox_byte_start)
        };

        let new_checked = !is_checked;
        let mut cursor_pos = self.cursor().offset;

        // Find the list_item node for this checkbox - use checkbox_byte_start for accurate node finding
        let list_item_node = self.list_item_at(checkbox_byte_start);

        // Collect all checkboxes to toggle (clicked + nested children)
        let mut checkboxes_to_toggle: Vec<(usize, bool)> = Vec::new();

        if let Some(node) = list_item_node {
            // Get all nested checkboxes within this list_item
            let nested = self.find_nested_checkboxes(node);
            for (offset, currently_checked) in nested {
                // Only toggle if state differs from target
                if currently_checked != new_checked {
                    checkboxes_to_toggle.push((offset, currently_checked));
                }
            }
        } else {
            // No list_item found, just toggle the clicked checkbox
            checkboxes_to_toggle.push((checkbox_byte_start, is_checked));
        }

        // Sort by offset descending so we can modify without invalidating earlier offsets
        checkboxes_to_toggle.sort_by_key(|c| std::cmp::Reverse(c.0));

        // Toggle each checkbox + its line strikethrough. Descending offset order keeps a
        // strikethrough's byte shift from invalidating the lower offsets processed next;
        // the state replace is length-preserving.
        for (offset, _currently_checked) in &checkboxes_to_toggle {
            self.set_checkbox(*offset, new_checked, &mut cursor_pos);
        }

        // Propagate upward: if checking and all siblings are now checked, check parent
        // If unchecking, uncheck parent if it was checked
        self.propagate_checkbox_up(checkbox_byte_start, new_checked, &mut cursor_pos);

        let text_after = self.buffer.text();
        self.buffer.coalesce_since(
            head_before,
            &text_before,
            &text_after,
            cursor_before,
            cursor_pos,
        );

        self.selection = Selection::new(cursor_pos, cursor_pos);
    }

    /// Propagate checkbox state upward through parent list items.
    fn propagate_checkbox_up(
        &mut self,
        list_item_start: usize,
        checked: bool,
        cursor_pos: &mut usize,
    ) {
        // Find parent checkbox
        let parent_info = self.find_parent_checkbox(list_item_start);
        let Some((parent_offset, parent_checked)) = parent_info else {
            return;
        };

        if checked {
            // When checking: only auto-check parent if ALL siblings are now checked
            let siblings = self.find_sibling_checkboxes(list_item_start);
            let all_checked = siblings.iter().all(|(_, is_checked)| *is_checked);

            if all_checked && !parent_checked {
                self.set_checkbox(parent_offset, true, cursor_pos);
                // Recursively propagate up
                self.propagate_checkbox_up(parent_offset, true, cursor_pos);
            }
        } else {
            // When unchecking: uncheck parent if it was checked
            if parent_checked {
                self.set_checkbox(parent_offset, false, cursor_pos);
                // Recursively propagate up
                self.propagate_checkbox_up(parent_offset, false, cursor_pos);
            }
        }
    }

    /// Propagate checkbox state after editing (insert/delete): if the current line has a
    /// checkbox, propagate from it; otherwise re-evaluate the enclosing parent checkbox.
    fn propagate_checkbox_after_edit(&mut self) {
        let cursor_offset = self.cursor().offset;
        let line_idx = self.buffer.byte_to_line(cursor_offset);
        let markers = self.buffer.line_markers(line_idx);

        if let Some(is_checked) = markers.checkbox() {
            // Current line has a checkbox - propagate from it
            if let Some(checkbox_byte_start) = self.checkbox_byte_offset(&markers, is_checked) {
                let mut cursor_pos = cursor_offset;
                self.propagate_checkbox_up(checkbox_byte_start, is_checked, &mut cursor_pos);
                self.selection = Selection::new(cursor_pos, cursor_pos);
            }
        } else {
            // No checkbox on current line - maybe we deleted one.
            // Check if there's a parent checkbox that needs re-evaluation.
            self.propagate_from_parent_checkbox();
        }
    }

    /// When current line has no checkbox, find parent checkbox and re-evaluate it.
    fn propagate_from_parent_checkbox(&mut self) {
        let cursor_offset = self.cursor().offset;

        // Try to find a parent checkbox using tree-sitter.
        // If cursor is at end of file or outside a node, try one position back.
        let parent_info = self.find_parent_checkbox(cursor_offset).or_else(|| {
            if cursor_offset > 0 {
                self.find_parent_checkbox(cursor_offset - 1)
            } else {
                None
            }
        });

        let Some(parent_info) = parent_info else {
            return;
        };

        // Also need to find siblings from a valid position
        let sibling_offset =
            if self.find_sibling_checkboxes(cursor_offset).is_empty() && cursor_offset > 0 {
                cursor_offset - 1
            } else {
                cursor_offset
            };

        let (parent_checkbox_offset, parent_checked) = parent_info;

        // Find siblings using the adjusted offset
        let siblings = self.find_sibling_checkboxes(sibling_offset);

        // If no siblings with checkboxes, nothing to propagate
        if siblings.is_empty() {
            // No sibling checkboxes - if parent was checked, it should stay checked
            // (the deleted item wasn't affecting the parent's state)
            return;
        }

        let all_siblings_checked = siblings.iter().all(|(_, checked)| *checked);
        let mut cursor_pos = cursor_offset;

        if all_siblings_checked && !parent_checked {
            // All remaining siblings are checked, check the parent
            self.set_checkbox(parent_checkbox_offset, true, &mut cursor_pos);
            self.propagate_checkbox_up(parent_checkbox_offset, true, &mut cursor_pos);
            self.selection = Selection::new(cursor_pos, cursor_pos);
        } else if !all_siblings_checked && parent_checked {
            // Some siblings unchecked, uncheck the parent
            self.set_checkbox(parent_checkbox_offset, false, &mut cursor_pos);
            self.propagate_checkbox_up(parent_checkbox_offset, false, &mut cursor_pos);
            self.selection = Selection::new(cursor_pos, cursor_pos);
        }
    }

    /// Flip a single checkbox's state byte (`[ ]`↔`[x]`), toggle its line's
    /// strikethrough to match, and advance `cursor_pos` by the strikethrough's byte
    /// adjustment. The state replace is length-preserving; only strikethrough shifts bytes.
    fn set_checkbox(&mut self, checkbox_offset: usize, checked: bool, cursor_pos: &mut usize) {
        let content_start = checkbox_offset + 1; // skip '['
        let content_end = content_start + 1;
        let new_content = if checked { "x" } else { " " };
        self.buffer
            .replace(content_start..content_end, new_content, *cursor_pos);
        let line = self.buffer.byte_to_line(checkbox_offset);
        let adjustment = self.toggle_line_strikethrough(line, checked, *cursor_pos);
        *cursor_pos = (*cursor_pos as isize + adjustment) as usize;
    }

    /// Add or remove strikethrough (`~~`) from a line's content.
    fn toggle_line_strikethrough(
        &mut self,
        line_idx: usize,
        add_strikethrough: bool,
        cursor_pos: usize,
    ) -> isize {
        // Clear tab cycle cache since content is changing
        self.tab_cycle_cache = None;
        if line_idx >= self.buffer.line_count() {
            return 0;
        }
        let line = self.buffer.line_markers(line_idx);

        let content_start = line.content_start();
        let content_end = line.range.end;

        if content_start >= content_end {
            return 0;
        }

        let content = self.buffer.slice_cow(content_start..content_end);
        let trimmed = content.trim();

        if trimmed.is_empty() {
            return 0;
        }

        // The content span excluding surrounding whitespace — the range the `~~` wraps.
        let leading_ws = content.len() - content.trim_start().len();
        let trailing_ws = content.len() - content.trim_end().len();
        let text_start = content_start + leading_ws;
        let text_end = content_end - trailing_ws;

        if add_strikethrough {
            if trimmed.starts_with("~~") && trimmed.ends_with("~~") {
                return 0;
            }
            // Single replace wrapping the text in `~~` — one undo entry, byte-identical
            // to inserting `~~` at both ends.
            let wrapped = format!("~~{trimmed}~~");
            self.buffer
                .replace(text_start..text_end, &wrapped, cursor_pos);

            let mut adjustment: isize = 0;
            if cursor_pos > text_start {
                adjustment += 2;
            }
            if cursor_pos > text_end {
                adjustment += 2;
            }
            adjustment
        } else if trimmed.starts_with("~~") && trimmed.ends_with("~~") && trimmed.len() >= 4 {
            // Single replace stripping the wrapping `~~` — one undo entry, byte-identical
            // to deleting the trailing and leading `~~` separately.
            let inner = trimmed[2..trimmed.len() - 2].to_string();
            self.buffer
                .replace(text_start..text_end, &inner, cursor_pos);

            let mut adjustment: isize = 0;
            if cursor_pos > text_start + 2 {
                adjustment -= 2;
            }
            if cursor_pos > text_end {
                adjustment -= 2;
            }
            adjustment
        } else {
            0
        }
    }
}

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

    /// Trim leading newline from raw string literals for readability.
    /// Allows writing:
    /// ```
    /// r#"
    /// - item one
    /// - item two
    /// "#
    /// ```
    fn trim_raw(s: &str) -> &str {
        s.strip_prefix('\n').unwrap_or(s)
    }

    /// Helper to create an EditorState with cursor at a specific position.
    /// The cursor position is indicated by | in the input string.
    fn editor_with_cursor(input: &str) -> EditorState {
        let input = trim_raw(input);
        let cursor_pos = input
            .find('|')
            .expect("Input must contain | for cursor position");
        let content = input.replace('|', "");
        let mut state = EditorState::new(&content);
        state.set_cursor(cursor_pos);
        state
    }

    /// Helper to check editor state matches expected content with cursor.
    fn assert_editor_eq(state: &EditorState, expected: &str) {
        let expected = trim_raw(expected);
        let text = state.text();
        let cursor = state.cursor().offset;
        let mut actual = String::new();
        actual.push_str(&text[..cursor]);
        actual.push('|');
        actual.push_str(&text[cursor..]);
        assert_eq!(actual, expected);
    }

    /// Helper to check editor state with selection.
    /// Format: `<` marks start of selection, `|` marks head (cursor), `>` marks end.
    /// Examples:
    ///   - `|hello` - cursor at start, no selection
    ///   - `<hello|>` - "hello" selected, cursor at end
    ///   - `<|hello>` - "hello" selected, cursor at start
    fn assert_selection_eq(state: &EditorState, expected: &str) {
        let expected = trim_raw(expected);
        let text = state.text();
        let selection = &state.selection;

        let anchor = selection.anchor;
        let head = selection.head;
        let start = anchor.min(head);
        let end = anchor.max(head);
        let is_collapsed = anchor == head;

        let mut actual = String::new();
        let mut byte_pos = 0;

        for c in text.chars() {
            if !is_collapsed && byte_pos == start {
                actual.push('<');
            }
            if byte_pos == head {
                actual.push('|');
            }
            if !is_collapsed && byte_pos == end {
                actual.push('>');
            }
            actual.push(c);
            byte_pos += c.len_utf8();
        }

        // Handle markers at end of text
        if !is_collapsed && byte_pos == start {
            actual.push('<');
        }
        if byte_pos == head {
            actual.push('|');
        }
        if !is_collapsed && byte_pos == end {
            actual.push('>');
        }

        assert_eq!(actual, expected, "Selection mismatch");
    }

    mod click_tests {
        use super::*;

        #[test]
        fn click_sets_cursor() {
            let mut state = editor_with_cursor("hello| world");
            state.handle_click(0, false, 1);
            assert_editor_eq(&state, "|hello world");
        }

        #[test]
        fn click_middle() {
            let mut state = editor_with_cursor("|hello world");
            state.handle_click(6, false, 1);
            assert_editor_eq(&state, "hello |world");
        }

        #[test]
        fn shift_click_extends_selection() {
            let mut state = editor_with_cursor("hello| world");
            state.handle_click(11, true, 1);
            assert_selection_eq(&state, "hello< world|>");
        }

        #[test]
        fn shift_click_backward() {
            let mut state = editor_with_cursor("hello| world");
            state.handle_click(0, true, 1);
            assert_selection_eq(&state, "<|hello> world");
        }

        #[test]
        fn double_click_selects_word() {
            let mut state = editor_with_cursor("|hello world");
            state.handle_click(2, false, 2);
            assert_selection_eq(&state, "<hello|> world");
        }

        #[test]
        fn double_click_second_word() {
            let mut state = editor_with_cursor("|hello world");
            state.handle_click(8, false, 2);
            assert_selection_eq(&state, "hello <world|>");
        }

        #[test]
        fn triple_click_selects_line() {
            let mut state = editor_with_cursor("|hello world");
            state.handle_click(2, false, 3);
            assert_selection_eq(&state, "<hello world|>");
        }

        #[test]
        fn drag_extends_selection() {
            let mut state = editor_with_cursor("|hello world");
            state.handle_click(0, false, 1);
            state.handle_drag(5);
            assert_selection_eq(&state, "<hello|> world");
        }

        #[test]
        fn drag_backward() {
            let mut state = editor_with_cursor("hello world|");
            state.handle_click(11, false, 1);
            state.handle_drag(6);
            assert_selection_eq(&state, "hello <|world>");
        }
    }

    mod cursor_movement_tests {
        use super::*;

        #[test]
        fn move_left() {
            let mut state = editor_with_cursor("hel|lo");
            state.move_left();
            assert_editor_eq(&state, "he|llo");
        }

        #[test]
        fn move_left_at_start() {
            let mut state = editor_with_cursor("|hello");
            state.move_left();
            assert_editor_eq(&state, "|hello");
        }

        #[test]
        fn move_right() {
            let mut state = editor_with_cursor("he|llo");
            state.move_right();
            assert_editor_eq(&state, "hel|lo");
        }

        #[test]
        fn move_right_at_end() {
            let mut state = editor_with_cursor("hello|");
            state.move_right();
            assert_editor_eq(&state, "hello|");
        }

        #[test]
        fn move_up() {
            let mut state = editor_with_cursor("line one\nline |two\nline three");
            state.move_up();
            assert_editor_eq(&state, "line |one\nline two\nline three");
        }

        #[test]
        fn sticky_goal_column_survives_short_line() {
            // Down through a 2-char line then Down again restores the original column 7,
            // instead of clamping permanently to the short line's end.
            let mut state = editor_with_cursor("0123456|789\nab\nXYZ0123456");
            state.move_down(); // clamps to end of "ab"
            state.move_down(); // restores column 7 on the long last line
            assert_editor_eq(&state, "0123456789\nab\nXYZ0123|456");
        }

        #[test]
        fn goal_column_reset_by_horizontal_move() {
            // A horizontal move between vertical moves invalidates the goal column.
            let mut state = editor_with_cursor("0123456|789\nab\nXYZ0123456");
            state.move_down(); // end of "ab" (column 2)
            state.move_left(); // column 1 — invalidates the goal
            state.move_down(); // uses column 1, not 7
            assert_editor_eq(&state, "0123456789\nab\nX|YZ0123456");
        }

        #[test]
        fn move_up_from_first_line() {
            let mut state = editor_with_cursor("hel|lo\nworld");
            state.move_up();
            assert_editor_eq(&state, "|hello\nworld");
        }

        #[test]
        fn move_down() {
            let mut state = editor_with_cursor("line |one\nline two\nline three");
            state.move_down();
            assert_editor_eq(&state, "line one\nline |two\nline three");
        }

        #[test]
        fn move_down_from_last_line() {
            let mut state = editor_with_cursor("hello\nwor|ld");
            state.move_down();
            assert_editor_eq(&state, "hello\nworld|");
        }

        #[test]
        fn move_up_preserves_column() {
            let mut state = editor_with_cursor("short\nlonger line|");
            state.move_up();
            assert_editor_eq(&state, "short|\nlonger line");
        }

        #[test]
        fn move_to_line_start() {
            let mut state = editor_with_cursor("hello\nwor|ld");
            state.move_to_line_start();
            assert_editor_eq(&state, "hello\n|world");
        }

        #[test]
        fn move_to_line_end() {
            let mut state = editor_with_cursor("hello\nwor|ld");
            state.move_to_line_end();
            assert_editor_eq(&state, "hello\nworld|");
        }
    }

    // ========================================================================
    // New "raw markdown" behavior tests
    // These test the simplified, non-controlling editing paradigm.
    // ========================================================================

    mod raw_enter_tests {
        use super::*;

        // --- Enter: always raw \n ---

        #[test]
        fn enter_on_paragraph_inserts_newline() {
            let mut state = editor_with_cursor("Hello world|");
            state.enter();
            assert_editor_eq(&state, "Hello world\n|");
        }

        #[test]
        fn enter_on_heading_inserts_newline() {
            let mut state = editor_with_cursor("# Hello|");
            state.enter();
            assert_editor_eq(&state, "# Hello\n|");
        }

        #[test]
        fn enter_on_list_item_inserts_newline_no_marker() {
            let mut state = editor_with_cursor("- item one|");
            state.enter();
            assert_editor_eq(&state, "- item one\n|");
        }

        #[test]
        fn enter_on_blockquote_inserts_newline_no_marker() {
            let mut state = editor_with_cursor("> quote|");
            state.enter();
            assert_editor_eq(&state, "> quote\n|");
        }

        #[test]
        fn enter_on_nested_container_inserts_newline_no_markers() {
            let mut state = editor_with_cursor("> - item|");
            state.enter();
            assert_editor_eq(&state, "> - item\n|");
        }

        #[test]
        fn enter_on_empty_list_item_inserts_newline_keeps_marker() {
            let mut state = editor_with_cursor("- item one\n- |");
            state.enter();
            assert_editor_eq(&state, "- item one\n- \n|");
        }

        #[test]
        fn enter_on_empty_blockquote_inserts_newline_keeps_marker() {
            let mut state = editor_with_cursor("> quote one\n> |");
            state.enter();
            assert_editor_eq(&state, "> quote one\n> \n|");
        }

        #[test]
        fn enter_in_code_block_inserts_newline() {
            let mut state = editor_with_cursor("```rust\nlet x = 1;|");
            state.enter();
            assert_editor_eq(&state, "```rust\nlet x = 1;\n|");
        }

        #[test]
        fn enter_on_code_fence_inserts_newline() {
            let mut state = editor_with_cursor("```rust|");
            state.enter();
            assert_editor_eq(&state, "```rust\n|");
        }

        #[test]
        fn enter_preserves_soft_wrap_style() {
            // Adjacent lines without blank line between them
            let mut state = editor_with_cursor("First sentence.\nSecond sentence.|");
            state.enter();
            assert_editor_eq(&state, "First sentence.\nSecond sentence.\n|");
        }

        // --- Shift+Enter: continue container ---

        #[test]
        fn shift_enter_on_list_item_continues_list() {
            let mut state = editor_with_cursor("- item one|");
            state.shift_enter();
            assert_editor_eq(&state, "- item one\n- |");
        }

        #[test]
        fn shift_enter_on_blockquote_continues_blockquote() {
            let mut state = editor_with_cursor("> quote|");
            state.shift_enter();
            assert_editor_eq(&state, "> quote\n> |");
        }

        #[test]
        fn shift_enter_on_nested_container_continues_all() {
            let mut state = editor_with_cursor("> - item|");
            state.shift_enter();
            assert_editor_eq(&state, "> - item\n> - |");
        }

        #[test]
        fn shift_enter_on_paragraph_just_inserts_newline() {
            let mut state = editor_with_cursor("Hello world|");
            state.shift_enter();
            assert_editor_eq(&state, "Hello world\n|");
        }

        #[test]
        fn shift_enter_on_heading_just_inserts_newline() {
            let mut state = editor_with_cursor("# Hello|");
            state.shift_enter();
            assert_editor_eq(&state, "# Hello\n|");
        }

        // --- Shift+Alt+Enter: indented continuation ---

        #[test]
        fn shift_alt_enter_on_list_item_creates_indent() {
            let mut state = editor_with_cursor("- item one|");
            state.shift_alt_enter();
            assert_editor_eq(&state, "- item one\n  |");
        }

        #[test]
        fn shift_alt_enter_on_blockquote_creates_indent_outside() {
            let mut state = editor_with_cursor("> quote|");
            state.shift_alt_enter();
            assert_editor_eq(&state, "> quote\n  |");
        }

        #[test]
        fn shift_alt_enter_on_nested_container_creates_indent_inside() {
            let mut state = editor_with_cursor("> - item|");
            state.shift_alt_enter();
            assert_editor_eq(&state, "> - item\n>   |");
        }

        #[test]
        fn shift_alt_enter_on_paragraph_just_inserts_newline() {
            let mut state = editor_with_cursor("Hello world|");
            state.shift_alt_enter();
            assert_editor_eq(&state, "Hello world\n|");
        }
    }

    mod raw_backspace_tests {
        use super::*;

        #[test]
        fn backspace_deletes_char() {
            let mut state = editor_with_cursor("hello|");
            state.delete_backward();
            assert_editor_eq(&state, "hell|");
        }

        #[test]
        fn backspace_at_line_start_joins_lines() {
            let mut state = editor_with_cursor("line one\n|line two");
            state.delete_backward();
            assert_editor_eq(&state, "line one|line two");
        }

        #[test]
        fn backspace_deletes_whole_zwj_emoji() {
            // A family emoji is 7 codepoints but one grapheme — deleted whole, not split.
            let mut state = editor_with_cursor("a👨‍👩‍👧‍👦|b");
            state.delete_backward();
            assert_editor_eq(&state, "a|b");
        }

        #[test]
        fn backspace_deletes_whole_combining_accent() {
            // "é" as base 'e' + combining acute (2 codepoints, 1 grapheme).
            let mut state = editor_with_cursor("e\u{301}|");
            state.delete_backward();
            assert_editor_eq(&state, "|");
        }

        #[test]
        fn backspace_deletes_entire_list_marker() {
            let mut state = editor_with_cursor("- |");
            state.delete_backward();
            assert_editor_eq(&state, "|");
        }

        #[test]
        fn backspace_deletes_innermost_marker_first() {
            let mut state = editor_with_cursor("> - |");
            state.delete_backward();
            assert_editor_eq(&state, "> |");
        }

        #[test]
        fn backspace_then_deletes_outer_marker() {
            let mut state = editor_with_cursor("> |");
            state.delete_backward();
            assert_editor_eq(&state, "|");
        }

        #[test]
        fn backspace_deletes_entire_indent() {
            // Indent after list item is atomic - need context for tree-sitter to recognize it
            let mut state = editor_with_cursor("- item\n  |text");
            state.delete_backward();
            assert_editor_eq(&state, "- item\n|text");
        }

        #[test]
        fn backspace_in_middle_of_text_deletes_char() {
            let mut state = editor_with_cursor("- item o|ne");
            state.delete_backward();
            assert_editor_eq(&state, "- item |ne");
        }

        #[test]
        fn backspace_on_empty_line_after_list_joins() {
            let mut state = editor_with_cursor("- item one\n|");
            state.delete_backward();
            assert_editor_eq(&state, "- item one|");
        }

        #[test]
        fn backspace_sequence_through_markers_and_join() {
            // Start: "- item one\n- |"
            // Backspace 1: delete "- " marker -> "- item one\n|"
            // Backspace 2: join lines -> "- item one|"
            let mut state = editor_with_cursor("- item one\n- |");
            state.delete_backward();
            assert_editor_eq(&state, "- item one\n|");
            state.delete_backward();
            assert_editor_eq(&state, "- item one|");
        }

        #[test]
        fn backspace_with_content_after_cursor_deletes_marker() {
            let mut state = editor_with_cursor("- |two");
            state.delete_backward();
            assert_editor_eq(&state, "|two");
        }

        #[test]
        fn backspace_deletes_entire_task_list_marker() {
            // Task list now has separate Checkbox and ListItem markers
            // First backspace deletes the checkbox, second deletes the list marker
            let mut state = editor_with_cursor("- [ ] |");
            state.delete_backward();
            assert_editor_eq(&state, "- |");
            state.delete_backward();
            assert_editor_eq(&state, "|");
        }

        #[test]
        fn backspace_deletes_checked_task_list_marker() {
            let mut state = editor_with_cursor("- [x] |");
            state.delete_backward();
            assert_editor_eq(&state, "- |");
            state.delete_backward();
            assert_editor_eq(&state, "|");
        }
    }

    mod raw_tab_tests {
        use super::*;

        // --- Tab cycling through states ---
        // Tree-based: cycle is marker → (para indent if blank) → nested marker → empty

        #[test]
        fn tab_on_empty_line_after_list_adds_marker() {
            // Blank line cycle: ["- ", "  ", "  - ", ""]
            let mut state = editor_with_cursor("- item\n|");
            state.tab();
            assert_editor_eq(&state, "- item\n- |");
        }

        #[test]
        fn tab_twice_after_list_adds_nested_marker() {
            // Cycle is: "" -> "- " -> "  " -> "  - " -> ""
            let mut state = editor_with_cursor("- item\n|");
            state.tab();
            state.tab();
            assert_editor_eq(&state, "- item\n  |"); // para indent
            state.tab();
            assert_editor_eq(&state, "- item\n  - |"); // nested marker
        }

        #[test]
        fn tab_three_times_cycles_back() {
            // Cycle is: "" -> "- " -> "  " -> "  - " -> "" (4 states)
            let mut state = editor_with_cursor("- item\n|");
            state.tab();
            state.tab();
            state.tab();
            state.tab();
            assert_editor_eq(&state, "- item\n|");
        }

        #[test]
        fn tab_cycles_ordered_list_after_checkbox() {
            // Bug case: ordered list preceded by checkbox content
            // Cycle should be: "" -> "2. " -> "   " -> "   1. " -> "" (4 states)
            let mut state = editor_with_cursor("## Writ\n- [ ] item\n\n1. hey\n|");

            state.tab();
            assert_editor_eq(&state, "## Writ\n- [ ] item\n\n1. hey\n2. |");

            state.tab();
            assert_editor_eq(&state, "## Writ\n- [ ] item\n\n1. hey\n   |"); // para indent

            state.tab();
            assert_editor_eq(&state, "## Writ\n- [ ] item\n\n1. hey\n   1. |");

            state.tab();
            assert_editor_eq(&state, "## Writ\n- [ ] item\n\n1. hey\n|");
        }

        #[test]
        fn tab_indents_line_with_content() {
            // Tab should cycle the prefix even when there's content after it
            // Content is preserved and cursor stays in place relative to content
            let mut state = editor_with_cursor("1. hey\n2. asdf|");
            state.tab();
            assert_editor_eq(&state, "1. hey\n   asdf|"); // para indent, content preserved
            state.tab();
            assert_editor_eq(&state, "1. hey\n   1. asdf|"); // nested, content preserved
        }

        #[test]
        fn tab_preserves_unchecked_checkbox_state() {
            // Tab cycling preserves the current line's checkbox state
            // Propagation doesn't happen because tree-sitter can't parse incomplete lines
            // Cycle: "" -> "- [ ] " -> "  " -> "  - [ ] " -> ""
            let mut state = editor_with_cursor("- [x] hey\n- [ ] |");
            state.tab();
            // Checkbox stays unchecked (from current line), no propagation
            assert_editor_eq(&state, "- [x] hey\n  |"); // para indent
            state.tab();
            assert_editor_eq(&state, "- [x] hey\n  - [ ] |"); // nested
            state.tab();
            assert_editor_eq(&state, "- [x] hey\n|");
            state.tab();
            assert_editor_eq(&state, "- [x] hey\n- [ ] |");
        }

        #[test]
        fn tab_preserves_checked_checkbox_state() {
            // Tab cycling preserves the current line's checkbox state
            // Cycle: "" -> "- [x] " -> "  " -> "  - [x] " -> ""
            let mut state = editor_with_cursor("- [ ] hey\n- [x] |");
            state.tab();
            // Checkbox stays checked (from current line), no propagation
            assert_editor_eq(&state, "- [ ] hey\n  |"); // para indent
            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n  - [x] |"); // nested
            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n|");
            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n- [x] |");
        }

        #[test]
        fn tab_new_checkbox_defaults_unchecked() {
            // Starting from empty line, new checkboxes default to unchecked
            // Cycle: "" -> "- [ ] " -> "  " -> "  - [ ] " -> ""
            let mut state = editor_with_cursor("- [x] ~~hey~~\n|");
            state.tab(); // sibling: - [ ] |
            assert_editor_eq(&state, "- [x] ~~hey~~\n- [ ] |");
            state.tab(); // para indent
            assert_editor_eq(&state, "- [x] ~~hey~~\n  |");
            state.tab(); // nested: - [ ] |
            assert_editor_eq(&state, "- [x] ~~hey~~\n  - [ ] |");
        }

        #[test]
        fn typing_after_tab_propagates_checkbox() {
            // Tab creates incomplete line "- [ ] |" which tree-sitter can't parse.
            // Once we type content, tree-sitter recognizes it and propagation happens.
            // Cycle: "" -> "- [ ] " -> "  " -> "  - [ ] " -> ""
            let mut state = editor_with_cursor("- [x] hey\n|");
            state.tab(); // "- [ ] |" - incomplete, no propagation yet
            assert_editor_eq(&state, "- [x] hey\n- [ ] |");
            state.tab(); // para indent
            assert_editor_eq(&state, "- [x] hey\n  |");
            state.tab(); // nest it: "  - [ ] |"
            assert_editor_eq(&state, "- [x] hey\n  - [ ] |");
            // Type a character - now tree-sitter can parse, propagation unchecks parent
            state.insert_text("a");
            assert_editor_eq(&state, "- [ ] hey\n  - [ ] a|");
        }

        #[test]
        fn delete_backward_propagates_checkbox() {
            // Deleting content can affect checkbox propagation
            let mut state = editor_with_cursor("- [x] hey\n  - [ ] ab|");
            // Delete 'b' - still has content, propagation runs (parent stays unchecked)
            state.delete_backward();
            assert_editor_eq(&state, "- [ ] hey\n  - [ ] a|");
        }

        #[test]
        fn delete_forward_propagates_checkbox() {
            // Deleting content forward can affect checkbox propagation
            let mut state = editor_with_cursor("- [x] hey\n  - [ ] |ab");
            // Delete 'a' - still has content, propagation runs
            state.delete_forward();
            assert_editor_eq(&state, "- [ ] hey\n  - [ ] |b");
        }

        #[test]
        fn delete_checkbox_marker_rechecks_parent() {
            // Start with checked parent and one checked nested child
            // Cycle: "" -> "- [ ] " -> "  " -> "  - [ ] " -> ""
            let mut state = editor_with_cursor("- [x] ~~parent~~\n  - [x] ~~nested~~\n|");
            // Tab three times to create a new nested unchecked checkbox (with para indent now in cycle)
            state.tab();
            state.tab();
            state.tab();
            assert_editor_eq(&state, "- [x] ~~parent~~\n  - [x] ~~nested~~\n  - [ ] |");
            // Type to make it parseable - this should uncheck the parent
            state.insert_text("new");
            assert_editor_eq(&state, "- [ ] parent\n  - [x] ~~nested~~\n  - [ ] new|");
            // Now delete backwards to remove the unchecked child entirely
            // First delete the content
            state.delete_backward();
            state.delete_backward();
            state.delete_backward();
            assert_editor_eq(&state, "- [ ] parent\n  - [x] ~~nested~~\n  - [ ] |");
            // Delete the checkbox marker
            state.delete_backward();
            assert_editor_eq(&state, "- [ ] parent\n  - [x] ~~nested~~\n  - |");
            // Delete the list marker
            state.delete_backward();
            assert_editor_eq(&state, "- [x] ~~parent~~\n  - [x] ~~nested~~\n  |");
        }

        #[test]
        fn tab_with_blank_line_between_still_works() {
            // Tree-sitter includes blank lines in list_item
            let mut state = editor_with_cursor("- item\n\n|");
            state.tab();
            assert_editor_eq(&state, "- item\n\n- |");
        }

        #[test]
        fn tab_with_two_blank_lines_still_works() {
            // Tree-sitter includes multiple blank lines in list_item
            let mut state = editor_with_cursor("- item\n\n\n|");
            state.tab();
            assert_editor_eq(&state, "- item\n\n\n- |");
        }

        #[test]
        fn tab_on_blockquote_context_adds_marker() {
            let mut state = editor_with_cursor("> quote\n|");
            state.tab();
            assert_editor_eq(&state, "> quote\n> |");
        }

        #[test]
        fn tab_twice_on_blockquote_context_cycles_back() {
            let mut state = editor_with_cursor("> quote\n|");
            state.tab();
            state.tab();
            assert_editor_eq(&state, "> quote\n|");
        }

        #[test]
        fn tab_on_nested_context_cycles() {
            // Cycle: ["> ", "> - ", ">   ", ">   - ", ""]
            let mut state = editor_with_cursor("> - item\n|");

            state.tab();
            assert_editor_eq(&state, "> - item\n> |");

            state.tab();
            assert_editor_eq(&state, "> - item\n> - |");

            state.tab();
            assert_editor_eq(&state, "> - item\n>   |"); // para indent

            state.tab();
            assert_editor_eq(&state, "> - item\n>   - |");

            state.tab();
            assert_editor_eq(&state, "> - item\n|");
        }

        // --- Shift+Tab cycling backwards ---

        #[test]
        fn shift_tab_cycles_backwards() {
            // Cycle: ["- ", "  ", "  - ", ""]
            // Backwards from "" goes to "  - "
            let mut state = editor_with_cursor("- item\n|");
            state.shift_tab();
            assert_editor_eq(&state, "- item\n  - |");
        }

        #[test]
        fn shift_tab_from_marker_goes_to_empty() {
            let mut state = editor_with_cursor("- item\n- |");
            state.shift_tab();
            assert_editor_eq(&state, "- item\n|");
        }

        #[test]
        fn shift_tab_from_nested_marker_goes_to_marker() {
            // "  - " is nested list, cycle found via ERROR handling
            // Cycle backwards: "  - " -> "  " -> "- " -> ""
            let mut state = editor_with_cursor("- item\n  - |");
            state.shift_tab();
            assert_editor_eq(&state, "- item\n  |"); // para indent
            state.shift_tab();
            assert_editor_eq(&state, "- item\n- |");
        }

        #[test]
        fn tab_after_blank_line_includes_para_indent() {
            // With blank line, para indent should be in cycle
            // Cycle: ["- ", "  ", "  - ", "    ", "    - ", ""]
            let mut state = editor_with_cursor("- parent\n  - nested\n\n|");

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n- |");

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n  |"); // para indent

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n  - |");

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n    |"); // nested para indent

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n    - |");

            state.tab();
            assert_editor_eq(&state, "- parent\n  - nested\n\n|"); // back to empty
        }

        #[test]
        fn tab_no_blank_line_includes_para_indent() {
            // Para indent is now always in cycle, even without blank line
            // Cycle: ["- ", "  ", "  - ", "    ", "    - ", ""]
            let mut state = editor_with_cursor("- parent item\n  - nested with tab\n|");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n- |");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n  |"); // para indent

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n  - |");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n    |"); // nested para indent

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n    - |");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n|");
        }

        #[test]
        fn tab_with_trailing_newline() {
            // Cursor on line with newline after it - should still cycle correctly
            // Cycle: ["- ", "  ", "  - ", "    ", "    - ", ""]
            let mut state = editor_with_cursor("- parent item\n  - nested with tab\n|\n");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n- |\n");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n  |\n"); // para indent

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n  - |\n");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n    |\n"); // nested para indent

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n    - |\n");

            state.tab();
            assert_editor_eq(&state, "- parent item\n  - nested with tab\n|\n");
        }

        #[test]
        fn tab_task_list_uses_list_marker_width_not_full_marker() {
            // Task list "- [ ] " is 6 chars, but para indent should use list marker width (2)
            // Cycle: ["- [ ] ", "  ", "  - [ ] ", ""]
            let mut state = editor_with_cursor("- [ ] hey\n\n|");

            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n\n- [ ] |");

            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n\n  |"); // 2 spaces, not 6

            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n\n  - [ ] |"); // nested at 2 spaces

            state.tab();
            assert_editor_eq(&state, "- [ ] hey\n\n|");
        }
    }

    mod table_editing_tests {
        use super::*;

        /// 2-col table with cell content offsets:
        /// header cells "a"@2, "b"@6; body[0] "1"@26, "2"@30.
        const TABLE_2X1: &str = "| a | b |\n| --- | --- |\n| 1 | 2 |\n";

        // --- Stage 5: creation via smart Enter ---

        #[test]
        fn enter_inserts_raw_newline_never_creates_table() {
            // Plain Enter is "no magic" — table creation is Shift+Enter only.
            let mut state = EditorState::new("| a | b |");
            state.set_cursor(9); // end of line
            state.enter();
            assert_eq!(state.text(), "| a | b |\n");
        }

        #[test]
        fn shift_enter_completes_lone_pipe_header_into_table() {
            let mut state = EditorState::new("| a | b |");
            state.set_cursor(9);
            state.shift_enter();
            assert_eq!(state.text(), "| a | b |\n| --- | --- |\n|  |  |");
            assert_eq!(state.cursor().offset, 26);
        }

        #[test]
        fn create_rejects_unbounded_pipe_row() {
            // Not bounded by leading + trailing pipes → not treated as a table header.
            let mut state = EditorState::new("a | b");
            state.set_cursor(5);
            assert!(!state.maybe_create_table());
            assert_eq!(state.text(), "a | b");
        }

        #[test]
        fn create_does_nothing_on_existing_table_row() {
            // Header row already followed by a delimiter (a real table).
            let mut state = EditorState::new("| a | b |\n| --- | --- |\n");
            state.set_cursor(9);
            assert!(!state.maybe_create_table());
            assert_eq!(state.text(), "| a | b |\n| --- | --- |\n");
        }

        #[test]
        fn create_does_nothing_inside_code_block() {
            let mut state = EditorState::new("```\n| a | b |\n```\n");
            state.set_cursor(13); // end of "| a | b |"
            assert!(!state.maybe_create_table());
            assert_eq!(state.text(), "```\n| a | b |\n```\n");
        }

        #[test]
        fn create_does_nothing_on_plain_paragraph() {
            let mut state = EditorState::new("hello world");
            state.set_cursor(11);
            assert!(!state.maybe_create_table());
            assert_eq!(state.text(), "hello world");
        }

        #[test]
        fn create_does_nothing_when_cursor_not_at_line_end() {
            let mut state = EditorState::new("| a | b |");
            state.set_cursor(4); // middle of the line
            assert!(!state.maybe_create_table());
            assert_eq!(state.text(), "| a | b |");
        }

        // --- Stage 6: cell navigation via Tab / Shift+Tab ---

        #[test]
        fn tab_moves_to_next_cell_in_row() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(2); // header cell (0,0), before "a"
            state.tab();
            assert_eq!(state.cursor().offset, 6); // header cell (0,1), before "b"
        }

        #[test]
        fn tab_at_row_end_moves_to_next_row_first_cell() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(6); // header last cell
            state.tab();
            assert_eq!(state.cursor().offset, 26); // body[0] first cell, before "1"
        }

        #[test]
        fn tab_on_last_cell_of_last_row_creates_new_row() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(30); // body[0] last cell, before "2"
            state.tab();
            assert_eq!(
                state.text(),
                "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n"
            );
            assert_eq!(state.cursor().offset, 36); // new row first empty cell
        }

        #[test]
        fn shift_tab_moves_to_previous_cell() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(6); // header cell (0,1)
            state.shift_tab();
            assert_eq!(state.cursor().offset, 2); // header cell (0,0)
        }

        #[test]
        fn shift_tab_at_row_start_moves_to_previous_row_last_cell() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(26); // body[0] first cell
            state.shift_tab();
            assert_eq!(state.cursor().offset, 6); // header last cell
        }

        #[test]
        fn shift_tab_on_header_first_cell_is_noop() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(2);
            state.shift_tab();
            assert_eq!(state.cursor().offset, 2);
            assert_eq!(state.text(), TABLE_2X1);
        }

        #[test]
        fn shift_enter_in_table_adds_matched_row() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(26); // inside body[0]
            state.shift_enter();
            assert_eq!(
                state.text(),
                "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n"
            );
            assert_eq!(state.cursor().offset, 36);
        }

        #[test]
        fn typing_a_header_column_grows_the_whole_table() {
            let mut state = EditorState::new("| A | B |\n| - | - |\n| 1 | 2 |\n| 3 | 4 |\n");
            state.set_cursor(9); // end of the header line, after the final '|'
            state.insert_text(" C"); // add a third header cell
            assert_eq!(
                state.text(),
                "| A | B | C\n| - | - | --- |\n| 1 | 2 |   |\n| 3 | 4 |   |\n"
            );
            // And it's a valid 3-column table again.
            let t = &state.buffer.parsed().tables[0];
            assert_eq!(t.ncols, 3);
            assert_eq!(t.body.len(), 2);
        }

        #[test]
        fn adding_a_middle_header_column_inserts_body_columns_in_place() {
            let mut state = EditorState::new("| A | B | C |\n| - | - | - |\n| 1 | 2 | 3 |\n");
            state.set_cursor(9); // right after the pipe following B, before " C"
            state.insert_text(" X |"); // insert a new column between B and C
            assert_eq!(
                state.text(),
                "| A | B | X | C |\n| - | - | --- | - |\n| 1 | 2 |   | 3 |\n"
            );
        }

        #[test]
        fn middle_column_via_empty_cell_lands_in_place() {
            // A bare pipe creates an empty header cell between B and C; the body column
            // must land at that same index, not on the far right.
            let mut state = EditorState::new("| A | B | C |\n| - | - | - |\n| 1 | 2 | 3 |\n");
            state.set_cursor(9); // right after the pipe following B
            state.insert_text("|");
            assert_eq!(
                state.text(),
                "| A | B || C |\n| - | - | --- | - |\n| 1 | 2 |   | 3 |\n"
            );
        }

        #[test]
        fn column_grow_ignores_preexisting_empty_header_cell() {
            // Header already has an empty middle cell; appending a column at the right must
            // grow the body at the RIGHT, not steal the pre-existing empty cell's position.
            let mut state = EditorState::new("| A |  | C |\n| - | - | - |\n| 1 | 2 | 3 |\n");
            let header_end = state.text().find('\n').unwrap();
            state.set_cursor(header_end);
            state.insert_text(" D");
            assert_eq!(
                state.text(),
                "| A |  | C | D\n| - | - | - | --- |\n| 1 | 2 | 3 |   |\n"
            );
        }

        #[test]
        fn typing_in_a_body_cell_does_not_grow_columns() {
            // Editing a body cell must never trigger column growth.
            let mut state = EditorState::new("| A | B |\n| - | - |\n| 1 | 2 |\n");
            let pos = state.text().rfind('1').unwrap() + 1;
            state.set_cursor(pos);
            state.insert_text("x");
            assert_eq!(state.text(), "| A | B |\n| - | - |\n| 1x | 2 |\n");
        }

        #[test]
        fn backspace_removes_just_added_empty_table_row() {
            let mut state = EditorState::new(TABLE_2X1);
            state.set_cursor(26); // inside body[0]
            state.shift_enter(); // adds an empty row, caret inside it
            assert!(state.text().ends_with("|  |  |\n"));
            state.delete_backward(); // one backspace removes the whole empty row
            assert_eq!(state.text(), TABLE_2X1);
        }

        #[test]
        fn backspace_in_nonempty_table_row_deletes_char_not_row() {
            let mut state = EditorState::new("| a | b |\n| --- | --- |\n| xy | 2 |\n");
            let pos = state.text().find('y').unwrap() + 1; // just after 'y'
            state.set_cursor(pos);
            state.delete_backward();
            // The 'y' is deleted; the row (and its cells) survive.
            assert!(state.text().contains("| x | 2 |"));
        }

        // --- Issue 2: Tab lands on cell content, never on a pipe ---

        #[test]
        fn tab_lands_on_content_char_in_nonempty_cell() {
            // "| ab | cd |": cell (0,1) content "cd" starts at byte 7 ('c').
            let mut state = EditorState::new("| ab | cd |\n| --- | --- |\n");
            state.set_cursor(2); // cell (0,0), before "ab"
            state.tab();
            assert_eq!(state.cursor().offset, 7);
            assert_eq!(state.buffer.byte_at(7), Some(b'c'));
        }

        #[test]
        fn tab_into_empty_cell_lands_between_pipes() {
            // Body row "|  |  |" starts at byte 24: pipes at 24, 27, 30.
            let mut state = EditorState::new("| a | b |\n| --- | --- |\n|  |  |\n");
            state.set_cursor(6); // header cell (0,1) → Tab → empty body[0] cell 0
            state.tab();
            let off = state.cursor().offset;
            assert!(off > 24 && off < 27, "strictly between the cell's pipes");
            assert_ne!(state.buffer.byte_at(off), Some(b'|'), "not on a pipe");
        }

        #[test]
        fn tab_through_freshly_created_empty_row_never_on_pipe() {
            // Every empty cell reached by tabbing must sit the caret off a pipe.
            let mut state = EditorState::new("| a | b |");
            state.set_cursor(9);
            state.shift_enter(); // create table, land in body cell 0
            for _ in 0..2 {
                let off = state.cursor().offset;
                assert_ne!(
                    state.buffer.byte_at(off),
                    Some(b'|'),
                    "caret never on a pipe"
                );
                state.tab();
            }
        }

        // --- Issue 3: vertical movement into/through a table; left edge counts ---

        #[test]
        fn move_down_from_paragraph_enters_table_block() {
            let mut state =
                EditorState::new("para\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\nafter\n");
            state.set_cursor(0); // paragraph above the table
            state.move_down();
            let (table, _) = state
                .table_context_at_cursor()
                .expect("cursor is in the table after move_down");
            assert!(
                table.block.contains(&state.cursor().offset),
                "cursor offset is within the table block"
            );
        }

        #[test]
        fn move_down_passes_through_every_table_row() {
            let mut state =
                EditorState::new("para\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\nafter\n");
            state.set_cursor(0);
            let mut in_table_lines = 0;
            for _ in 0..5 {
                state.move_down();
                if state.table_context_at_cursor().is_some() {
                    in_table_lines += 1;
                }
            }
            // header + delimiter + one body row are all passed through, in-block.
            assert_eq!(in_table_lines, 3, "caret lands on each table row in turn");
        }

        #[test]
        fn cursor_at_first_table_line_start_is_in_table() {
            let mut state =
                EditorState::new("para\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\nafter\n");
            let start = state.buffer.line_to_byte(1); // first table line (header), column 0
            state.set_cursor(start);
            assert!(
                state.table_context_at_cursor().is_some(),
                "the left edge / line start of a table row counts as in-table"
            );
        }

        // --- Regressions: not in a table ---

        #[test]
        fn tab_outside_table_still_cycles_list() {
            let mut state = editor_with_cursor("- item\n|");
            state.tab();
            assert_editor_eq(&state, "- item\n- |");
        }

        #[test]
        fn shift_enter_outside_table_still_continues_list() {
            let mut state = editor_with_cursor("- item one|");
            state.shift_enter();
            assert_editor_eq(&state, "- item one\n- |");
        }
    }

    mod raw_cursor_movement_tests {
        use super::*;

        #[test]
        fn move_left_through_marker_is_atomic() {
            let mut state = editor_with_cursor("- |item");
            state.move_left();
            assert_editor_eq(&state, "|- item");
        }

        #[test]
        fn move_right_through_marker_is_atomic() {
            let mut state = editor_with_cursor("|- item");
            state.move_right();
            assert_editor_eq(&state, "- |item");
        }

        #[test]
        fn move_left_through_nested_markers_one_at_a_time() {
            let mut state = editor_with_cursor("> - |item");
            state.move_left();
            assert_editor_eq(&state, "> |- item");
            state.move_left();
            assert_editor_eq(&state, "|> - item");
        }

        #[test]
        fn move_left_does_not_skip_blank_lines() {
            let mut state = editor_with_cursor("line one\n\n|line three");
            state.move_left();
            assert_editor_eq(&state, "line one\n|\nline three");
        }

        #[test]
        fn move_left_from_blank_line_goes_to_previous() {
            let mut state = editor_with_cursor("line one\n|\nline three");
            state.move_left();
            assert_editor_eq(&state, "line one|\n\nline three");
        }

        #[test]
        fn move_up_maintains_column_in_content_area() {
            let mut state = editor_with_cursor("- item one\n- item |two");
            state.move_up();
            assert_editor_eq(&state, "- item |one\n- item two");
        }

        #[test]
        fn move_left_through_blockquote_ordered_list() {
            let mut state = editor_with_cursor("> 1. |");
            state.move_left();
            assert_editor_eq(&state, "> |1. ");
            state.move_left();
            assert_editor_eq(&state, "|> 1. ");
        }
    }

    mod checkbox_propagation_tests {
        use super::*;

        #[test]
        fn check_parent_checks_all_children() {
            let mut state = editor_with_cursor("- [ ] |parent\n  - [ ] child1\n  - [ ] child2\n");
            state.toggle_checkbox(0);
            let text = state.text();
            assert!(text.contains("[x] ~~parent~~"), "parent should be checked");
            assert!(text.contains("[x] ~~child1~~"), "child1 should be checked");
            assert!(text.contains("[x] ~~child2~~"), "child2 should be checked");
        }

        #[test]
        fn uncheck_parent_unchecks_all_children() {
            let mut state =
                editor_with_cursor("- [x] ~~|parent~~\n  - [x] ~~child1~~\n  - [x] ~~child2~~\n");
            state.toggle_checkbox(0);
            let text = state.text();
            assert!(text.contains("[ ] parent"), "parent should be unchecked");
            assert!(text.contains("[ ] child1"), "child1 should be unchecked");
            assert!(text.contains("[ ] child2"), "child2 should be unchecked");
            assert!(!text.contains("~~"), "no strikethrough should remain");
        }

        #[test]
        fn check_all_siblings_checks_parent() {
            let mut state =
                editor_with_cursor("- [ ] parent\n  - [x] ~~child1~~\n  - [ ] |child2\n");
            state.toggle_checkbox(2);
            let text = state.text();
            assert!(
                text.contains("[x] ~~parent~~"),
                "parent should be auto-checked"
            );
            assert!(
                text.contains("[x] ~~child1~~"),
                "child1 should remain checked"
            );
            assert!(text.contains("[x] ~~child2~~"), "child2 should be checked");
        }

        #[test]
        fn uncheck_child_unchecks_parent() {
            let mut state =
                editor_with_cursor("- [x] ~~parent~~\n  - [x] ~~|child1~~\n  - [x] ~~child2~~\n");
            state.toggle_checkbox(1);
            let text = state.text();
            assert!(text.contains("[ ] parent"), "parent should be unchecked");
            assert!(text.contains("[ ] child1"), "child1 should be unchecked");
            assert!(
                text.contains("[x] ~~child2~~"),
                "child2 should remain checked"
            );
        }

        #[test]
        fn checkbox_cascade_caches_match_fresh_parse() {
            // The suspend_caches batching must leave the derived inline styles identical
            // to a from-scratch parse of the resulting text (rebuilt once at the end).
            let mut state = editor_with_cursor("- [ ] |parent\n  - [ ] child1\n  - [ ] child2\n");
            state.toggle_checkbox(0); // cascades to children
            let mut fresh: Buffer = state.text().parse().unwrap();
            assert_eq!(
                *state.buffer.render_snapshot().inline_styles,
                *fresh.render_snapshot().inline_styles,
                "styles after the cascade equal a fresh parse"
            );
        }

        #[test]
        fn caches_not_frozen_after_cascade() {
            // suspend_caches must reset on every exit, so a later edit re-derives caches.
            let mut state = editor_with_cursor("- [ ] |task\nplain line\n");
            state.toggle_checkbox(0);
            let at = state.text().find("plain").unwrap();
            state.set_cursor(at);
            state.insert_text("**bold** ");
            let mut fresh: Buffer = state.text().parse().unwrap();
            assert_eq!(
                *state.buffer.render_snapshot().inline_styles,
                *fresh.render_snapshot().inline_styles,
                "caches re-derived after a post-cascade edit (not frozen)"
            );
        }

        #[test]
        fn deeply_nested_propagation_down() {
            let mut state = editor_with_cursor("- [ ] |level1\n  - [ ] level2\n    - [ ] level3\n");
            state.toggle_checkbox(0);
            let text = state.text();
            assert!(text.contains("[x] ~~level1~~"), "level1 should be checked");
            assert!(text.contains("[x] ~~level2~~"), "level2 should be checked");
            assert!(text.contains("[x] ~~level3~~"), "level3 should be checked");
        }

        #[test]
        fn deeply_nested_propagation_up() {
            let mut state = editor_with_cursor("- [ ] level1\n  - [ ] level2\n    - [ ] |level3\n");
            state.toggle_checkbox(2);
            let text = state.text();
            assert!(
                text.contains("[x] ~~level1~~"),
                "level1 should be auto-checked"
            );
            assert!(
                text.contains("[x] ~~level2~~"),
                "level2 should be auto-checked"
            );
            assert!(text.contains("[x] ~~level3~~"), "level3 should be checked");
        }

        #[test]
        fn mixed_siblings_parent_stays_unchecked() {
            let mut state = editor_with_cursor("- [ ] parent\n  - [ ] |child1\n  - [ ] child2\n");
            state.toggle_checkbox(1);
            let text = state.text();
            assert!(text.contains("[ ] parent"), "parent should stay unchecked");
            assert!(text.contains("[x] ~~child1~~"), "child1 should be checked");
            assert!(text.contains("[ ] child2"), "child2 should stay unchecked");
        }
    }

    mod checkbox_undo_tests {
        use super::*;

        #[test]
        fn single_undo_reverts_cascade_to_children_and_parent() {
            // Checking child2 checks child2 AND auto-checks the parent — a cascade
            // spanning multiple lines. One undo must revert the entire toggle.
            let before = trim_raw("- [ ] parent\n  - [x] ~~child1~~\n  - [ ] child2\n");
            let mut state =
                editor_with_cursor("- [ ] parent\n  - [x] ~~child1~~\n  - [ ] |child2\n");
            state.toggle_checkbox(2);
            assert!(
                state.text().contains("[x] ~~parent~~"),
                "parent auto-checked"
            );
            assert!(state.text().contains("[x] ~~child2~~"), "child2 checked");

            state.buffer.undo();
            assert_eq!(state.text(), before, "one undo reverts the whole cascade");
            assert!(!state.buffer.can_undo(), "toggle was a single undo entry");
        }

        #[test]
        fn redo_reapplies_full_cascade() {
            let mut state =
                editor_with_cursor("- [ ] parent\n  - [x] ~~child1~~\n  - [ ] |child2\n");
            state.toggle_checkbox(2);
            let after = state.text();

            state.buffer.undo();
            state.buffer.redo();
            assert_eq!(state.text(), after, "one redo re-applies the whole cascade");
        }

        #[test]
        fn toggle_leaf_box_text_and_single_entry() {
            let mut state = editor_with_cursor("- [ ] |task\n");
            state.toggle_checkbox(0);
            assert_eq!(state.text(), "- [x] ~~task~~\n");
            state.buffer.undo();
            assert_eq!(state.text(), "- [ ] task\n");
            assert!(!state.buffer.can_undo(), "leaf toggle is one undo entry");
        }

        #[test]
        fn toggle_parent_all_children_text() {
            let mut state = editor_with_cursor("- [ ] |parent\n  - [ ] child1\n  - [ ] child2\n");
            state.toggle_checkbox(0);
            assert_eq!(
                state.text(),
                "- [x] ~~parent~~\n  - [x] ~~child1~~\n  - [x] ~~child2~~\n"
            );
        }

        #[test]
        fn uncheck_cascades_to_parent_text() {
            let mut state =
                editor_with_cursor("- [x] ~~parent~~\n  - [x] ~~|child1~~\n  - [x] ~~child2~~\n");
            state.toggle_checkbox(1);
            assert_eq!(
                state.text(),
                "- [ ] parent\n  - [ ] child1\n  - [x] ~~child2~~\n"
            );
        }
    }

    mod strikethrough_tests {
        use super::*;

        #[test]
        fn strikethrough_add_remove_round_trips() {
            let mut state = EditorState::new("hello world\n");
            state.toggle_line_strikethrough(0, true, 0);
            assert_eq!(state.text(), "~~hello world~~\n");
            state.toggle_line_strikethrough(0, false, 0);
            assert_eq!(
                state.text(),
                "hello world\n",
                "round-trip is byte-identical"
            );
        }

        #[test]
        fn strikethrough_add_is_single_undo() {
            let mut state = EditorState::new("hello world\n");
            state.toggle_line_strikethrough(0, true, 0);
            assert_eq!(state.text(), "~~hello world~~\n");
            state.buffer.undo();
            assert_eq!(
                state.text(),
                "hello world\n",
                "one undo reverts the whole strikethrough toggle"
            );
            assert!(!state.buffer.can_undo(), "no further undo entries remain");
        }

        #[test]
        fn typing_coalesces_into_word_undo_steps() {
            let mut state = EditorState::new("");
            for c in "hi there".chars() {
                state.insert_text(&c.to_string());
            }
            assert_eq!(state.text(), "hi there");
            // Word-granular undo: "there", then the space, then "hi".
            state.buffer.undo();
            assert_eq!(state.text(), "hi ", "undo removes the whole last word");
            state.buffer.undo();
            assert_eq!(state.text(), "hi", "undo removes the space");
            state.buffer.undo();
            assert_eq!(state.text(), "", "undo removes the first word");
        }

        #[test]
        fn backspace_coalesces_into_one_undo() {
            let mut state = EditorState::new("word\n");
            state.set_cursor(4); // end of "word"
            for _ in 0..4 {
                state.delete_backward();
            }
            assert_eq!(state.text(), "\n");
            state.buffer.undo();
            assert_eq!(
                state.text(),
                "word\n",
                "one undo restores the backspaced word"
            );
        }

        #[test]
        fn paste_is_its_own_undo_step() {
            let mut state = EditorState::new("");
            state.insert_text("ab"); // multi-char (paste-like) — not coalescable
            for c in "cd".chars() {
                state.insert_text(&c.to_string());
            }
            assert_eq!(state.text(), "abcd");
            state.buffer.undo();
            assert_eq!(state.text(), "ab", "typing after a paste undoes separately");
            state.buffer.undo();
            assert_eq!(state.text(), "", "the paste is its own step");
        }

        #[test]
        fn strikethrough_remove_is_single_undo() {
            let mut state = EditorState::new("~~hello world~~\n");
            state.toggle_line_strikethrough(0, false, 0);
            assert_eq!(state.text(), "hello world\n");
            state.buffer.undo();
            assert_eq!(state.text(), "~~hello world~~\n", "one undo restores `~~`");
            assert!(!state.buffer.can_undo(), "no further undo entries remain");
        }

        #[test]
        fn strikethrough_preserves_surrounding_whitespace() {
            // Leading/trailing whitespace must be outside the `~~` wrap.
            let mut state = EditorState::new("  hello  \n");
            state.toggle_line_strikethrough(0, true, 0);
            assert_eq!(state.text(), "  ~~hello~~  \n");
            state.toggle_line_strikethrough(0, false, 0);
            assert_eq!(state.text(), "  hello  \n");
        }
    }
}

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

    #[test]
    fn nested_context_simple_list() {
        let state = EditorState::new("- item\n");
        let cursor_offset = 2; // on "item"
        let markers = state.build_nested_context(cursor_offset);
        assert_eq!(markers.len(), 1);
        assert!(matches!(
            markers[0],
            MarkerKind::ListItem { ordered: false, .. }
        ));
    }

    #[test]
    fn nested_context_nested_list() {
        let state = EditorState::new("- parent\n  - child\n");
        let cursor_offset = 14; // on "child"
        let markers = state.build_nested_context(cursor_offset);
        // Should show: - -
        assert_eq!(markers.len(), 2);
        assert!(matches!(
            markers[0],
            MarkerKind::ListItem { ordered: false, .. }
        ));
        assert!(matches!(
            markers[1],
            MarkerKind::ListItem { ordered: false, .. }
        ));
    }

    #[test]
    fn nested_context_checkbox_nested() {
        let state = EditorState::new("- [x] parent\n  - [ ] child\n");
        let cursor_offset = 20; // on "child"
        let markers = state.build_nested_context(cursor_offset);
        // Should show: - [x] - [ ]
        assert_eq!(markers.len(), 4);
        assert!(matches!(
            markers[0],
            MarkerKind::ListItem { ordered: false, .. }
        ));
        assert!(matches!(markers[1], MarkerKind::Checkbox { checked: true }));
        assert!(matches!(
            markers[2],
            MarkerKind::ListItem { ordered: false, .. }
        ));
        assert!(matches!(
            markers[3],
            MarkerKind::Checkbox { checked: false }
        ));
    }

    #[test]
    fn nested_context_blockquote_list() {
        let state = EditorState::new("> - item\n");
        let cursor_offset = 4; // on "item"
        let markers = state.build_nested_context(cursor_offset);
        // Should show: > -
        assert_eq!(markers.len(), 2);
        assert!(matches!(markers[0], MarkerKind::BlockQuote));
        assert!(matches!(
            markers[1],
            MarkerKind::ListItem { ordered: false, .. }
        ));
    }

    #[test]
    fn nested_context_ordered_list() {
        let state = EditorState::new("1. first\n2. second\n");
        let cursor_offset = 12; // on "second"
        let markers = state.build_nested_context(cursor_offset);
        assert_eq!(markers.len(), 1);
        assert!(matches!(
            markers[0],
            MarkerKind::ListItem { ordered: true, .. }
        ));
    }

    #[test]
    fn nested_context_empty_line() {
        let state = EditorState::new("hello\n");
        let cursor_offset = 2; // on "llo"
        let markers = state.build_nested_context(cursor_offset);
        assert_eq!(markers.len(), 0);
    }
}

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

    #[test]
    fn check_blockquote_list_paragraph() {
        let state = EditorState::new("> - hey\n>   paragraph\n");

        if let Some(tree) = state.buffer.tree() {
            let root = tree.block_tree().root_node();
            eprintln!("Tree: {}", root.to_sexp());
        }
    }

    #[test]
    fn check_simple_list_paragraph() {
        let state = EditorState::new("- hey\n  paragraph\n");

        if let Some(tree) = state.buffer.tree() {
            let root = tree.block_tree().root_node();
            eprintln!("Tree: {}", root.to_sexp());
        }
    }
}

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

    #[test]
    fn show_tree_detail() {
        let content = "> - hey\n>   paragraph\n";
        eprintln!("Content: {:?}", content);
        eprintln!("Bytes:");
        for (i, b) in content.bytes().enumerate() {
            eprintln!("  {}: {:?} ({})", i, b as char, b);
        }

        let state = EditorState::new(content);

        if let Some(tree) = state.buffer.tree() {
            let root = tree.block_tree().root_node();
            eprintln!("\nTree: {}", root.to_sexp());

            // Show each node with byte ranges
            fn print_node(node: tree_sitter::Node, indent: usize) {
                eprintln!(
                    "{}{} [{}-{}]",
                    "  ".repeat(indent),
                    node.kind(),
                    node.start_byte(),
                    node.end_byte()
                );
                for child in node.children(&mut node.walk()) {
                    print_node(child, indent + 1);
                }
            }
            print_node(root, 0);
        }
    }
}