mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
//! The text-editing core: a `String` + a byte cursor + selection anchor + undo/redo,
//! and `apply(EditOp)` — the single interpreter every input handler funnels through.
//!
//! Storage is a plain `String` (fine for typical source files; all mutation is
//! funnelled through `apply` so a rope can replace this later without touching
//! call sites). Columns are counted in **chars** for now (display-width / tabs /
//! CJK are a P2 refinement). All byte offsets are kept on char boundaries.

use crate::clipboard::Clipboard;
use crate::edit_op::{CaseTransform, EditOp, EditOutcome, TextEdit};

mod persistent_undo;
pub use persistent_undo::{load_history_from, save_history_to, undo_path_for};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct Snapshot {
    text: String,
    cursor: usize,
    anchor: Option<usize>,
    /// Seconds since UNIX epoch when this snapshot was taken. Used by vim's
    /// `:earlier <N><unit>` / `:later <N><unit>` to walk the undo/redo
    /// stacks by elapsed wall-clock. `#[serde(default)]` so old persisted
    /// histories without the field still load (they'll just lack the
    /// time-walk ability for older snapshots).
    #[serde(default)]
    timestamp: u64,
}

/// Per-line `(col, depth)` for every `()[]{}` bracket in `text`. Depth is the
/// nesting level — `0` for the outermost pair, `1` for nested inside, etc. —
/// shared across `(`, `[`, `{` (no kind-mismatch tracking; the renderer just
/// wants a stable color cycle, not strict balance). Used by the editor's
/// rainbow-brackets renderer.
///
/// Cheap to call (~one walk of the buffer); the editor view skips it when
/// `[ui] bracket_rainbow` is off so files without rainbow pay nothing.
/// Byte ranges of every whole-word, case-sensitive occurrence of `word` in
/// `text`. "Whole word" means the chars immediately before and after the
/// match aren't `[A-Za-z0-9_]`. Used by the "highlight word under cursor"
/// render feature + the "select all occurrences" multi-cursor gesture.
/// dial.nvim-style smart increment. Looks at the word under the cursor
/// (on `line`) and tries to bump it by `delta`. Recognized shapes:
/// `true`/`false`, `yes`/`no`, `on`/`off`, day-of-week, month names,
/// ISO dates `YYYY-MM-DD`. Returns `(start_byte, end_byte, new_str)` on
/// hit, or `None` to let the caller fall back to its number path.
pub fn smart_increment_at(
    text: &str,
    cursor: usize,
    line: usize,
    delta: i64,
) -> Option<(usize, usize, String)> {
    let line_start = if line == 0 {
        0
    } else {
        // Walk to the nth newline.
        let mut n = 0;
        let bytes = text.as_bytes();
        let mut i = 0;
        while i < bytes.len() && n < line {
            if bytes[i] == b'\n' {
                n += 1;
            }
            i += 1;
        }
        i
    };
    let line_end = text[line_start..]
        .find('\n')
        .map(|p| line_start + p)
        .unwrap_or(text.len());
    let line_text = &text[line_start..line_end];
    let cur_rel = cursor.saturating_sub(line_start).min(line_text.len());
    // ISO date pattern first — broader span than the boolean word.
    if let Some((rs, re, s)) = try_iso_date(line_text, cur_rel, delta) {
        return Some((line_start + rs, line_start + re, s));
    }
    // Word-based matches.
    let bytes = line_text.as_bytes();
    let is_id = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
    let mut start = cur_rel.min(bytes.len());
    while start > 0 && is_id(bytes[start - 1]) {
        start -= 1;
    }
    let mut end = cur_rel.min(bytes.len());
    while end < bytes.len() && is_id(bytes[end]) {
        end += 1;
    }
    if start >= end {
        return None;
    }
    let word = &line_text[start..end];
    let new = swap_keyword(word, delta)?;
    Some((line_start + start, line_start + end, new))
}

fn swap_keyword(word: &str, delta: i64) -> Option<String> {
    // Case-preserving boolean / yes-no toggle. `delta` direction doesn't
    // matter for booleans — both `Ctrl+A` and `Ctrl+X` toggle.
    if let Some(p) = boolean_pair(word) {
        return Some(p);
    }
    // Day-of-week / month names — cycle by delta.
    if let Some(p) = cycle_named(
        word,
        &["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        delta,
    ) {
        return Some(p);
    }
    if let Some(p) = cycle_named(
        word,
        &[
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
            "Sunday",
        ],
        delta,
    ) {
        return Some(p);
    }
    if let Some(p) = cycle_named(
        word,
        &[
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        ],
        delta,
    ) {
        return Some(p);
    }
    if let Some(p) = cycle_named(
        word,
        &[
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December",
        ],
        delta,
    ) {
        return Some(p);
    }
    None
}

fn boolean_pair(word: &str) -> Option<String> {
    // Case-preserving toggle.
    let pairs = [
        ("true", "false"),
        ("True", "False"),
        ("TRUE", "FALSE"),
        ("yes", "no"),
        ("Yes", "No"),
        ("YES", "NO"),
        ("on", "off"),
        ("On", "Off"),
        ("ON", "OFF"),
    ];
    for (a, b) in pairs {
        if word == a {
            return Some(b.to_string());
        }
        if word == b {
            return Some(a.to_string());
        }
    }
    None
}

fn cycle_named(word: &str, table: &[&str], delta: i64) -> Option<String> {
    // Case-insensitive match; preserve the lookup table's case.
    let idx = table.iter().position(|t| t.eq_ignore_ascii_case(word))?;
    let n = table.len() as i64;
    let new_idx = ((idx as i64 + delta).rem_euclid(n)) as usize;
    Some(table[new_idx].to_string())
}

fn try_iso_date(line: &str, cur_rel: usize, delta: i64) -> Option<(usize, usize, String)> {
    // Find an ISO date `YYYY-MM-DD` that straddles cur_rel.
    let bytes = line.as_bytes();
    if bytes.len() < 10 {
        return None;
    }
    let cur_rel = cur_rel.min(bytes.len());
    // Scan small windows around cur_rel.
    let lo = cur_rel.saturating_sub(10);
    let hi = (cur_rel + 10).min(bytes.len().saturating_sub(9));
    for s in lo..=hi {
        if s + 10 > bytes.len() {
            break;
        }
        let slice = &line[s..s + 10];
        if !looks_like_iso(slice) {
            continue;
        }
        if !(s <= cur_rel && cur_rel <= s + 10) {
            continue;
        }
        let new = bump_iso_date(slice, delta)?;
        return Some((s, s + 10, new));
    }
    None
}

fn looks_like_iso(s: &str) -> bool {
    let bytes = s.as_bytes();
    bytes.len() == 10
        && bytes[0..4].iter().all(|b| b.is_ascii_digit())
        && bytes[4] == b'-'
        && bytes[5..7].iter().all(|b| b.is_ascii_digit())
        && bytes[7] == b'-'
        && bytes[8..10].iter().all(|b| b.is_ascii_digit())
}

fn bump_iso_date(date: &str, delta: i64) -> Option<String> {
    let y: i64 = date[0..4].parse().ok()?;
    let m: u32 = date[5..7].parse().ok()?;
    let d: u32 = date[8..10].parse().ok()?;
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    let (ny, nm, nd) = add_days(y, m, d, delta);
    Some(format!("{:04}-{:02}-{:02}", ny, nm, nd))
}

fn add_days(y: i64, m: u32, d: u32, delta: i64) -> (i64, u32, u32) {
    // Convert to a Julian-ish day-number, add delta, convert back.
    // Implementation: brute-force day-by-day for small deltas (which
    // is the common case for Ctrl+A/X repeated presses). For large
    // deltas we'd want a real algorithm; this covers ±365 in 365 ops.
    let mut y = y;
    let mut m = m;
    let mut d = d;
    let mut left = delta;
    while left > 0 {
        // Forward one day.
        d += 1;
        if d > days_in_month(y, m) {
            d = 1;
            m += 1;
            if m > 12 {
                m = 1;
                y += 1;
            }
        }
        left -= 1;
    }
    while left < 0 {
        if d > 1 {
            d -= 1;
        } else {
            m = if m == 1 {
                y -= 1;
                12
            } else {
                m - 1
            };
            d = days_in_month(y, m);
        }
        left += 1;
    }
    (y, m, d)
}

fn days_in_month(year: i64, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
                29
            } else {
                28
            }
        }
        _ => 0,
    }
}

/// vim-matchup-style HTML/XML tag matching. If the cursor sits inside or
/// on a `<TagName ...>` (or `</TagName>`), return the byte position of
/// the matching tag's `<`. Returns `None` when the cursor isn't on a tag
/// or no match exists (mismatched / self-closing / void).
pub fn tag_match_at(text: &str, cursor: usize) -> Option<usize> {
    // Find the enclosing tag — the `<` and `>` that bracket the cursor.
    let (open_lt, close_gt, is_closing) = enclosing_tag(text, cursor)?;
    let inside = &text[open_lt + 1..close_gt];
    if inside.is_empty() {
        return None;
    }
    // Self-closing or void: no match exists.
    if inside.ends_with('/') {
        return None;
    }
    let name = extract_tag_name(if is_closing { &inside[1..] } else { inside })?;
    if name.is_empty() {
        return None;
    }
    if is_closing {
        find_opening_tag(text, name, open_lt)
    } else {
        find_closing_tag(text, name, close_gt)
    }
}

/// Find the `<` and `>` that enclose `cursor`, plus whether it's a closing tag.
fn enclosing_tag(text: &str, cursor: usize) -> Option<(usize, usize, bool)> {
    let bytes = text.as_bytes();
    let cursor = cursor.min(bytes.len());
    // If the cursor sits ON a `<`, that's our open. Otherwise walk back.
    let mut lt = if cursor < bytes.len() && bytes[cursor] == b'<' {
        Some(cursor)
    } else {
        None
    };
    if lt.is_none() {
        // Walk back to find `<`. Bail if we hit a `>` first (not in a tag).
        let mut i = cursor;
        while i > 0 {
            i -= 1;
            if bytes[i] == b'>' && lt.is_none() {
                return None;
            }
            if bytes[i] == b'<' {
                lt = Some(i);
                break;
            }
        }
    }
    let lt = lt?;
    // Walk forward to find the matching `>`.
    let mut gt = None;
    let mut j = lt + 1;
    while j < bytes.len() {
        if bytes[j] == b'>' {
            gt = Some(j);
            break;
        }
        if bytes[j] == b'<' {
            return None; // nested `<` — malformed
        }
        j += 1;
    }
    let gt = gt?;
    if gt < cursor {
        return None;
    }
    let is_closing = gt > lt + 1 && bytes[lt + 1] == b'/';
    Some((lt, gt, is_closing))
}

fn extract_tag_name(inside: &str) -> Option<&str> {
    let end = inside
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == ':'))
        .unwrap_or(inside.len());
    if end == 0 { None } else { Some(&inside[..end]) }
}

fn find_opening_tag(text: &str, name: &str, before_byte: usize) -> Option<usize> {
    // Walk backward looking for the matching `<TagName` at depth 0.
    let mut depth = 1i32;
    let mut i = before_byte;
    while i > 0 {
        // Find the previous `<`.
        let prev_lt = text[..i].rfind('<')?;
        let after = &text[prev_lt + 1..];
        let is_close = after.starts_with('/');
        let body = if is_close { &after[1..] } else { after };
        if extract_tag_name(body).map(|n| n == name).unwrap_or(false) {
            if is_close {
                depth += 1;
            } else {
                depth -= 1;
                if depth == 0 {
                    return Some(prev_lt);
                }
            }
        }
        i = prev_lt;
    }
    None
}

fn find_closing_tag(text: &str, name: &str, after_byte: usize) -> Option<usize> {
    let mut depth = 1i32;
    let mut search_from = after_byte;
    while search_from < text.len() {
        let next_lt_rel = text[search_from..].find('<')?;
        let lt = search_from + next_lt_rel;
        let after = &text[lt + 1..];
        let is_close = after.starts_with('/');
        let body = if is_close { &after[1..] } else { after };
        if extract_tag_name(body).map(|n| n == name).unwrap_or(false) {
            if is_close {
                depth -= 1;
                if depth == 0 {
                    return Some(lt);
                }
            } else {
                // Skip self-closing tags (`<Foo />`) — they don't add depth.
                let close_gt = text[lt..].find('>').map(|p| lt + p);
                if let Some(g) = close_gt
                    && text[lt..g].ends_with('/')
                {
                    search_from = g + 1;
                    continue;
                }
                depth += 1;
            }
        }
        search_from = lt + 1;
    }
    None
}

/// Find the innermost enclosing HTML/XML/JSX tag pair around `cursor`.
/// Returns `(open_lt, open_gt, close_lt, close_gt)` — the byte offsets
/// of the opening `<` and `>` of the open tag, and the `<` and `>` of
/// the matching close tag. `open_gt` is the byte AFTER the open's `>`
/// (exclusive end); same for `close_gt`. Returns `None` when the
/// cursor isn't inside a tag pair (top-level text) or a matching
/// close tag can't be found (self-closing / void / malformed).
///
/// Used by vim's `dit` / `dat` / `cit` / `cat` / etc. text objects.
/// nvchad-user SEV-2 2026-07-10 fix.
pub fn enclosing_tag_pair(text: &str, cursor: usize) -> Option<(usize, usize, usize, usize)> {
    let bytes = text.as_bytes();
    let cursor = cursor.min(bytes.len());
    // Walk backward from `cursor` looking for `<TagName>` opens whose
    // matching `</TagName>` sits AT OR AFTER the cursor. First match
    // wins (innermost).
    let mut i = cursor;
    loop {
        // Find the previous `<`.
        let mut lt = None;
        let mut j = i;
        while j > 0 {
            j -= 1;
            if bytes[j] == b'<' {
                lt = Some(j);
                break;
            }
        }
        let lt = lt?;
        // Find the matching `>` for this open. If none, stop.
        let after = &text[lt + 1..];
        let gt_rel = after.find('>')?;
        let gt = lt + 1 + gt_rel;
        // Skip closing tags (`</Foo>`) — we want open tags.
        // Skip self-closing tags (`<Foo />`) — no matching close.
        let is_closing = bytes.get(lt + 1) == Some(&b'/');
        let is_self_closing = gt > lt && text[lt..gt].ends_with('/');
        if !is_closing && !is_self_closing {
            let inside = &text[lt + 1..gt];
            if let Some(name) = extract_tag_name(inside)
                && let Some(close_lt) = find_closing_tag(text, name, gt + 1)
            {
                // Only accept when the cursor falls between the two.
                // Vim's dit/dat wants "enclosing" — cursor sits in
                // the body OR on either tag's cells.
                let close_gt_rel = text[close_lt..].find('>');
                if let Some(cgr) = close_gt_rel {
                    let close_gt = close_lt + cgr;
                    if cursor >= lt && cursor <= close_gt {
                        return Some((lt, gt + 1, close_lt, close_gt + 1));
                    }
                }
            }
        }
        // No match at this `<` — keep walking further back.
        if lt == 0 {
            return None;
        }
        i = lt;
    }
}

pub fn find_whole_word_occurrences(text: &str, word: &str) -> Vec<(usize, usize)> {
    if word.is_empty() || word.len() > text.len() {
        return Vec::new();
    }
    let bytes = text.as_bytes();
    let is_id = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
    let wlen = word.len();
    let mut out: Vec<(usize, usize)> = Vec::new();
    let mut start = 0usize;
    while let Some(off) = text[start..].find(word) {
        let s = start + off;
        let e = s + wlen;
        let before_ok = s == 0 || !is_id(bytes[s - 1]);
        let after_ok = e == text.len() || !is_id(bytes[e]);
        if before_ok && after_ok {
            out.push((s, e));
        }
        start = s + 1; // overlap-safe: step one byte past the start
    }
    out
}

pub fn bracket_depths_per_line(text: &str) -> Vec<Vec<(usize, u32)>> {
    let mut out: Vec<Vec<(usize, u32)>> = vec![Vec::new()];
    let mut depth: u32 = 0;
    let mut col: usize = 0;
    for c in text.chars() {
        if c == '\n' {
            out.push(Vec::new());
            col = 0;
            continue;
        }
        match c {
            '(' | '[' | '{' => {
                out.last_mut().unwrap().push((col, depth));
                depth = depth.saturating_add(1);
            }
            ')' | ']' | '}' => {
                depth = depth.saturating_sub(1);
                out.last_mut().unwrap().push((col, depth));
            }
            _ => {}
        }
        col += 1;
    }
    out
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CharClass {
    Word,
    Punct,
    Space,
}

fn class_of(c: char) -> CharClass {
    if c.is_whitespace() {
        CharClass::Space
    } else if c.is_alphanumeric() || c == '_' {
        CharClass::Word
    } else {
        CharClass::Punct
    }
}

/// Vertical motions keep the "goal column" so repeated up/down through short
/// lines doesn't shrink the target. Everything else resets it to the new column.
fn op_preserves_goal_col(op: &EditOp) -> bool {
    use EditOp::*;
    match op {
        MoveUp | MoveDown | PageUp | PageDown | HalfPageUp | HalfPageDown => true,
        Repeat(_, inner) => op_preserves_goal_col(inner),
        // Atomic groups preserve goal col iff EVERY inner op does —
        // conservative default so a mixed group (motion + edit) still
        // resets goal_col.
        Atomic(ops) => ops.iter().all(op_preserves_goal_col),
        _ => false,
    }
}

/// Matching closing char for an auto-pair open char, or `None` if `c` isn't a
/// configured open. Single-char pairs only.
/// Closing char for a bracket-pair text object opener (`(` → `)`, `[` → `]`,
/// `{` → `}`). For any non-bracket the close is the same char (so `match_close_for`
/// composes safely with quotes if you ever call it on one).
fn match_close_for(open: char) -> char {
    match open {
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '<' => '>',
        c => c,
    }
}

/// Forward depth-balanced match for a `{`. Walks from `open_byte` (must
/// point at a `{`) and returns the byte offset of the matching `}` or
/// `None` if unbalanced. Bare scan — doesn't respect strings/comments
/// (good enough for the text-object MVP; refinement is a follow-up).
/// Indent width of the line starting at `line_start`. Treats tabs
/// as 8 spaces (Python's `tabnanny`-compatible default; also matches
/// vim's `tabstop=8` historical default). Used by
/// [`Editor::enclosing_indent_scope`] for indent-scoped languages.
fn line_indent(text: &str, line_start: usize) -> usize {
    let bytes = text.as_bytes();
    let mut n = 0;
    let mut i = line_start;
    while i < bytes.len() {
        match bytes[i] {
            b' ' => n += 1,
            b'\t' => n += 8,
            _ => break,
        }
        i += 1;
    }
    n
}

fn match_close_after(text: &str, open_byte: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    if bytes.get(open_byte) != Some(&b'{') {
        return None;
    }
    let mut depth: i32 = 0;
    let mut i = open_byte;
    while i < bytes.len() {
        match bytes[i] {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

fn auto_pair_close(c: char) -> Option<char> {
    match c {
        '(' => Some(')'),
        '[' => Some(']'),
        '{' => Some('}'),
        '"' => Some('"'),
        '\'' => Some('\''),
        '`' => Some('`'),
        _ => None,
    }
}

/// True if `c` is one of the close chars our auto-pair would have inserted.
/// (Used for the "skip over an auto-inserted close" shortcut.)
fn is_auto_pair_close(c: char) -> bool {
    matches!(c, ')' | ']' | '}' | '"' | '\'' | '`')
}

/// Whether an op mutates the buffer text (adds/removes/replaces
/// characters). Motions, selection ops, undo/redo, and clipboard
/// side effects return `false`. Used by `Repeat` in apply_one to
/// decide whether to wrap in an atomic-undo group so `<count><op>`
/// combos (`3dd`, `5x`, `3J`) collapse into a single undo entry.
/// nvchad-round-14 SEV-2 2026-07-14.
fn op_mutates_buffer(op: &EditOp) -> bool {
    use EditOp::*;
    match op {
        // Text mutations. Kept as an explicit allow-list so a new
        // motion-like variant added later doesn't accidentally opt
        // into atomic-undo grouping.
        InsertChar(_)
        | InsertStr(_)
        | InsertCharFromLine { .. }
        | InsertNewline
        | InsertNewlineBelow
        | InsertNewlineAbove
        | Backspace
        | DeleteForward
        | DeleteWordLeft
        | DeleteWordRight
        | DeleteToLineStart
        | DeleteToLineEnd
        | DeleteLine
        | DeleteSelection
        | DeleteBlock
        | ReplaceSelection(_)
        | ReplaceCharAtCursor(_)
        | OverwriteCharAndAdvance(_)
        | ReplaceUndoOne
        | ReplaceRange { .. }
        | Indent
        | Outdent
        | ToggleLineComment
        | MoveLineUp
        | MoveLineDown
        | DuplicateLine
        | JoinLines { .. }
        | TransformSelectionCase(_)
        | ToggleCaseChar
        | ChangeNumberAtCursor { .. }
        | ReflowParagraph { .. }
        | AlignSelection { .. }
        | SurroundSelection { .. }
        | DeleteSurround(_)
        | ChangeSurround { .. }
        | PasteAfter
        | PasteBefore
        | PasteAfterEnd
        | PasteBeforeEnd
        | Paste
        | CutSelection => true,
        // Recurse into wrappers.
        Repeat(_, inner) => op_mutates_buffer(inner),
        Atomic(ops) => ops.iter().any(op_mutates_buffer),
        // Everything else (motions, selection ops, undo/redo, yank,
        // clipboard side effects, meta) leaves buffer text alone.
        _ => false,
    }
}

/// Whether an op is (a chain of) typed characters — used to decide whether to
/// keep the coalescing undo run alive.
fn op_is_insert_char(op: &EditOp) -> bool {
    match op {
        EditOp::InsertChar(_) => true,
        EditOp::Repeat(_, inner) => op_is_insert_char(inner),
        _ => false,
    }
}

/// Infer a single `TextEdit` for an op whose shape we don't explicitly track,
/// using only the before/after `(len, cursor)` snapshot. Returns `Some` when
/// the shape matches one of the canonical single-edit patterns (insert at
/// cursor, backspace-style, forward-delete-style, cursor-on-right selection
/// delete, cursor-on-left selection delete). `None` for anything else —
/// callers treat that as "untracked; drop the cached parse tree."
///
/// This catches ~95% of edits during typing without needing to instrument every
/// `apply_one` arm. The remaining ops (multi-cursor fan-out, indent/outdent
/// across N lines, auto-pair inserting two chars while cursor advances by one,
/// JoinLines, etc.) fall through to a full reparse.
fn infer_single_edit(
    before_len: usize,
    after_len: usize,
    before_cursor: usize,
    after_cursor: usize,
) -> Option<TextEdit> {
    if before_len == after_len {
        return None;
    }
    let len_delta = after_len as i64 - before_len as i64;
    let cur_delta = after_cursor as i64 - before_cursor as i64;
    if len_delta > 0 {
        // Pure insertion. Cursor advanced by exactly `len_delta` ⇒ insertion
        // happened at the pre-edit cursor position. Inserts that don't move
        // the cursor (rare: `InsertNewlineBelow` etc.) bail to None.
        if cur_delta == len_delta {
            Some(TextEdit {
                start_byte: before_cursor,
                old_end_byte: before_cursor,
                new_end_byte: after_cursor,
            })
        } else {
            None
        }
    } else {
        let n = (-len_delta) as usize;
        if cur_delta == len_delta {
            // Backspace-style or selection-delete with cursor at the right
            // end of the selection: deleted range was `[after_cursor, before_cursor)`.
            Some(TextEdit {
                start_byte: after_cursor,
                old_end_byte: before_cursor,
                new_end_byte: after_cursor,
            })
        } else if cur_delta == 0 {
            // Forward-delete-style or selection-delete with cursor at the
            // left end of the selection: deleted range was
            // `[before_cursor, before_cursor + n)`.
            Some(TextEdit {
                start_byte: before_cursor,
                old_end_byte: before_cursor + n,
                new_end_byte: before_cursor,
            })
        } else {
            None
        }
    }
}

const UNDO_LIMIT: usize = 2000;

#[derive(Debug, Clone)]
pub struct Editor {
    text: String,
    cursor: usize,
    anchor: Option<usize>,
    /// Sticky column for vertical motion. `None` = "recompute from current
    /// cursor position when a vertical motion reads it." Marking dirty
    /// (`None`) is O(1); [`Self::col_at_byte`] is O(n), so recomputing
    /// eagerly on every edit dominated the hot path on 5 MB files
    /// (~2.9 ms/keystroke → sub-µs after lazification).
    goal_col: Option<usize>,
    tab_width: usize,
    comment_token: String,
    /// Closing token for block-comment-style line toggling (HTML's `-->`,
    /// CSS's `*/`). Empty for languages where the line-comment is a pure
    /// prefix (`//`, `#`, `--`). Wrapped + unwrapped together with
    /// `comment_token` in `ToggleLineComment`.
    comment_token_close: String,
    undo: Vec<Snapshot>,
    redo: Vec<Snapshot>,
    /// True while a coalescing run of `InsertChar` is in progress.
    in_insert_run: bool,
    /// Auto-insert the matching close char after `(`/`[`/`{`/`"`/`'`/`` ` ``.
    /// Toggled by `[editor] auto_pair`; off in `Editor::new` so unit tests have
    /// vanilla behavior.
    pub auto_pair: bool,
    /// On `Enter`, carry forward the previous line's leading whitespace
    /// (`auto_indent`). Off in `Editor::new` so unit tests get vanilla
    /// newlines; on by default for real buffers via `[editor] auto_indent`.
    pub auto_indent: bool,
    /// `Some((anchor_byte, cursor_byte))` for the last selection that was
    /// "closed" (cleared, yanked, deleted, or changed). vim's `gv` restores
    /// it. `None` until the user has made at least one selection.
    last_selection: Option<(usize, usize)>,
    /// Vim visual-block mode anchor (byte position). When `Some`, the
    /// editor is in block-select mode: the rectangle is computed from
    /// `(byte_to_rowcol(block_anchor), byte_to_rowcol(cursor))` — min/max
    /// of rows + cols. The regular `anchor` is independent (block mode
    /// uses its own state so motions don't conflict with charwise).
    pub block_anchor: Option<usize>,
    /// Additional cursor positions for multi-cursor editing. `self.cursor`
    /// stays the "primary" cursor (the one motions/selection-based ops
    /// continue to work on); ops that opt in (InsertChar, Backspace,
    /// DeleteForward today) apply to the primary AND each extra cursor.
    /// Always sorted, distinct from `cursor`, char-boundary safe.
    pub extra_cursors: Vec<usize>,
    /// Per-extra-cursor anchor (selection start). Parallel array to
    /// `extra_cursors` — `extra_anchors[i]` is the anchor (or `None`) for
    /// the cursor at `extra_cursors[i]`. Maintained by `SelectStart` /
    /// `SelectClear` and by every delete/insert that shifts cursors.
    pub extra_anchors: Vec<Option<usize>>,
    /// Stack of overwrites performed in Replace mode (`R`). Each entry is
    /// either `Some(c)` (the original char that was overwritten — restore
    /// on Backspace) or `None` (a chars was inserted past EOL, no
    /// original — just delete the inserted char on Backspace). Cleared
    /// on `ReplaceSessionBegin`. The vim Replace handler reads it via
    /// `ReplaceUndoOne` to implement vim's "Backspace restores" behavior.
    replace_stack: Vec<Option<char>>,
    /// File extension used to pick syntax/text-object regexes (mirror of
    /// `Buffer.language_ext`). Synced by `Buffer::set_language_ext`; the
    /// editor reads it for the tree-sitter text objects (`if`/`af`/`ic`/
    /// `ac`) so they can scope by `regex_outline` per language.
    pub language_ext: Option<String>,
    /// AI inline ghost-text suggestion — the greyed completion painted
    /// after the cursor (`[ai] inline_suggestions`). `Tab` accepts it,
    /// any edit / cursor move clears it. Set by `App::drain_suggestions`.
    pub ghost_suggestion: Option<String>,
}

impl Editor {
    pub fn new(text: impl Into<String>, tab_width: usize) -> Self {
        Editor {
            text: text.into(),
            cursor: 0,
            anchor: None,
            goal_col: None,
            tab_width: tab_width.max(1),
            comment_token: "// ".to_string(),
            comment_token_close: String::new(),
            undo: Vec::new(),
            redo: Vec::new(),
            in_insert_run: false,
            block_anchor: None,
            auto_pair: false,
            auto_indent: false,
            last_selection: None,
            replace_stack: Vec::new(),
            extra_cursors: Vec::new(),
            extra_anchors: Vec::new(),
            language_ext: None,
            ghost_suggestion: None,
        }
    }

    /// Add a cursor at byte position `byte` (clamped to a char boundary).
    /// No-op if it'd duplicate the primary cursor or an existing extra.
    /// If the primary cursor currently has a selection anchor, the new
    /// extra is anchored at its own position (zero-width selection that
    /// follows the existing selection model — subsequent motions extend
    /// it across all cursors).
    pub fn add_extra_cursor(&mut self, byte: usize) {
        let mut b = byte.min(self.text.len());
        while b < self.text.len() && !self.text.is_char_boundary(b) {
            b += 1;
        }
        // Alt+click at the primary cursor's position is a no-op — the
        // user can't remove the primary from an editor pane. Alt+click
        // at an EXISTING extra cursor REMOVES that extra (VS Code
        // convention: alt+click toggles). mouse-round-10 SEV-3
        // 2026-07-12.
        if b == self.cursor {
            return;
        }
        if let Some(pos) = self.extra_cursors.iter().position(|&c| c == b) {
            self.extra_cursors.remove(pos);
            self.extra_anchors.remove(pos);
            return;
        }
        let anchor_for_new = if self.anchor.is_some() { Some(b) } else { None };
        self.extra_cursors.push(b);
        self.extra_anchors.push(anchor_for_new);
        self.sort_extras();
    }

    /// Add an extra cursor at `cursor` with a real selection anchored at
    /// `anchor` (so the extra spans `[min(anchor,cursor), max(…))`). Used
    /// by "Select all occurrences" (Ctrl+Shift+L) where each hit is a
    /// word range, not just a point — the plain `add_extra_cursor(byte)`
    /// helper synthesizes anchor=cursor for the pointwise mouse case,
    /// which produced zero-length "selections" that made typing INSERT
    /// instead of REPLACE. keyboard-round-10 SEV-2 F2 2026-07-14.
    pub fn add_extra_cursor_with_anchor(&mut self, anchor: usize, cursor: usize) {
        let cur = cursor.min(self.text.len());
        let mut cur = cur;
        while cur < self.text.len() && !self.text.is_char_boundary(cur) {
            cur += 1;
        }
        let mut anc = anchor.min(self.text.len());
        while anc < self.text.len() && !self.text.is_char_boundary(anc) {
            anc += 1;
        }
        if cur == self.cursor {
            return;
        }
        if let Some(pos) = self.extra_cursors.iter().position(|&c| c == cur) {
            self.extra_cursors.remove(pos);
            self.extra_anchors.remove(pos);
            return;
        }
        self.extra_cursors.push(cur);
        self.extra_anchors.push(Some(anc));
        self.sort_extras();
    }

    /// Re-sort `extra_cursors` and keep `extra_anchors` in sync. Public
    /// helpers that mutate the parallel arrays should call this after.
    fn sort_extras(&mut self) {
        if self.extra_cursors.len() < 2 {
            return;
        }
        let mut paired: Vec<(usize, Option<usize>)> = self
            .extra_cursors
            .iter()
            .copied()
            .zip(self.extra_anchors.iter().copied())
            .collect();
        paired.sort_by_key(|&(c, _)| c);
        paired.dedup_by_key(|p| p.0);
        let (cs, ans): (Vec<usize>, Vec<Option<usize>>) = paired.into_iter().unzip();
        self.extra_cursors = cs;
        self.extra_anchors = ans;
    }

    pub fn clear_extra_cursors(&mut self) {
        self.extra_cursors.clear();
        self.extra_anchors.clear();
    }

    /// Move each extra cursor one char left / right (no goal_col since
    /// it's a horizontal motion). Caller has already moved the primary.
    /// Char-boundary safe; clamped to `[0, text.len()]`. Anchors stay put
    /// so selections extend.
    fn move_extras_horizontal(&mut self, dir: i32) {
        if self.extra_cursors.is_empty() {
            return;
        }
        let len = self.text.len();
        let updated: Vec<usize> = self
            .extra_cursors
            .iter()
            .map(|&p| {
                if dir < 0 {
                    self.prev_char_boundary(p)
                } else {
                    self.next_char_boundary(p).min(len)
                }
            })
            .collect();
        self.replace_extra_positions(updated);
    }

    /// Move each extra cursor one row up / down at its current visual
    /// column (independent goal_col per extra). Drops any extra that
    /// runs off the top / bottom of the buffer. Anchors stay put.
    fn move_extras_vertical(&mut self, dir: i32) {
        if self.extra_cursors.is_empty() {
            return;
        }
        let lc = self.line_count();
        let mut pairs: Vec<(usize, Option<usize>)> = Vec::with_capacity(self.extra_cursors.len());
        for (idx, &p) in self.extra_cursors.iter().enumerate() {
            let (row, col) = self.row_col_at(p);
            let next_row = if dir < 0 {
                if row == 0 {
                    continue;
                }
                row - 1
            } else {
                if row + 1 >= lc {
                    continue;
                }
                row + 1
            };
            pairs.push((self.byte_at_col(next_row, col), self.extra_anchors[idx]));
        }
        self.replace_extra_pairs(pairs);
    }

    /// Replace `extra_cursors` with `new_positions`, keeping each pair's
    /// anchor matched by INDEX. Drops cursors that collide with the
    /// primary and dedups against each other.
    fn replace_extra_positions(&mut self, new_positions: Vec<usize>) {
        debug_assert_eq!(new_positions.len(), self.extra_anchors.len());
        let pairs: Vec<(usize, Option<usize>)> = new_positions
            .into_iter()
            .zip(self.extra_anchors.iter().copied())
            .collect();
        self.replace_extra_pairs(pairs);
    }

    fn replace_extra_pairs(&mut self, mut pairs: Vec<(usize, Option<usize>)>) {
        pairs.retain(|&(c, _)| c != self.cursor);
        pairs.sort_by_key(|&(c, _)| c);
        pairs.dedup_by_key(|p| p.0);
        let (cs, ans): (Vec<usize>, Vec<Option<usize>>) = pairs.into_iter().unzip();
        self.extra_cursors = cs;
        self.extra_anchors = ans;
    }

    /// Commit a multi-cursor edit: `cursors[0]` becomes the primary, the
    /// rest get re-paired with `anchors` and re-sorted/deduped. `anchors[0]`
    /// becomes the primary anchor.
    fn commit_multi(&mut self, cursors: Vec<usize>, anchors: Vec<Option<usize>>) {
        debug_assert_eq!(cursors.len(), anchors.len());
        self.cursor = cursors[0];
        self.anchor = anchors[0];
        let pairs: Vec<(usize, Option<usize>)> = cursors[1..]
            .iter()
            .copied()
            .zip(anchors[1..].iter().copied())
            .collect();
        self.replace_extra_pairs(pairs);
    }

    /// Multi-cursor Backspace — each cursor deletes the char before it.
    /// Apply in descending order so earlier offsets stay valid; update
    /// all OTHER cursors as each delete shifts the text. Auto-pair is
    /// skipped (semantics get hairy across N cursors).
    fn multi_delete_backward(&mut self) {
        let mut cursors: Vec<usize> = std::iter::once(self.cursor)
            .chain(self.extra_cursors.iter().copied())
            .collect();
        let mut anchors: Vec<Option<usize>> = std::iter::once(self.anchor)
            .chain(self.extra_anchors.iter().copied())
            .collect();
        let mut order: Vec<usize> = (0..cursors.len()).collect();
        order.sort_by_key(|&i| std::cmp::Reverse(cursors[i]));
        for &i in &order {
            let p = cursors[i];
            if p == 0 {
                continue;
            }
            let prev = self.prev_char_boundary(p);
            let removed = p - prev;
            self.text.replace_range(prev..p, "");
            for (j, c) in cursors.iter_mut().enumerate() {
                if j == i {
                    *c = prev;
                } else if *c >= p {
                    *c = c.saturating_sub(removed);
                } else if *c > prev {
                    *c = prev;
                }
            }
            for av in anchors.iter_mut().flatten() {
                if *av >= p {
                    *av = av.saturating_sub(removed);
                } else if *av > prev {
                    *av = prev;
                }
            }
        }
        self.commit_multi(cursors, anchors);
    }

    /// Apply a unary position-mapping function to every extra cursor.
    /// Used by motion ops (word-left / word-right / etc.) to fan out the
    /// motion across all cursors. Caller has already moved the primary.
    fn move_extras_with<F>(&mut self, mut f: F)
    where
        F: FnMut(&Self, usize) -> usize,
    {
        if self.extra_cursors.is_empty() {
            return;
        }
        let updated: Vec<usize> = self.extra_cursors.iter().map(|&p| f(self, p)).collect();
        self.replace_extra_positions(updated);
    }

    /// Move every extra cursor to the start / end of its own line.
    fn move_extras_to_line_edge(&mut self, to_end: bool) {
        if self.extra_cursors.is_empty() {
            return;
        }
        let updated: Vec<usize> = self
            .extra_cursors
            .iter()
            .map(|&p| {
                let row = self.row_col_at(p).0;
                if to_end {
                    self.line_end(row)
                } else {
                    self.line_start(row)
                }
            })
            .collect();
        self.replace_extra_positions(updated);
    }

    /// Multi-cursor "delete a per-cursor range". The closure receives each
    /// cursor's CURRENT position and returns the `(start, end)` byte range
    /// to remove. Ranges are applied in descending start-position order so
    /// earlier offsets stay valid; cursors after each delete are shifted.
    /// The originating cursor lands at the range start.
    fn multi_delete_range_per_cursor<F>(&mut self, mut range_for: F)
    where
        F: FnMut(&Self, usize) -> (usize, usize),
    {
        let mut cursors: Vec<usize> = std::iter::once(self.cursor)
            .chain(self.extra_cursors.iter().copied())
            .collect();
        let mut anchors: Vec<Option<usize>> = std::iter::once(self.anchor)
            .chain(self.extra_anchors.iter().copied())
            .collect();
        let mut ranges: Vec<(usize, usize, usize)> = cursors
            .iter()
            .enumerate()
            .map(|(i, &p)| {
                let (s, e) = range_for(self, p);
                (i, s.min(e), s.max(e))
            })
            .collect();
        ranges.sort_by_key(|&(_, s, _)| std::cmp::Reverse(s));
        for (i, s, e) in ranges {
            if s == e {
                continue;
            }
            let removed = e - s;
            self.text.replace_range(s..e, "");
            for (j, c) in cursors.iter_mut().enumerate() {
                if j == i {
                    *c = s;
                } else if *c >= e {
                    *c = c.saturating_sub(removed);
                } else if *c > s {
                    *c = s;
                }
            }
            for av in anchors.iter_mut().flatten() {
                if *av >= e {
                    *av = av.saturating_sub(removed);
                } else if *av > s {
                    *av = s;
                }
            }
        }
        self.commit_multi(cursors, anchors);
    }

    /// Multi-cursor InsertStr — insert `s` at every cursor and advance each
    /// by `s.len()`. Anchors are similarly shifted by the number of inserts
    /// at-or-before them.
    fn multi_insert_str(&mut self, s: &str) {
        let mut cursors: Vec<usize> = std::iter::once(self.cursor)
            .chain(self.extra_cursors.iter().copied())
            .collect();
        let mut anchors: Vec<Option<usize>> = std::iter::once(self.anchor)
            .chain(self.extra_anchors.iter().copied())
            .collect();
        // Stable cursor positions sorted ascending — used to compute the
        // post-insert shift for both cursors and anchors.
        let mut positions: Vec<usize> = cursors.clone();
        positions.sort_unstable();
        positions.dedup();
        let bytes = s.len();
        for &p in positions.iter().rev() {
            self.text.insert_str(p, s);
        }
        // Each cursor at original position `p` shifts by
        //   `(count of insertion points <= p) * bytes`.
        for c in cursors.iter_mut() {
            let inserts_at_or_before = positions.iter().filter(|&&pp| pp <= *c).count();
            *c += inserts_at_or_before * bytes;
        }
        // Anchors shift by (count of insertion points STRICTLY before them)
        // so the anchor stays "left of" any insertion that landed at the
        // anchor's exact position — that's where the cursor was at
        // SelectStart time, so the inserted text goes between anchor and
        // cursor, growing the selection. (Anchors at-or-after a higher
        // insertion point shift by that one too.)
        for av in anchors.iter_mut().flatten() {
            let n = positions.iter().filter(|&&pp| pp < *av).count();
            *av += n * bytes;
        }
        self.commit_multi(cursors, anchors);
    }

    /// Distributed paste — each cursor gets `parts[i]` (vim block-paste
    /// convention when clipboard line count matches cursor count). Cursors
    /// are paired in *visual order* (top-to-bottom): part 0 → topmost
    /// cursor, part N-1 → bottommost. Each cursor moves to the end of its
    /// inserted slice. When `after` is true the insertion goes one char
    /// past the cursor (vim `p`), else at the cursor itself (vim `P`).
    fn multi_paste_distribute(&mut self, parts: &[&str], after: bool) {
        let mut cursors: Vec<usize> = std::iter::once(self.cursor)
            .chain(self.extra_cursors.iter().copied())
            .collect();
        let mut anchors: Vec<Option<usize>> = std::iter::once(self.anchor)
            .chain(self.extra_anchors.iter().copied())
            .collect();
        debug_assert_eq!(parts.len(), cursors.len());
        // Map each cursor index to its visual order (ascending byte position).
        let mut order: Vec<usize> = (0..cursors.len()).collect();
        order.sort_by_key(|&i| cursors[i]);
        // visual_index[i] = which part this cursor receives.
        let mut visual_index = vec![0usize; cursors.len()];
        for (vi, &i) in order.iter().enumerate() {
            visual_index[i] = vi;
        }
        // Process by descending cursor position so earlier offsets stay valid.
        let mut indices: Vec<usize> = (0..cursors.len()).collect();
        indices.sort_by_key(|&i| std::cmp::Reverse(cursors[i]));
        for &i in &indices {
            let at = if after {
                self.next_char_boundary(cursors[i]).min(self.text.len())
            } else {
                cursors[i].min(self.text.len())
            };
            let payload = parts[visual_index[i]];
            let bytes = payload.len();
            self.text.insert_str(at, payload);
            // Shift other cursors / anchors that were at-or-after the
            // insertion point.
            for (j, c) in cursors.iter_mut().enumerate() {
                if j == i {
                    *c = at + bytes;
                } else if *c >= at {
                    *c += bytes;
                }
            }
            for av in anchors.iter_mut().flatten() {
                if *av >= at {
                    *av += bytes;
                }
            }
        }
        self.commit_multi(cursors, anchors);
    }

    /// Multi-cursor DeleteForward — each cursor deletes the char at it.
    fn multi_delete_forward(&mut self) {
        let mut cursors: Vec<usize> = std::iter::once(self.cursor)
            .chain(self.extra_cursors.iter().copied())
            .collect();
        let mut anchors: Vec<Option<usize>> = std::iter::once(self.anchor)
            .chain(self.extra_anchors.iter().copied())
            .collect();
        let mut order: Vec<usize> = (0..cursors.len()).collect();
        order.sort_by_key(|&i| std::cmp::Reverse(cursors[i]));
        for &i in &order {
            let p = cursors[i];
            if p >= self.text.len() {
                continue;
            }
            let next = self.next_char_boundary(p);
            let removed = next - p;
            self.text.replace_range(p..next, "");
            for (j, c) in cursors.iter_mut().enumerate() {
                if j == i {
                    // Cursor stays at p — the deleted char was AT cursor.
                } else if *c > next {
                    *c = c.saturating_sub(removed);
                } else if *c >= p {
                    *c = p;
                }
            }
            for av in anchors.iter_mut().flatten() {
                if *av > next {
                    *av = av.saturating_sub(removed);
                } else if *av >= p {
                    *av = p;
                }
            }
        }
        self.commit_multi(cursors, anchors);
    }

    /// Capture the current selection as `last_selection` (the buffer's "gv
    /// memory"). Called by `Editor::apply` on ops that close the selection
    /// — Yank, Cut, ReplaceSelection, DeleteSelection, SelectClear. Also
    /// callable by the input layer when the user opens `:` from visual
    /// mode so `'<,'>` resolves against the still-live selection.
    pub fn remember_selection(&mut self) {
        if let Some(anchor) = self.anchor
            && anchor != self.cursor
        {
            let (lo, hi) = if anchor < self.cursor {
                (anchor, self.cursor)
            } else {
                (self.cursor, anchor)
            };
            self.last_selection = Some((lo, hi));
        }
    }

    pub fn empty() -> Self {
        Editor::new(String::new(), 4)
    }

    // ─── accessors ──────────────────────────────────────────────────
    pub fn text(&self) -> &str {
        &self.text
    }
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Insert `s` at the cursor *without* moving the cursor forward — used
    /// by buffer-side auto-close-tag so `<div>|` becomes `<div>|</div>`
    /// (the `|` denotes cursor position).
    pub fn insert_str_at_cursor_no_advance(&mut self, s: &str) {
        if s.is_empty() {
            return;
        }
        self.text.insert_str(self.cursor, s);
    }

    /// The identifier under the cursor — the maximal run of `[A-Za-z0-9_]`
    /// chars containing the cursor byte. Empty when the cursor isn't on or
    /// adjacent to an identifier char. Used by the "highlight word under
    /// cursor" view feature.
    pub fn word_under_cursor(&self) -> &str {
        let bytes = self.text.as_bytes();
        let len = self.text.len();
        let cur = self.cursor.min(len);
        let is_id = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
        // Cursor may be one past the last id char (typical insert mode); the
        // standard editor-word check is "cursor or cursor-1 sits on an id char".
        if cur == 0 && (cur >= len || !is_id(bytes[0])) {
            return "";
        }
        if cur >= len && (cur == 0 || !is_id(bytes[cur - 1])) {
            return "";
        }
        if cur < len && !is_id(bytes[cur]) && (cur == 0 || !is_id(bytes[cur - 1])) {
            return "";
        }
        let mut start = cur;
        while start > 0 && is_id(bytes[start - 1]) {
            start -= 1;
        }
        let mut end = cur;
        while end < len && is_id(bytes[end]) {
            end += 1;
        }
        &self.text[start..end]
    }
    pub fn set_comment_token(&mut self, token: impl Into<String>) {
        self.comment_token = token.into();
    }
    pub fn set_comment_token_close(&mut self, token: impl Into<String>) {
        self.comment_token_close = token.into();
    }
    /// Move the cursor to `(row, col)` (both clamped), clearing any selection.
    /// Update the tab width. Used by .editorconfig per-buffer overrides.
    pub fn set_tab_width(&mut self, width: usize) {
        self.tab_width = width.max(1);
    }

    /// Set the selection to the byte range `[start, end)`. The cursor lands
    /// at `end` and the anchor at `start`. Clamps to text bounds. No-op when
    /// either offset isn't on a char boundary.
    pub fn set_selection(&mut self, start: usize, end: usize) {
        let len = self.text.len();
        let s = start.min(len);
        let e = end.min(len);
        if !self.text.is_char_boundary(s) || !self.text.is_char_boundary(e) {
            return;
        }
        self.anchor = Some(s);
        self.cursor = e;
        self.goal_col = None;
    }

    /// Used for click-to-place.
    pub fn place_cursor(&mut self, row: usize, col: usize) {
        let row = row.min(self.line_count().saturating_sub(1));
        self.cursor = self.byte_at_col(row, col);
        self.anchor = None;
        self.goal_col = None;
        self.in_insert_run = false;
    }
    /// Like [`Self::place_cursor`] but preserves the active selection
    /// anchor — moving the cursor extends the selection instead of
    /// clearing it. Used by mouse drag-select (after `SelectStart`
    /// has dropped the anchor at the click origin); each Drag event
    /// then extends the cursor to the current pointer cell without
    /// the per-event place_cursor wiping the anchor — the chrome-hunt
    /// SEV-2 "drag-select moves cursor but doesn't create selection."
    pub fn extend_cursor_to(&mut self, row: usize, col: usize) {
        let row = row.min(self.line_count().saturating_sub(1));
        self.cursor = self.byte_at_col(row, col);
        self.goal_col = None;
        self.in_insert_run = false;
    }
    /// `(row, col)` of the cursor, 0-based, col in chars.
    pub fn row_col(&self) -> (usize, usize) {
        let row = self.current_line();
        let col = self.text[self.line_start(row)..self.cursor].chars().count();
        (row, col)
    }
    pub fn line_count(&self) -> usize {
        // Count newlines; +1 catches the partial-trailing-line case
        // (`"foo\nbar"` is 2 lines). Subtract 1 when the buffer ends
        // in a newline (`"foo\nbar\n"` is also 2 lines, matching
        // `wc -l` + every other editor — the trailing newline is the
        // line *terminator*, not an extra empty line). Bug-hunt
        // SEV-3 from 2026-06-07: the chip used to say `Ln 1/4` for
        // a 3-line file with the Unix-correct trailing newline.
        let nl_count = self.text.bytes().filter(|&b| b == b'\n').count();
        if nl_count == 0 {
            // Empty buffer ⇒ 1 visual line; non-empty no-newline ⇒ 1.
            1
        } else if self.text.ends_with('\n') {
            nl_count
        } else {
            nl_count + 1
        }
    }
    pub fn line_str(&self, line: usize) -> &str {
        let s = self.line_start(line);
        let e = self.line_end(line);
        &self.text[s..e]
    }
    /// Byte range `[start, end)` of line `line`'s content (the newline excluded).
    pub fn line_byte_range(&self, line: usize) -> (usize, usize) {
        (self.line_start(line), self.line_end(line))
    }
    /// Byte length of `line`'s content (newline excluded).
    pub fn line_byte_len(&self, line: usize) -> usize {
        let (s, e) = self.line_byte_range(line);
        e - s
    }
    /// Public mirror of [`Self::byte_at_col`]. Lets the App map a (row, char-col)
    /// pair to a byte offset — used by visual-block insert to position the
    /// cursor at the insert origin and to splice the replay text on other rows.
    pub fn byte_at_col_pub(&self, line: usize, col: usize) -> usize {
        self.byte_at_col(line, col)
    }
    /// Public cursor setter, byte-clamped to a char boundary. The App uses
    /// this for "place the cursor here precisely" gestures (visual-block
    /// insert origin, etc.) that bypass the EditOp path.
    pub fn set_cursor_byte(&mut self, byte: usize) {
        let mut b = byte.min(self.text.len());
        while b < self.text.len() && !self.text.is_char_boundary(b) {
            b += 1;
        }
        self.cursor = b;
        self.goal_col = None;
    }
    /// Char-column count of `text[..byte_offset_within_line]` relative to the
    /// start of the line that contains `byte`. Public so the view can map a
    /// selection's byte offsets to columns.
    pub fn byte_to_col(&self, byte: usize) -> usize {
        self.col_at_byte(byte)
    }
    /// The full selection range as byte offsets `[lo, hi)`, or `None`.
    pub fn selection(&self) -> Option<(usize, usize)> {
        self.anchor
            .map(|a| (a.min(self.cursor), a.max(self.cursor)))
    }
    /// The selected text, or `""` when there's no selection.
    pub fn selected_text(&self) -> String {
        self.selection()
            .map(|(lo, hi)| self.text[lo..hi].to_string())
            .unwrap_or_default()
    }
    /// The visual-block rectangle as `(rmin, cmin, rmax, cmax)` (inclusive,
    /// chars, 0-based). `None` when not in block-select mode.
    pub fn block_selection(&self) -> Option<(usize, usize, usize, usize)> {
        let anchor = self.block_anchor?;
        let (ar, ac) = self.row_col_at(anchor);
        let (cr, cc) = self.row_col();
        let (rmin, rmax) = (ar.min(cr), ar.max(cr));
        let (cmin, cmax) = (ac.min(cc), ac.max(cc));
        Some((rmin, cmin, rmax, cmax))
    }

    /// Row range of the last "closed" selection (vim's `'<` / `'>` marks).
    /// Returns `(start_row, end_row)` inclusive. `None` until the buffer has
    /// closed at least one selection. If the end byte sits exactly past a
    /// trailing newline (a linewise / extended selection's exclusive boundary),
    /// the row is rolled back so the range reflects the last *content* row.
    pub fn last_selection_rows(&self) -> Option<(usize, usize)> {
        let (lo, hi) = self.last_selection?;
        let (r1, _) = self.row_col_at(lo);
        let (mut r2, c2) = self.row_col_at(hi);
        if r2 > r1 && c2 == 0 && hi > 0 && self.text.as_bytes().get(hi - 1) == Some(&b'\n') {
            r2 -= 1;
        }
        Some((r1, r2))
    }

    /// `(row, char_col)` of the byte position `byte` (clamped to text bounds).
    pub fn row_col_at(&self, byte: usize) -> (usize, usize) {
        let byte = byte.min(self.text.len());
        let row = self.text[..byte].bytes().filter(|&c| c == b'\n').count();
        let bol = self.line_start(row);
        let col = self.text[bol..byte].chars().count();
        (row, col)
    }

    /// Build the per-row byte ranges for the visual-block rectangle. Returns
    /// `Vec<(start_byte, end_byte)>` — one entry per row in `[rmin..=rmax]`.
    /// For each row, start is the byte of column `cmin` clamped to the
    /// line's content (or the line's EOL if the line is shorter than `cmin`),
    /// and end is the byte of column `cmax + 1` clamped to EOL. Rows shorter
    /// than `cmin` get an empty `(eol, eol)` entry (vim convention — no
    /// edit on those rows).
    pub fn block_ranges(
        &self,
        rmin: usize,
        cmin: usize,
        rmax: usize,
        cmax: usize,
    ) -> Vec<(usize, usize)> {
        let mut out = Vec::with_capacity(rmax - rmin + 1);
        let line_count = self.line_count();
        for r in rmin..=rmax.min(line_count.saturating_sub(1)) {
            let (s, e) = self.line_byte_range(r);
            let line_text = &self.text[s..e];
            let line_chars = line_text.chars().count();
            // Walk to char col cmin
            let start = if line_chars <= cmin {
                e
            } else {
                let mut b = s;
                for (col, ch) in line_text.chars().enumerate() {
                    if col == cmin {
                        break;
                    }
                    b += ch.len_utf8();
                }
                b
            };
            let end = if line_chars <= cmax {
                e
            } else {
                let mut b = s;
                for (col, ch) in line_text.chars().enumerate() {
                    if col == cmax + 1 {
                        break;
                    }
                    b += ch.len_utf8();
                }
                b
            };
            out.push((start, end));
        }
        out
    }

    pub fn has_selection(&self) -> bool {
        self.anchor.map(|a| a != self.cursor).unwrap_or(false)
    }
    pub fn is_at_line_end(&self) -> bool {
        self.cursor == self.line_end(self.current_line())
    }
    pub fn can_undo(&self) -> bool {
        !self.undo.is_empty()
    }
    /// How many undo steps go back to a snapshot at least `secs` old. Used
    /// by `:earlier <N><unit>` — caller multiplies the result by Undo to
    /// walk that far back. Walks newest→oldest until it finds a snapshot
    /// whose timestamp is older than `cutoff_secs`.
    pub fn undo_steps_for_age(&self, secs: u64) -> usize {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let cutoff = now.saturating_sub(secs);
        // Newest first.
        for (i, snap) in self.undo.iter().rev().enumerate() {
            if snap.timestamp <= cutoff {
                return i + 1;
            }
        }
        self.undo.len()
    }
    /// Mirror for `:later <N><unit>` — count redo entries newer than the
    /// `secs` cutoff (the user wants to move forward N seconds of edits).
    pub fn redo_steps_for_age(&self, secs: u64) -> usize {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let cutoff = now.saturating_sub(secs);
        // redo is in oldest→newest order; walk back until we find one
        // older than cutoff.
        for (i, snap) in self.redo.iter().rev().enumerate() {
            if snap.timestamp <= cutoff {
                return i + 1;
            }
        }
        self.redo.len()
    }

    // ─── line geometry helpers ──────────────────────────────────────
    fn current_line(&self) -> usize {
        self.text[..self.cursor]
            .bytes()
            .filter(|&b| b == b'\n')
            .count()
    }
    /// Public byte-offset → 0-based line index. Mirrors [`Self::current_line`]
    /// but for any caller (folds, click-to-place, etc.).
    pub fn line_at_byte(&self, byte: usize) -> usize {
        let byte = byte.min(self.text.len());
        self.text[..byte].bytes().filter(|&b| b == b'\n').count()
    }
    /// Byte offset of the start of line `line` (clamped to last line).
    fn line_start(&self, line: usize) -> usize {
        if line == 0 {
            return 0;
        }
        let mut seen = 0;
        for (i, b) in self.text.bytes().enumerate() {
            if b == b'\n' {
                seen += 1;
                if seen == line {
                    return i + 1;
                }
            }
        }
        // line beyond the last → start of the last line
        self.text.rfind('\n').map(|i| i + 1).unwrap_or(0)
    }
    /// Byte offset just before line `line`'s newline (or EOF for the last line).
    fn line_end(&self, line: usize) -> usize {
        let start = self.line_start(line);
        match self.text[start..].find('\n') {
            Some(rel) => start + rel,
            None => self.text.len(),
        }
    }
    fn byte_at_col(&self, line: usize, col: usize) -> usize {
        let start = self.line_start(line);
        let end = self.line_end(line);
        let mut b = start;
        for (c, ch) in self.text[start..end].chars().enumerate() {
            if c == col {
                break;
            }
            b += ch.len_utf8();
        }
        b
    }
    fn col_at_byte(&self, byte: usize) -> usize {
        let line = self.text[..byte].bytes().filter(|&b| b == b'\n').count();
        self.text[self.line_start(line)..byte].chars().count()
    }

    /// Resolve `goal_col` for a read (a vertical motion) and cache it. First
    /// call after a non-vertical op computes from the cursor position; every
    /// subsequent vertical motion (which preserves goal_col via
    /// `op_preserves_goal_col`) reuses the cached value so it "sticks" past
    /// clamped shorter lines. `None` = "dirty, recompute" — most edits mark
    /// dirty in constant time and never pay the O(n) cost.
    fn goal_col(&mut self) -> usize {
        if let Some(c) = self.goal_col {
            return c;
        }
        let c = self.col_at_byte(self.cursor);
        self.goal_col = Some(c);
        c
    }

    /// True when auto-pair should fire — i.e. the next char is "empty space"
    /// (newline, whitespace, end-of-buffer, or a closing bracket / quote). If
    /// the next char is a word char we'd be wrapping live code, so don't.
    fn next_char_allows_pair(&self) -> bool {
        match self.text[self.cursor..].chars().next() {
            None => true,
            Some(c) if c.is_whitespace() => true,
            Some(')' | ']' | '}' | '>' | ',' | ';' | ':') => true,
            _ => false,
        }
    }

    /// True if the next char in the buffer is exactly `c` (used to skip over
    /// an already-auto-paired close char).
    fn cursor_on_char(&self, c: char) -> bool {
        self.text[self.cursor..].starts_with(c)
    }

    /// `(row, col)` of the bracket that matches the one under the cursor, or
    /// `None` if the cursor isn't on a bracket. Used by `editor.bracket_match`
    /// (`Ctrl+]`) to jump to the pair, and by the editor renderer to paint a
    /// match-highlight.
    pub fn bracket_match(&self) -> Option<(usize, usize)> {
        let here = self.text[self.cursor..].chars().next()?;
        let (open, close, forward) = match here {
            '(' => ('(', ')', true),
            '[' => ('[', ']', true),
            '{' => ('{', '}', true),
            ')' => ('(', ')', false),
            ']' => ('[', ']', false),
            '}' => ('{', '}', false),
            _ => return None,
        };
        const BUDGET: usize = 50_000;
        let (cur_row, cur_col) = self.row_col();
        if forward {
            let mut depth: usize = 1;
            let mut row = cur_row;
            let mut col = cur_col + 1;
            let mut iter = self.text[self.cursor + here.len_utf8()..].chars();
            for _ in 0..BUDGET {
                let ch = iter.next()?;
                if ch == '\n' {
                    row += 1;
                    col = 0;
                    continue;
                }
                if ch == open {
                    depth += 1;
                } else if ch == close {
                    depth -= 1;
                    if depth == 0 {
                        return Some((row, col));
                    }
                }
                col += 1;
            }
            None
        } else {
            let prefix = &self.text[..self.cursor];
            let mut chars: Vec<char> = prefix.chars().collect();
            let mut row = 0usize;
            let mut col = 0usize;
            let mut positions: Vec<(usize, usize)> = Vec::with_capacity(chars.len());
            for ch in &chars {
                positions.push((row, col));
                if *ch == '\n' {
                    row += 1;
                    col = 0;
                } else {
                    col += 1;
                }
            }
            let take = chars.len().min(BUDGET);
            let start = chars.len() - take;
            chars.drain(..start);
            let positions = &positions[start..];
            let mut depth: usize = 1;
            for (i, ch) in chars.iter().enumerate().rev() {
                if *ch == close {
                    depth += 1;
                } else if *ch == open {
                    depth -= 1;
                    if depth == 0 {
                        return Some(positions[i]);
                    }
                }
            }
            None
        }
    }

    /// The leading whitespace (' ' / '\t') of the current line, up to the
    /// cursor — what `auto_indent` carries forward when Enter is pressed mid-
    /// line. (If the cursor sits inside the indent, only the chars before it
    /// are copied — typing Enter doesn't *expand* the indent.)
    fn leading_indent_of_line_to_cursor(&self) -> String {
        let line = self.current_line();
        let bol = self.line_start(line);
        let mut out = String::new();
        for ch in self.text[bol..self.cursor].chars() {
            if ch == ' ' || ch == '\t' {
                out.push(ch);
            } else {
                break;
            }
        }
        out
    }

    /// The leading whitespace of `line`, irrespective of the cursor — used by
    /// `InsertNewlineBelow` (vim `o`), which opens a fresh line *below* the
    /// current one and wants its full indent.
    fn leading_indent_of_line(&self, line: usize) -> String {
        let mut out = String::new();
        for ch in self.line_str(line).chars() {
            if ch == ' ' || ch == '\t' {
                out.push(ch);
            } else {
                break;
            }
        }
        out
    }
    fn prev_char_boundary(&self, byte: usize) -> usize {
        if byte == 0 {
            return 0;
        }
        let mut i = byte - 1;
        while !self.text.is_char_boundary(i) {
            i -= 1;
        }
        i
    }
    fn next_char_boundary(&self, byte: usize) -> usize {
        if byte >= self.text.len() {
            return self.text.len();
        }
        let mut i = byte + 1;
        while i < self.text.len() && !self.text.is_char_boundary(i) {
            i += 1;
        }
        i
    }
    fn char_before(&self, byte: usize) -> Option<char> {
        if byte == 0 {
            None
        } else {
            self.text[..byte].chars().next_back()
        }
    }
    fn char_at(&self, byte: usize) -> Option<char> {
        self.text[byte..].chars().next()
    }

    // ─── undo plumbing ──────────────────────────────────────────────
    fn snapshot(&self) -> Snapshot {
        Snapshot {
            text: self.text.clone(),
            cursor: self.cursor,
            anchor: self.anchor,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
        }
    }
    /// Begin a fresh undo group for a mutation that is *about* to change text.
    fn checkpoint(&mut self) {
        self.redo.clear();
        self.in_insert_run = false;
        self.push_undo();
    }
    /// Begin / continue the coalescing group for typed characters.
    fn checkpoint_insert_run(&mut self) {
        self.redo.clear();
        if !self.in_insert_run {
            self.push_undo();
            self.in_insert_run = true;
        }
    }
    fn push_undo(&mut self) {
        self.undo.push(self.snapshot());
        if self.undo.len() > UNDO_LIMIT {
            self.undo.remove(0);
        }
    }

    /// Push one pre-state checkpoint, run `body`, then collapse every
    /// intermediate undo entry the body pushed into that single
    /// checkpoint. The result: one `u` reverts the entire run.
    ///
    /// `body` receives `&mut Self` so the caller can stream ops
    /// through `apply` (which would normally checkpoint per op).
    /// Used by `:%s/.../.../g` and any future "batch many edits, undo
    /// as one" path.
    ///
    /// 2026-06-13 nvchad-user SEV-2 follow-up (S2-02: `:%s` was not
    /// a single undo step).
    pub fn atomic_undo<R>(&mut self, body: impl FnOnce(&mut Self) -> R) -> R {
        self.redo.clear();
        self.in_insert_run = false;
        let before_len = self.undo.len();
        self.push_undo();
        // After our checkpoint, the body may push N more entries
        // (one per inner `apply`). We keep ours at `before_len` and
        // drop the body's.
        let target_len = before_len + 1;
        let out = body(self);
        if self.undo.len() > target_len {
            self.undo.truncate(target_len);
        }
        self.in_insert_run = false;
        out
    }
    fn restore(&mut self, s: Snapshot) {
        self.text = s.text;
        self.cursor = s.cursor.min(self.text.len());
        while !self.text.is_char_boundary(self.cursor) {
            self.cursor -= 1;
        }
        self.anchor = s.anchor.map(|a| a.min(self.text.len()));
        self.in_insert_run = false;
    }

    // ─── the interpreter ────────────────────────────────────────────
    pub fn apply(&mut self, op: EditOp, viewport_rows: usize, clip: &mut Clipboard) -> EditOutcome {
        let before_cursor = self.cursor;
        let before_len = self.text.len();
        let had_multicursor = !self.extra_cursors.is_empty();
        // Capture `ReplaceRange`'s explicit fields before the op moves out of `op`.
        // The post-op inference below can't recover them — cursor lands at
        // `start + text.len()`, which is the new_end but says nothing about
        // `start`.
        let replace_range_info = if let EditOp::ReplaceRange { start, end, text } = &op {
            Some((*start, *end, text.len()))
        } else {
            None
        };
        let keep_goal_col = op_preserves_goal_col(&op);
        // Anything that isn't a typed character ends the coalescing undo run, so
        // a motion between two typing bursts splits them into separate undo steps.
        if !op_is_insert_char(&op) {
            self.in_insert_run = false;
        }
        let mut out = EditOutcome::default();
        self.apply_one(op, viewport_rows, clip, &mut out);
        out.cursor_moved |= self.cursor != before_cursor;
        out.buffer_changed |= self.text.len() != before_len;
        // Goal column tracks horizontal intent; vertical motions deliberately keep it.
        if !keep_goal_col {
            self.goal_col = None;
        }

        // Tracked text-edit hint for incremental tree-sitter reparse.
        // Skip when multi-cursor was active either before or after the op —
        // those fan-out edits aren't single-extent.
        if out.buffer_changed
            && !had_multicursor
            && self.extra_cursors.is_empty()
            && out.text_edits.is_empty()
        {
            if let Some((s, e, new_len)) = replace_range_info {
                let len = self.text.len();
                let s = s.min(len);
                let e = e.min(len).max(s);
                if self.text.is_char_boundary(s) && self.text.is_char_boundary(e) {
                    out.text_edits.push(TextEdit {
                        start_byte: s,
                        old_end_byte: e,
                        new_end_byte: s + new_len,
                    });
                }
            } else if let Some(edit) =
                infer_single_edit(before_len, self.text.len(), before_cursor, self.cursor)
            {
                out.text_edits.push(edit);
            }
            // Else: untracked. `text_edits` stays empty; caller drops the tree.
        }

        out
    }

    fn apply_one(&mut self, op: EditOp, vp: usize, clip: &mut Clipboard, out: &mut EditOutcome) {
        use EditOp::*;
        match op {
            Repeat(n, inner) => {
                // nvchad-round-14 SEV-2 2026-07-14 — when the inner
                // op mutates the buffer, coalesce all N per-iteration
                // checkpoints into ONE so a single `u` reverts the
                // whole count-multiplied op (`3dd`, `5x`, `3J`, …).
                // Motion-only Repeat (`3w`, `5j`, …) doesn't push
                // checkpoints anyway; skip the wrapping in that case
                // to avoid a spurious empty undo entry.
                if op_mutates_buffer(&inner) && n > 1 {
                    self.redo.clear();
                    self.in_insert_run = false;
                    let before_len = self.undo.len();
                    self.push_undo();
                    let target_len = before_len + 1;
                    for _ in 0..n {
                        self.apply_one((*inner).clone(), vp, clip, out);
                    }
                    if self.undo.len() > target_len {
                        self.undo.truncate(target_len);
                    }
                } else {
                    for _ in 0..n {
                        self.apply_one((*inner).clone(), vp, clip, out);
                    }
                }
            }
            // Explicit atomic group — like Repeat above but for a
            // heterogeneous list of ops. Push one pre-state
            // checkpoint, run the inner ops (each of which pushes
            // its own), then truncate back to keep only ours.
            // Mirrors `Editor::atomic_undo` at the op level.
            // nvchad-round-14 SEV-2 2026-07-14.
            Atomic(inner_ops) => {
                self.redo.clear();
                self.in_insert_run = false;
                let before_len = self.undo.len();
                self.push_undo();
                let target_len = before_len + 1;
                for inner in inner_ops {
                    self.apply_one(inner, vp, clip, out);
                }
                if self.undo.len() > target_len {
                    self.undo.truncate(target_len);
                }
            }

            // ── motion ──
            MoveLeft => {
                self.move_horizontal(-1, false);
                self.move_extras_horizontal(-1);
            }
            MoveRight => {
                self.move_horizontal(1, false);
                self.move_extras_horizontal(1);
            }
            MoveUp => {
                self.move_vertical(-1);
                self.move_extras_vertical(-1);
            }
            MoveDown => {
                self.move_vertical(1);
                self.move_extras_vertical(1);
            }
            PageUp => {
                for _ in 0..vp.max(1) {
                    self.move_vertical(-1);
                }
            }
            PageDown => {
                for _ in 0..vp.max(1) {
                    self.move_vertical(1);
                }
            }
            HalfPageUp => {
                for _ in 0..(vp / 2).max(1) {
                    self.move_vertical(-1);
                }
            }
            HalfPageDown => {
                for _ in 0..(vp / 2).max(1) {
                    self.move_vertical(1);
                }
            }
            MoveWordRight => {
                self.move_word_right();
                self.move_extras_with(Self::word_right_target_from);
            }
            MoveWordRightNoCrossLine => {
                // vim `dw` special-case (nvchad-user 2026-07-30
                // SEV-2). Behaves like MoveWordRight but clamps to
                // end-of-line so the operator range doesn't consume
                // the newline. Cursor lands on the newline byte itself
                // when the current word ends at EOL.
                let line = self.current_line();
                let line_end = self.line_end(line);
                self.move_word_right();
                if self.cursor > line_end {
                    self.cursor = line_end;
                }
                self.move_extras_with(Self::word_right_target_from);
            }
            MoveWordLeft => {
                self.move_word_left();
                self.move_extras_with(Self::word_left_target_from);
            }
            MoveWordEnd => self.move_word_end(),
            MoveWordEndBack => self.move_word_end_back(),
            MoveBigWordRight => self.move_big_word_right(),
            MoveBigWordRightNoCrossLine => {
                let line = self.current_line();
                let line_end = self.line_end(line);
                self.move_big_word_right();
                if self.cursor > line_end {
                    self.cursor = line_end;
                }
            }
            MoveBigWordLeft => self.move_big_word_left(),
            MoveBigWordEnd => self.move_big_word_end(),
            MoveBigWordEndBack => self.move_big_word_end_back(),
            MoveLineStart => {
                self.cursor = self.line_start(self.current_line());
                self.move_extras_to_line_edge(false);
            }
            MoveLineFirstNonWs => {
                let line = self.current_line();
                let (s, e) = (self.line_start(line), self.line_end(line));
                let mut b = s;
                for ch in self.text[s..e].chars() {
                    if !ch.is_whitespace() {
                        break;
                    }
                    b += ch.len_utf8();
                }
                self.cursor = b;
            }
            MoveDownFirstNonWs => {
                self.move_vertical(1);
                self.apply_one(MoveLineFirstNonWs, vp, clip, out);
            }
            MoveUpFirstNonWs => {
                self.move_vertical(-1);
                self.apply_one(MoveLineFirstNonWs, vp, clip, out);
            }
            MoveLineLastNonWs => {
                let line = self.current_line();
                let (s, e) = (self.line_start(line), self.line_end(line));
                let slice = &self.text[s..e];
                // walk back over trailing whitespace
                let mut last_nonws_end = s;
                let mut idx = s;
                for ch in slice.chars() {
                    let nxt = idx + ch.len_utf8();
                    if !ch.is_whitespace() {
                        last_nonws_end = nxt;
                    }
                    idx = nxt;
                }
                if last_nonws_end == s {
                    // blank line — go to start
                    self.cursor = s;
                } else {
                    // land on the last non-blank char (one char back from its end)
                    let mut c = s;
                    let mut prev = s;
                    for ch in slice.chars() {
                        let nxt = c + ch.len_utf8();
                        if nxt == last_nonws_end {
                            prev = c;
                            break;
                        }
                        c = nxt;
                    }
                    self.cursor = prev;
                }
            }
            MoveLineEnd => {
                self.cursor = self.line_end(self.current_line());
                self.move_extras_to_line_edge(true);
            }
            MoveLineLastChar => {
                // vim `$` — land on the last printable char, not on
                // the trailing `\n` / EOF. For an empty line this
                // collapses to the line start (same as the cursor's
                // current position when on an empty line; harmless).
                // 2026-06-13 nvchad-user SEV-3 S3-02 fix.
                let line = self.current_line();
                let start = self.line_start(line);
                let end = self.line_end(line);
                if end == start {
                    self.cursor = start;
                } else {
                    // Step back one char from `end` (the `\n` byte
                    // / EOF) to the LAST printable char's byte.
                    let mut b = end - 1;
                    while !self.text.is_char_boundary(b) {
                        b = b.saturating_sub(1);
                    }
                    self.cursor = b;
                }
                self.move_extras_to_line_edge(true);
            }
            MoveVisualDown(width) => {
                let w = width.max(1);
                let line = self.current_line();
                let col = self.col_at_byte(self.cursor);
                let line_chars = self.line_str(line).chars().count();
                if col + w < line_chars {
                    // Forward `w` chars on the same line — under wrap this
                    // is the next visual row of the same file line.
                    self.cursor = self.byte_at_col(line, col + w);
                    self.goal_col = None;
                } else if line + 1 < self.line_count() {
                    // Past the line's last visual row — jump down one file
                    // line at `col % w`.
                    let target_col = col % w;
                    self.cursor = self.byte_at_col(line + 1, target_col);
                    self.goal_col = None;
                } else {
                    // Already on last line's last visual row — end of file.
                    self.cursor = self.line_end(line);
                    self.goal_col = None;
                }
            }
            MoveVisualUp(width) => {
                let w = width.max(1);
                let line = self.current_line();
                let col = self.col_at_byte(self.cursor);
                if col >= w {
                    self.cursor = self.byte_at_col(line, col - w);
                    self.goal_col = None;
                } else if line > 0 {
                    // Up one file line, landing on its last visual row at
                    // the same intra-row column.
                    let prev = line - 1;
                    let prev_chars = self.line_str(prev).chars().count();
                    let last_segment_start = (prev_chars / w) * w;
                    let target_col = (last_segment_start + col).min(prev_chars);
                    self.cursor = self.byte_at_col(prev, target_col);
                    self.goal_col = None;
                } else {
                    self.cursor = self.line_start(line);
                    self.goal_col = Some(0);
                }
            }
            MoveVisualLineStart(width) => {
                let w = width.max(1);
                let line = self.current_line();
                let col = self.col_at_byte(self.cursor);
                let target_col = (col / w) * w;
                self.cursor = self.byte_at_col(line, target_col);
                self.goal_col = Some(target_col);
            }
            MoveVisualLineEnd(width) => {
                let w = width.max(1);
                let line = self.current_line();
                let col = self.col_at_byte(self.cursor);
                let line_chars = self.line_str(line).chars().count();
                let segment_start = (col / w) * w;
                let target_col = (segment_start + w - 1).min(line_chars.saturating_sub(1));
                self.cursor = self.byte_at_col(line, target_col);
                self.goal_col = Some(target_col);
            }
            MoveParagraph { forward } => {
                let cur_row = self.current_line();
                let line_count = self.line_count();
                let is_blank = |row: usize| {
                    let (s, e) = self.line_byte_range(row);
                    self.text[s..e].chars().all(|c| c.is_whitespace())
                };
                let target = if forward {
                    // Skip the current run, then find the next blank.
                    let mut skipped_current = false;
                    let mut row = cur_row + 1;
                    let mut found = None;
                    while row < line_count {
                        if is_blank(row) {
                            if skipped_current {
                                found = Some(row);
                                break;
                            }
                            // landed on the current paragraph's trailing blank
                            // — vim convention: jump past it to the NEXT blank
                            // after intervening text. Keep walking.
                            row += 1;
                            continue;
                        }
                        skipped_current = true;
                        row += 1;
                    }
                    found.unwrap_or_else(|| line_count.saturating_sub(1))
                } else {
                    // Walk back to the previous blank.
                    if cur_row == 0 {
                        0
                    } else {
                        let mut skipped_current = false;
                        let mut row = cur_row - 1;
                        let mut found = None;
                        loop {
                            if is_blank(row) {
                                if skipped_current {
                                    found = Some(row);
                                    break;
                                }
                                if row == 0 {
                                    break;
                                }
                                row -= 1;
                                continue;
                            }
                            skipped_current = true;
                            if row == 0 {
                                break;
                            }
                            row -= 1;
                        }
                        found.unwrap_or(0)
                    }
                };
                self.cursor = self.line_start(target);
            }
            MoveSentence { forward } => {
                // Sentence boundary = `.`/`!`/`?` followed by whitespace, or
                // a blank line. Vim's sentence motion is famously loose; this
                // is the common-case approximation.
                let bytes = self.text.as_bytes();
                let len = bytes.len();
                if forward {
                    let mut i = self.cursor + 1;
                    while i < len {
                        let c = bytes[i];
                        if (c == b'.' || c == b'!' || c == b'?') && i + 1 < len {
                            let nxt = bytes[i + 1];
                            if nxt == b' ' || nxt == b'\n' || nxt == b'\t' {
                                // land on the char after the whitespace
                                let mut j = i + 1;
                                while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
                                    j += 1;
                                }
                                self.cursor = j;
                                return;
                            }
                        }
                        i += 1;
                    }
                    self.cursor = len;
                } else {
                    // Walk backward; find the *start* of the current sentence
                    // (just-past the prior boundary, or BOF).
                    let mut i = self.cursor.saturating_sub(1);
                    while i > 0 {
                        let c = bytes[i];
                        if (c == b'.' || c == b'!' || c == b'?') && i + 1 < len {
                            let nxt = bytes[i + 1];
                            if nxt == b' ' || nxt == b'\n' || nxt == b'\t' {
                                let mut j = i + 1;
                                while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
                                    j += 1;
                                }
                                if j < self.cursor {
                                    self.cursor = j;
                                    return;
                                }
                            }
                        }
                        i -= 1;
                    }
                    self.cursor = 0;
                }
            }
            MoveBufferStart => self.cursor = 0,
            // Vim `G`: land on the START of the LAST line — never past
            // a trailing `\n`. Prior implementation used `text.len()`
            // which on `"a\nb\nc\n"` (3 lines) put the cursor on a
            // phantom line 4. 2026-06-13 nvchad-user SEV-2 S2-05 fix.
            MoveBufferEnd => {
                let last = self.line_count().saturating_sub(1);
                self.cursor = self.line_start(last);
            }
            MoveToLine(n) => {
                let line = n.saturating_sub(1).min(self.line_count().saturating_sub(1));
                self.cursor = self.line_start(line);
            }
            MoveToCol(n) => {
                let col = n.saturating_sub(1);
                let line = self.current_line();
                self.cursor = self.byte_at_col(line, col);
            }
            InsertCharFromLine { above } => {
                let (row, col) = self.row_col();
                let target_row = if above {
                    if row == 0 {
                        return;
                    }
                    row - 1
                } else {
                    if row + 1 >= self.line_count() {
                        return;
                    }
                    row + 1
                };
                let line = self.line_str(target_row);
                let Some(ch) = line.chars().nth(col) else {
                    return;
                };
                self.checkpoint();
                let s = ch.to_string();
                self.text.insert_str(self.cursor, &s);
                self.cursor += s.len();
                out.buffer_changed = true;
            }
            SetCursorByte(b) => {
                let mut b = b.min(self.text.len());
                while b > 0 && !self.text.is_char_boundary(b) {
                    b -= 1;
                }
                self.cursor = b;
                self.goal_col = None;
            }

            // ── selection ──
            SelectStart => {
                self.anchor = Some(self.cursor);
                // Multi-cursor: anchor each extra at its own position too,
                // so a subsequent motion extends N parallel selections.
                for i in 0..self.extra_cursors.len() {
                    self.extra_anchors[i] = Some(self.extra_cursors[i]);
                }
            }
            RememberSelection => {
                self.remember_selection();
            }
            SelectClear => {
                self.remember_selection();
                self.anchor = None;
                // Drop per-cursor anchors too — `Esc` from visual / yank-
                // closing should reset every cursor's selection state.
                for a in self.extra_anchors.iter_mut() {
                    *a = None;
                }
            }
            SelectAll => {
                self.anchor = Some(0);
                self.cursor = self.text.len();
            }
            SelectLine => {
                // Vim `V` (visual-line) leaves the CURSOR on the line
                // it was entered from, with the anchor at line_start;
                // the line selection extends through the trailing `\n`
                // conceptually but the cursor stays put. The prior
                // implementation set cursor to `line_end + 1` which is
                // the START of the NEXT line — visually "V snaps the
                // cursor down one line." 2026-06-13 nvchad-user SEV-3
                // S3-04 fix.
                let line = self.current_line();
                let start = self.line_start(line);
                self.anchor = Some(start);
                // Keep self.cursor where it is (the cursor was somewhere
                // ON the current line before V fired). For the bug-fix
                // case the user hadn't moved horizontally so cursor ==
                // start; either way it stays on the entered line.
            }
            SelectLineToEnd => {
                // VS Code Ctrl+L — anchor at line_start, cursor at
                // line_end+1 so the whole line is literally selected
                // regardless of where the cursor was when fired.
                // Repeated calls extend by one line (anchor stays,
                // cursor advances to next line's end).
                let line = self.current_line();
                let cur_was_in_selection =
                    matches!(self.anchor, Some(a) if a <= self.line_start(line));
                if !cur_was_in_selection || self.anchor.is_none() {
                    self.anchor = Some(self.line_start(line));
                }
                let end = self.line_end(line);
                // line_end is the index of the `\n` (or text.len() at EOF).
                // Cursor lands at end+1 so the selection covers the newline,
                // unless we're at the last line with no trailing newline.
                self.cursor = if end < self.text.len() { end + 1 } else { end };
            }
            SelectWord => {
                let (lo, hi) = self.word_bounds_at(self.cursor);
                self.anchor = Some(lo);
                self.cursor = hi;
            }
            SelectInnerWord => {
                // vim `iw` — identifier run under the cursor. Reuses
                // `word_bounds_at` which is what SelectWord already used.
                let (lo, hi) = self.word_bounds_at(self.cursor);
                self.anchor = Some(lo);
                self.cursor = hi;
            }
            SelectInnerBigWord => {
                // vim `iW` — whitespace-delimited big WORD.
                let (lo, hi) = self.big_word_bounds_at(self.cursor);
                self.anchor = Some(lo);
                self.cursor = hi;
            }
            SelectInnerQuote(q) => {
                if let Some((open, close)) = self.enclosing_quote_pair_on_line(q) {
                    // Inner range: between the two quotes.
                    self.anchor = Some(open + q.len_utf8());
                    self.cursor = close;
                }
            }
            SelectAroundQuote(q) => {
                if let Some((open, close)) = self.enclosing_quote_pair_on_line(q) {
                    self.anchor = Some(open);
                    self.cursor = close + q.len_utf8();
                }
            }
            SelectInnerSmartQuote | SelectAroundSmartQuote => {
                let around = matches!(op, SelectAroundSmartQuote);
                let mut best: Option<(usize, usize, char)> = None;
                for q in ['"', '\'', '`'] {
                    if let Some((open, close)) = self.enclosing_quote_pair_on_line(q) {
                        let span = close.saturating_sub(open);
                        match best {
                            None => best = Some((open, close, q)),
                            Some((_, _, _)) if span < (best.unwrap().1 - best.unwrap().0) => {
                                best = Some((open, close, q));
                            }
                            _ => {}
                        }
                    }
                }
                if let Some((open, close, q)) = best {
                    if around {
                        self.anchor = Some(open);
                        self.cursor = close + q.len_utf8();
                    } else {
                        self.anchor = Some(open + q.len_utf8());
                        self.cursor = close;
                    }
                }
            }
            SurroundSelection { open, close } => {
                if let Some((lo, hi)) = self.selection() {
                    self.checkpoint();
                    let mut close_buf = [0u8; 4];
                    let close_str = close.encode_utf8(&mut close_buf);
                    let mut open_buf = [0u8; 4];
                    let open_str = open.encode_utf8(&mut open_buf);
                    // Insert close at hi first (later offset), then open at
                    // lo, so earlier offsets stay valid.
                    self.text.insert_str(hi, close_str);
                    self.text.insert_str(lo, open_str);
                    // Land cursor on the closing char.
                    self.cursor = hi + open.len_utf8();
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            DeleteSurround(c) => {
                // Resolve which char is the open / close marker. Quotes
                // are symmetric (open == close); brackets use the canonical
                // open and its match.
                let (open, close) = match c {
                    '"' | '\'' | '`' => (c, c),
                    '(' | ')' => ('(', ')'),
                    '[' | ']' => ('[', ']'),
                    '{' | '}' => ('{', '}'),
                    '<' | '>' => ('<', '>'),
                    _ => return,
                };
                let pair = if matches!(c, '"' | '\'' | '`') {
                    self.enclosing_quote_pair_on_line(c)
                } else {
                    self.enclosing_bracket_pair(open, close)
                };
                if let Some((o, cl)) = pair {
                    // Splice descending so earlier offsets stay valid.
                    self.checkpoint();
                    let close_len = close.len_utf8();
                    let open_len = open.len_utf8();
                    self.text.replace_range(cl..cl + close_len, "");
                    self.text.replace_range(o..o + open_len, "");
                    // Land cursor at the (now-shifted) inner-content start.
                    self.cursor = o.min(self.text.len());
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            ChangeSurround { from, to } => {
                let (from_open, from_close) = match from {
                    '"' | '\'' | '`' => (from, from),
                    '(' | ')' => ('(', ')'),
                    '[' | ']' => ('[', ']'),
                    '{' | '}' => ('{', '}'),
                    '<' | '>' => ('<', '>'),
                    _ => return,
                };
                let (to_open, to_close) = match to {
                    '"' | '\'' | '`' => (to, to),
                    '(' | ')' => ('(', ')'),
                    '[' | ']' => ('[', ']'),
                    '{' | '}' => ('{', '}'),
                    '<' | '>' => ('<', '>'),
                    _ => return,
                };
                let pair = if matches!(from, '"' | '\'' | '`') {
                    self.enclosing_quote_pair_on_line(from)
                } else {
                    self.enclosing_bracket_pair(from_open, from_close)
                };
                if let Some((o, cl)) = pair {
                    self.checkpoint();
                    let close_len = from_close.len_utf8();
                    let open_len = from_open.len_utf8();
                    let mut to_close_buf = [0u8; 4];
                    let to_close_str = to_close.encode_utf8(&mut to_close_buf);
                    let mut to_open_buf = [0u8; 4];
                    let to_open_str = to_open.encode_utf8(&mut to_open_buf);
                    // Replace close first (later offset), then open.
                    self.text.replace_range(cl..cl + close_len, to_close_str);
                    self.text.replace_range(o..o + open_len, to_open_str);
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            SelectInnerBracket(open) => {
                let close = match_close_for(open);
                if let Some((o, c)) = self.enclosing_bracket_pair(open, close) {
                    self.anchor = Some(o + open.len_utf8());
                    self.cursor = c;
                }
            }
            SelectInnerTag => {
                if let Some((_ol, og, cl, _cg)) = enclosing_tag_pair(&self.text, self.cursor) {
                    self.anchor = Some(og);
                    self.cursor = cl;
                }
            }
            SelectAroundTag => {
                if let Some((ol, _og, _cl, cg)) = enclosing_tag_pair(&self.text, self.cursor) {
                    self.anchor = Some(ol);
                    self.cursor = cg;
                }
            }
            RestoreLastSelection => {
                if let Some((lo, hi)) = self.last_selection {
                    let lo = lo.min(self.text.len());
                    let hi = hi.min(self.text.len());
                    self.anchor = Some(lo);
                    self.cursor = hi;
                }
            }
            SwapAnchorCursor => {
                if let Some(a) = self.anchor {
                    self.anchor = Some(self.cursor);
                    self.cursor = a;
                    self.goal_col = None;
                }
            }
            FindCharOnLine {
                ch,
                forward,
                before,
                inclusive,
            } => {
                let line = self.current_line();
                let ls = self.line_start(line);
                let le = self.line_end(line);
                let cur = self.cursor;
                if forward {
                    // Scan from one char past cursor to end-of-line.
                    let after = (cur + 1).min(le);
                    if let Some(off) = self.text[after..le].find(ch) {
                        let target = after + off;
                        // `f`: land on target. `t`: one *before* target.
                        // For operator-pending (`inclusive`), bump one cell
                        // forward so the operator's range includes the find
                        // char (for `f`) or stops exactly on it (for `t`).
                        let base = if before {
                            self.prev_char_boundary(target)
                        } else {
                            target
                        };
                        self.cursor = if inclusive {
                            self.next_char_boundary(base)
                        } else {
                            base
                        };
                        self.goal_col = None;
                    }
                } else {
                    // Backward scan from start-of-line up to (but not
                    // including) the cursor.
                    let before_cur = cur.min(le);
                    let slice = &self.text[ls..before_cur];
                    if let Some(off) = slice.rfind(ch) {
                        let target = ls + off;
                        let base = if before {
                            self.next_char_boundary(target)
                        } else {
                            target
                        };
                        // For an inclusive backward operator, the range
                        // wants to cover one cell less (the `f` form should
                        // include the target → cursor lands ON the target,
                        // not before it; for `t`, one past).
                        let _ = inclusive;
                        self.cursor = base;
                        self.goal_col = None;
                    }
                }
            }
            SelectAroundBracket(open) => {
                let close = match_close_for(open);
                if let Some((o, c)) = self.enclosing_bracket_pair(open, close) {
                    self.anchor = Some(o);
                    self.cursor = c + close.len_utf8();
                }
            }
            SelectInnerParagraph => {
                let (lo, hi) = self.paragraph_bounds(false);
                self.anchor = Some(lo);
                self.cursor = hi;
            }
            SelectAroundParagraph => {
                let (lo, hi) = self.paragraph_bounds(true);
                self.anchor = Some(lo);
                self.cursor = hi;
            }
            SelectInnerFunction | SelectAroundFunction => {
                let inner = matches!(op, SelectInnerFunction);
                if let Some(ext) = self.language_ext.as_deref() {
                    let kinds: &[&str] = &["fn"];
                    let range = if matches!(ext, "py" | "rb" | "coffee" | "yaml" | "yml") {
                        self.enclosing_indent_scope(ext, kinds, inner)
                    } else {
                        self.enclosing_function_range(ext, kinds, inner)
                    };
                    if let Some((lo, hi)) = range {
                        self.anchor = Some(lo);
                        self.cursor = hi;
                    }
                }
            }
            SelectInnerClass | SelectAroundClass => {
                let inner = matches!(op, SelectInnerClass);
                if let Some(ext) = self.language_ext.as_deref() {
                    let kinds: &[&str] = &[
                        "class",
                        "struct",
                        "enum",
                        "trait",
                        "interface",
                        "mod",
                        "module",
                        "namespace",
                        "impl",
                    ];
                    let range = if matches!(ext, "py" | "rb" | "coffee" | "yaml" | "yml") {
                        self.enclosing_indent_scope(ext, kinds, inner)
                    } else {
                        self.enclosing_function_range(ext, kinds, inner)
                    };
                    if let Some((lo, hi)) = range {
                        self.anchor = Some(lo);
                        self.cursor = hi;
                    }
                }
            }
            SelectInnerArgument | SelectAroundArgument => {
                let inner = matches!(op, SelectInnerArgument);
                if let Some((lo, hi)) = self.enclosing_argument_range(inner) {
                    self.anchor = Some(lo);
                    self.cursor = hi;
                }
            }
            SelectInnerIndentBlock | SelectAroundIndentBlock | SelectOuterIndentBlock => {
                let (above, below) = match op {
                    SelectInnerIndentBlock => (false, false),
                    SelectAroundIndentBlock => (true, false),
                    _ => (true, true), // SelectOuterIndentBlock — `aI`
                };
                if let Some((lo, hi)) = self.indent_block_bounds(above, below) {
                    self.anchor = Some(lo);
                    self.cursor = hi;
                }
            }
            SelectAroundBigWord => {
                // vim `aW` — big WORD + trailing whitespace (or leading
                // when EOL). Same shape as SelectAroundWord.
                let (lo, mut hi) = self.big_word_bounds_at(self.cursor);
                let bytes = self.text.as_bytes();
                let mut hi_extended = false;
                while hi < self.text.len() && matches!(bytes[hi], b' ' | b'\t') {
                    hi += 1;
                    hi_extended = true;
                }
                let mut lo_new = lo;
                if !hi_extended {
                    while lo_new > 0 && matches!(bytes[lo_new - 1], b' ' | b'\t') {
                        lo_new -= 1;
                    }
                }
                self.anchor = Some(lo_new);
                self.cursor = hi;
            }
            SelectAroundWord => {
                // vim `aw` — `iw` extended to include trailing whitespace,
                // or (when the word sits at end-of-line) leading whitespace
                // back to the previous non-space (vim's "around" semantics).
                let (lo, mut hi) = self.word_bounds_at(self.cursor);
                let bytes = self.text.as_bytes();
                let mut hi_extended = false;
                while hi < self.text.len() && matches!(bytes[hi], b' ' | b'\t') {
                    hi += 1;
                    hi_extended = true;
                }
                let mut lo_new = lo;
                if !hi_extended {
                    // No trailing ws to grab — fall back to leading ws.
                    while lo_new > 0 && matches!(bytes[lo_new - 1], b' ' | b'\t') {
                        lo_new -= 1;
                    }
                }
                self.anchor = Some(lo_new);
                self.cursor = hi;
            }
            AddCursorBelow => {
                // Add a cursor on the line BELOW the bottom-most existing
                // cursor (primary or extra). Chained presses extend
                // downward by one row each.
                let mut bottom_row = self.row_col().0;
                for &b in &self.extra_cursors {
                    let (r, _) = self.row_col_at(b);
                    if r > bottom_row {
                        bottom_row = r;
                    }
                }
                let lc = self.line_count();
                if bottom_row + 1 < lc {
                    let gc = self.goal_col();
                    let target = self.byte_at_col(bottom_row + 1, gc);
                    self.add_extra_cursor(target);
                }
            }
            AddCursorAbove => {
                let mut top_row = self.row_col().0;
                for &b in &self.extra_cursors {
                    let (r, _) = self.row_col_at(b);
                    if r < top_row {
                        top_row = r;
                    }
                }
                if top_row > 0 {
                    let gc = self.goal_col();
                    let target = self.byte_at_col(top_row - 1, gc);
                    self.add_extra_cursor(target);
                }
            }
            ClearExtraCursors => {
                self.extra_cursors.clear();
            }
            AddCursorAtNextWord => {
                // Word at the PRIMARY cursor is the rename target. Pick the
                // identifier the cursor sits on; if the cursor is one past
                // the last id char, prefer the word that ends there (same
                // rule as `word_under_cursor`).
                let bytes_all = self.text.as_bytes();
                let is_id = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
                let probe = if self.cursor < bytes_all.len() && is_id(bytes_all[self.cursor]) {
                    self.cursor
                } else if self.cursor > 0 && is_id(bytes_all[self.cursor - 1]) {
                    self.cursor - 1
                } else {
                    return;
                };
                let (ws, we) = self.word_bounds_at(probe);
                if ws == we {
                    return;
                }
                let word = self.text[ws..we].to_string();
                // First press: SELECT the word (anchor at its start,
                // cursor at its end) but don't add any extras yet.
                // That matches VS Code — 1st Ctrl+D selects, 2nd+
                // adds the next occurrence. Previously we jumped
                // straight to adding a next-match cursor on the very
                // first press with no visible feedback for the word
                // that had been "picked up".
                let first_press = self.extra_cursors.is_empty()
                    && self
                        .anchor
                        .map(|a| a != ws || self.cursor != we)
                        .unwrap_or(true);
                if first_press {
                    self.anchor = Some(ws);
                    self.cursor = we;
                    return;
                }
                let mut bottom = self.cursor;
                for &b in &self.extra_cursors {
                    if b > bottom {
                        bottom = b;
                    }
                }
                let bytes = self.text.as_bytes();
                let len = self.text.len();
                let is_id = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
                let target = word.as_bytes();
                let mut start = bottom;
                while start < len {
                    if let Some(off) = self.text[start..].find(&word) {
                        let pos = start + off;
                        let after = pos + target.len();
                        let before_ok = pos == 0 || !is_id(bytes[pos - 1]);
                        let after_ok = after == len || !is_id(bytes[after]);
                        // Skip the word that contains `bottom` itself (the
                        // cursor we last added is sitting at the end of its
                        // own match; we want the NEXT one).
                        if before_ok && after_ok && after > bottom {
                            // Add extra cursor at end-of-match AND anchor
                            // it at start-of-match so every occurrence
                            // shows the same word-selection highlight.
                            self.add_extra_cursor(after);
                            if let Some(i) = self.extra_cursors.iter().position(|&c| c == after) {
                                self.extra_anchors[i] = Some(pos);
                            }
                            return;
                        }
                        start = pos + 1;
                    } else {
                        break;
                    }
                }
            }

            // ── text mutation ──
            InsertChar(c) => {
                self.delete_selection_if_any(out);
                self.checkpoint_insert_run();
                if !self.extra_cursors.is_empty() {
                    // Multi-cursor insert: insert `c` at every cursor and
                    // advance each by char_len. Auto-pair is skipped here
                    // — the semantics get hairy across N cursors.
                    let mut positions: Vec<usize> = std::iter::once(self.cursor)
                        .chain(self.extra_cursors.iter().copied())
                        .collect();
                    positions.sort_unstable();
                    positions.dedup();
                    let primary_idx = positions
                        .iter()
                        .position(|&p| p == self.cursor)
                        .unwrap_or(0);
                    let char_len = c.len_utf8();
                    let mut tmp = [0u8; 4];
                    let s = c.encode_utf8(&mut tmp).to_string();
                    // Insert in descending order so earlier offsets stay valid.
                    for &p in positions.iter().rev() {
                        self.text.insert_str(p, &s);
                    }
                    let advanced: Vec<usize> = positions
                        .iter()
                        .enumerate()
                        .map(|(i, p)| p + (i + 1) * char_len)
                        .collect();
                    self.cursor = advanced[primary_idx];
                    self.extra_cursors = advanced
                        .iter()
                        .enumerate()
                        .filter(|(i, _)| *i != primary_idx)
                        .map(|(_, &p)| p)
                        .collect();
                    out.buffer_changed = true;
                    return;
                }
                // Auto-pair: typing `(` / `[` / `{` / `"` / `'` / `` ` `` inserts
                // the close char after the cursor when it makes sense (the next
                // char is end-of-line, whitespace, or another closer). When the
                // user types the same close char while the cursor sits *on*
                // an auto-inserted close, we skip over it instead of doubling
                // it up (`""` → type `"` → still `""`, cursor moved past).
                let close = auto_pair_close(c);
                if self.auto_pair
                    && let Some(closer) = close
                    && self.next_char_allows_pair()
                {
                    self.text.insert(self.cursor, c);
                    self.cursor += c.len_utf8();
                    self.text.insert(self.cursor, closer);
                    // Leave the cursor between the pair.
                    out.buffer_changed = true;
                } else if self.auto_pair && is_auto_pair_close(c) && self.cursor_on_char(c) {
                    // Skip over the auto-inserted close: just move past it.
                    self.cursor += c.len_utf8();
                } else {
                    self.text.insert(self.cursor, c);
                    self.cursor += c.len_utf8();
                    out.buffer_changed = true;
                }
            }
            InsertStr(s) => {
                if s.is_empty() {
                    return;
                }
                self.delete_selection_if_any(out);
                self.checkpoint();
                if !self.extra_cursors.is_empty() {
                    self.multi_insert_str(&s);
                    out.buffer_changed = true;
                    return;
                }
                self.text.insert_str(self.cursor, &s);
                self.cursor += s.len();
                out.buffer_changed = true;
            }
            InsertNewline => {
                self.delete_selection_if_any(out);
                self.checkpoint();
                if !self.extra_cursors.is_empty() {
                    // Multi-cursor newline — insert `\n` at every cursor.
                    // Auto-indent is skipped (per-cursor indent introspection
                    // gets hairy as earlier inserts shift later lines).
                    self.multi_insert_str("\n");
                    out.buffer_changed = true;
                    return;
                }
                let indent = if self.auto_indent {
                    self.leading_indent_of_line_to_cursor()
                } else {
                    String::new()
                };
                self.text.insert(self.cursor, '\n');
                self.cursor += 1;
                if !indent.is_empty() {
                    self.text.insert_str(self.cursor, &indent);
                    self.cursor += indent.len();
                }
                out.buffer_changed = true;
            }
            InsertNewlineBelow => {
                self.anchor = None;
                self.checkpoint();
                let line = self.current_line();
                let eol = self.line_end(line);
                let indent = if self.auto_indent {
                    self.leading_indent_of_line(line)
                } else {
                    String::new()
                };
                self.text.insert(eol, '\n');
                self.cursor = eol + 1;
                if !indent.is_empty() {
                    self.text.insert_str(self.cursor, &indent);
                    self.cursor += indent.len();
                }
                out.buffer_changed = true;
            }
            InsertNewlineAbove => {
                self.anchor = None;
                self.checkpoint();
                let line = self.current_line();
                let bol = self.line_start(line);
                self.text.insert(bol, '\n');
                self.cursor = bol;
                out.buffer_changed = true;
            }
            Backspace => {
                if self.delete_selection_if_any(out) {
                    return;
                }
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_backward();
                    out.buffer_changed = true;
                    return;
                }
                if self.cursor == 0 {
                    return;
                }
                self.checkpoint();
                let prev = self.prev_char_boundary(self.cursor);
                // Smart pair-backspace: when auto-pair is on and the cursor
                // sits between a paired `()` / `[]` / `""` etc., delete both
                // chars in one keystroke (so the undo of an auto-pair insert
                // is a single backspace).
                let pair_close = self.text[prev..self.cursor]
                    .chars()
                    .next()
                    .and_then(auto_pair_close);
                let next_byte = self.next_char_boundary(self.cursor);
                let next_char = self.text[self.cursor..next_byte].chars().next();
                if self.auto_pair
                    && let Some(closer) = pair_close
                    && next_char == Some(closer)
                {
                    self.text.replace_range(prev..next_byte, "");
                    self.cursor = prev;
                    out.buffer_changed = true;
                    return;
                }
                self.text.replace_range(prev..self.cursor, "");
                self.cursor = prev;
                out.buffer_changed = true;
            }
            DeleteForward => {
                if self.delete_selection_if_any(out) {
                    return;
                }
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_forward();
                    out.buffer_changed = true;
                    return;
                }
                if self.cursor >= self.text.len() {
                    return;
                }
                self.checkpoint();
                let next = self.next_char_boundary(self.cursor);
                self.text.replace_range(self.cursor..next, "");
                out.buffer_changed = true;
            }
            DeleteWordLeft => {
                if self.delete_selection_if_any(out) {
                    return;
                }
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_range_per_cursor(|ed, p| {
                        let target = ed.word_left_target_from(p);
                        (target, p)
                    });
                    out.buffer_changed = true;
                    return;
                }
                let target = self.word_left_target();
                if target == self.cursor {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(target..self.cursor, "");
                self.cursor = target;
                out.buffer_changed = true;
            }
            DeleteWordRight => {
                if self.delete_selection_if_any(out) {
                    return;
                }
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_range_per_cursor(|ed, p| {
                        let target = ed.word_right_target_from(p);
                        (p, target)
                    });
                    out.buffer_changed = true;
                    return;
                }
                let target = self.word_right_target();
                if target == self.cursor {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(self.cursor..target, "");
                out.buffer_changed = true;
            }
            DeleteToLineStart => {
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_range_per_cursor(|ed, p| {
                        let row = ed.row_col_at(p).0;
                        (ed.line_start(row), p)
                    });
                    out.buffer_changed = true;
                    return;
                }
                let bol = self.line_start(self.current_line());
                if bol == self.cursor {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(bol..self.cursor, "");
                self.cursor = bol;
                out.buffer_changed = true;
            }
            DeleteToLineEnd => {
                if !self.extra_cursors.is_empty() {
                    self.checkpoint();
                    self.multi_delete_range_per_cursor(|ed, p| {
                        let row = ed.row_col_at(p).0;
                        (p, ed.line_end(row))
                    });
                    out.buffer_changed = true;
                    return;
                }
                let eol = self.line_end(self.current_line());
                if eol == self.cursor {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(self.cursor..eol, "");
                out.buffer_changed = true;
            }
            DeleteLine => {
                // Yank the line + trailing newline into the unnamed
                // register before deleting (vim convention — `dd` yanks
                // the line linewise so a follow-up `p` re-inserts it).
                let line = self.current_line();
                let start = self.line_start(line);
                let line_text = self.line_str(line).to_string();
                let yanked = format!("{line_text}\n");
                clip.push_delete(yanked.clone(), true);
                out.clipboard_set = Some(yanked);
                out.clipboard_linewise = true;
                self.anchor = None;
                self.checkpoint();
                let has_newline_after = self.line_end(line) < self.text.len();
                if has_newline_after {
                    let end = self.line_end(line) + 1;
                    self.text.replace_range(start..end, "");
                    self.cursor = start.min(self.text.len());
                } else if start > 0 {
                    let prev_line_start = self.line_start(line - 1);
                    let cut_from = self.prev_char_boundary(start);
                    self.text.replace_range(cut_from..self.text.len(), "");
                    self.cursor = prev_line_start.min(self.text.len());
                } else {
                    self.text.clear();
                    self.cursor = 0;
                }
                out.buffer_changed = true;
            }
            DeleteSelection => {
                // Yank the deleted text first (vim convention — `d{motion}`
                // yanks). Standard mode emits this op only via explicit
                // copy/cut paths, so always-yank is the right default.
                let has_extras_sel = self
                    .extra_anchors
                    .iter()
                    .any(|a| a.is_some_and(|av| av != self.cursor));
                if has_extras_sel {
                    // Multi-cursor: gather every (anchor, cursor) range,
                    // join the texts with `\n`, then delete all in one go.
                    let mut ranges: Vec<(usize, usize)> = Vec::new();
                    if let Some(a) = self.anchor
                        && a != self.cursor
                    {
                        let (lo, hi) = if a < self.cursor {
                            (a, self.cursor)
                        } else {
                            (self.cursor, a)
                        };
                        ranges.push((lo, hi));
                    }
                    for (i, c) in self.extra_cursors.iter().enumerate() {
                        if let Some(a) = self.extra_anchors[i]
                            && a != *c
                        {
                            let (lo, hi) = if a < *c { (a, *c) } else { (*c, a) };
                            ranges.push((lo, hi));
                        }
                    }
                    ranges.sort_unstable();
                    let texts: Vec<String> = ranges
                        .iter()
                        .map(|&(lo, hi)| self.text[lo..hi].to_string())
                        .collect();
                    let joined = texts.join("\n");
                    if !joined.is_empty() {
                        clip.push_delete(joined.clone(), false);
                        out.clipboard_set = Some(joined);
                    }
                    self.checkpoint();
                    self.multi_delete_range_per_cursor(|ed, p| {
                        // Recompute each cursor's range from CURRENT state —
                        // the closure runs against an editor that hasn't
                        // been mutated yet, but anchors are tracked.
                        let idx = if p == ed.cursor {
                            None
                        } else {
                            ed.extra_cursors.iter().position(|&c| c == p)
                        };
                        let anchor = match idx {
                            None => ed.anchor,
                            Some(i) => ed.extra_anchors.get(i).copied().flatten(),
                        };
                        match anchor {
                            Some(a) if a != p => (a.min(p), a.max(p)),
                            _ => (p, p),
                        }
                    });
                    out.buffer_changed = true;
                    return;
                }
                if let Some((lo, hi)) = self.selection()
                    && hi > lo
                {
                    let s = self.text[lo..hi].to_string();
                    clip.push_delete(s.clone(), false);
                    out.clipboard_set = Some(s);
                }
                self.delete_selection_if_any(out);
            }
            ReplaceSelection(s) => {
                self.checkpoint();
                let extras_have_sel = self
                    .extra_anchors
                    .iter()
                    .any(|a| a.is_some_and(|av| av != self.cursor));
                if extras_have_sel {
                    // Multi-cursor: delete every (anchor, cursor) range,
                    // then insert `s` at each cursor's resting position.
                    self.multi_delete_range_per_cursor(|ed, p| {
                        let idx = if p == ed.cursor {
                            None
                        } else {
                            ed.extra_cursors.iter().position(|&c| c == p)
                        };
                        let anchor = match idx {
                            None => ed.anchor,
                            Some(i) => ed.extra_anchors.get(i).copied().flatten(),
                        };
                        match anchor {
                            Some(a) if a != p => (a.min(p), a.max(p)),
                            _ => (p, p),
                        }
                    });
                    if !s.is_empty() {
                        self.multi_insert_str(&s);
                    }
                    self.anchor = None;
                    for a in self.extra_anchors.iter_mut() {
                        *a = None;
                    }
                    out.buffer_changed = true;
                    return;
                }
                if let Some((lo, hi)) = self.selection() {
                    self.text.replace_range(lo..hi, &s);
                    self.cursor = lo + s.len();
                } else {
                    self.text.insert_str(self.cursor, &s);
                    self.cursor += s.len();
                }
                self.anchor = None;
                out.buffer_changed = true;
            }
            OverwriteCharAndAdvance(c) => {
                self.checkpoint();
                let cur = self.cursor;
                let next = self.text[cur..].chars().next();
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf).to_string();
                match next {
                    Some('\n') | None => {
                        // At EOL or EOF — insert instead of overwrite. Push
                        // `None` so Backspace knows to just delete-back.
                        self.text.insert_str(cur, &s);
                        self.cursor = cur + s.len();
                        self.replace_stack.push(None);
                    }
                    Some(target) => {
                        let end = cur + target.len_utf8();
                        self.text.replace_range(cur..end, &s);
                        self.cursor = cur + s.len();
                        // Remember the original char so Backspace can
                        // restore it (vim canonical Replace-Backspace).
                        self.replace_stack.push(Some(target));
                    }
                }
                out.buffer_changed = true;
            }
            ReplaceUndoOne => {
                let Some(prev) = self.replace_stack.pop() else {
                    // Nothing to undo — at the Replace-session origin.
                    return;
                };
                self.checkpoint();
                // The just-inserted char sits immediately before `cursor`.
                // Step the cursor back over it and patch the text.
                let before = self.prev_char_boundary(self.cursor);
                match prev {
                    Some(original) => {
                        // Replace the inserted char with the original.
                        let mut buf = [0u8; 4];
                        let s = original.encode_utf8(&mut buf).to_string();
                        self.text.replace_range(before..self.cursor, &s);
                    }
                    None => {
                        // Inserted-past-EOL — delete the inserted char.
                        self.text.replace_range(before..self.cursor, "");
                    }
                }
                self.cursor = before;
                out.buffer_changed = true;
            }
            ReplaceSessionBegin => {
                self.replace_stack.clear();
            }
            ReplaceCharAtCursor(c) => {
                if let Some((lo, hi)) = self.selection() {
                    // visual r<c>: replace each non-newline char with c
                    self.checkpoint();
                    let mut out_s = String::with_capacity(hi - lo);
                    for ch in self.text[lo..hi].chars() {
                        if ch == '\n' {
                            out_s.push('\n');
                        } else {
                            out_s.push(c);
                        }
                    }
                    self.text.replace_range(lo..hi, &out_s);
                    self.cursor = lo;
                    self.anchor = None;
                    out.buffer_changed = true;
                } else {
                    let cur = self.cursor;
                    if let Some(target) = self.text[cur..].chars().next()
                        && target != '\n'
                    {
                        self.checkpoint();
                        let end = cur + target.len_utf8();
                        let mut buf = [0u8; 4];
                        let s = c.encode_utf8(&mut buf);
                        self.text.replace_range(cur..end, s);
                        // cursor stays at `cur` (vim convention)
                        out.buffer_changed = true;
                    }
                }
            }
            ReplaceRange { start, end, text } => {
                let len = self.text.len();
                let start = start.min(len);
                let end = end.min(len).max(start);
                if self.text.is_char_boundary(start) && self.text.is_char_boundary(end) {
                    self.checkpoint();
                    self.text.replace_range(start..end, &text);
                    self.cursor = start + text.len();
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            Indent => {
                self.checkpoint();
                let pad: String = " ".repeat(self.tab_width);
                let changed = self.for_each_selected_line(|ed, bol| {
                    ed.text.insert_str(bol, &pad);
                    pad.len() as isize
                });
                if changed {
                    out.buffer_changed = true;
                } else {
                    self.pop_checkpoint();
                }
            }
            Outdent => {
                self.checkpoint();
                let tw = self.tab_width;
                let changed = self.for_each_selected_line(|ed, bol| {
                    let mut remove = 0usize;
                    for ch in ed.text[bol..].chars().take(tw) {
                        if ch == ' ' {
                            remove += 1;
                        } else if ch == '\t' {
                            remove += 1;
                            break;
                        } else {
                            break;
                        }
                    }
                    if remove > 0 {
                        ed.text.replace_range(bol..bol + remove, "");
                    }
                    -(remove as isize)
                });
                if changed {
                    out.buffer_changed = true;
                } else {
                    self.pop_checkpoint();
                }
            }
            ToggleLineComment => {
                self.checkpoint();
                let token = self.comment_token.clone();
                let close = self.comment_token_close.clone();
                let trimmed = token.trim_end().to_string();
                let close_trimmed = close.trim_start().to_string();
                let has_close = !close_trimmed.is_empty();
                // Decide add vs remove from the first selected line's leading content.
                let first_line = self.text
                    [..self.selection().map(|(l, _)| l).unwrap_or(self.cursor)]
                    .bytes()
                    .filter(|&b| b == b'\n')
                    .count();
                let fl_start = self.line_start(first_line);
                let fl_indent_end = {
                    let mut b = fl_start;
                    for ch in self.line_str(first_line).chars() {
                        if ch.is_whitespace() {
                            b += ch.len_utf8();
                        } else {
                            break;
                        }
                    }
                    b
                };
                let already = self.text[fl_indent_end..].starts_with(&trimmed);
                let changed = self.for_each_selected_line(|ed, bol| {
                    // find indent end
                    let mut ie = bol;
                    for ch in ed.text[bol..].chars() {
                        if ch == '\n' {
                            return 0;
                        }
                        if ch.is_whitespace() {
                            ie += ch.len_utf8();
                        } else {
                            break;
                        }
                    }
                    // End-of-line byte (exclusive of `\n`). Used to splice
                    // / strip the close token for block-comment languages.
                    let eol = {
                        let mut e = ie;
                        for ch in ed.text[ie..].chars() {
                            if ch == '\n' {
                                break;
                            }
                            e += ch.len_utf8();
                        }
                        e
                    };
                    if already {
                        // Strip the close first (rightmost edit) so the
                        // open's strip below doesn't shift the close offset.
                        let mut close_delta: isize = 0;
                        if has_close {
                            if ed.text[..eol].ends_with(&close) {
                                let cut = eol - close.len();
                                ed.text.replace_range(cut..eol, "");
                                close_delta = -(close.len() as isize);
                            } else if ed.text[..eol].ends_with(&close_trimmed) {
                                let cut = eol - close_trimmed.len();
                                ed.text.replace_range(cut..eol, "");
                                close_delta = -(close_trimmed.len() as isize);
                            }
                        }
                        let open_delta = if ed.text[ie..].starts_with(&token) {
                            ed.text.replace_range(ie..ie + token.len(), "");
                            -(token.len() as isize)
                        } else if ed.text[ie..].starts_with(&trimmed) {
                            ed.text.replace_range(ie..ie + trimmed.len(), "");
                            -(trimmed.len() as isize)
                        } else {
                            0
                        };
                        open_delta + close_delta
                    } else {
                        // Splice the close at EOL first (rightmost edit) so
                        // the open insert below doesn't shift EOL.
                        let mut close_delta: isize = 0;
                        if has_close {
                            ed.text.insert_str(eol, &close);
                            close_delta = close.len() as isize;
                        }
                        ed.text.insert_str(ie, &token);
                        token.len() as isize + close_delta
                    }
                });
                if changed {
                    out.buffer_changed = true;
                } else {
                    self.pop_checkpoint();
                }
            }
            MoveLineUp => {
                // Selection-aware: shift the whole selected block up by 1
                // (the row above slides past the block to land just below
                // it). Otherwise single-line swap.
                let (start_row, end_row) = self
                    .selection()
                    .map(|(lo, hi)| {
                        (
                            self.row_col_at(lo).0,
                            // The selection's exclusive endpoint sometimes
                            // sits at the start of the line *after* the
                            // last selected line; back it off in that case.
                            {
                                let (r, c) = self.row_col_at(hi);
                                if c == 0 && r > self.row_col_at(lo).0 {
                                    r - 1
                                } else {
                                    r
                                }
                            },
                        )
                    })
                    .unwrap_or_else(|| {
                        let l = self.current_line();
                        (l, l)
                    });
                if start_row == 0 {
                    return;
                }
                self.checkpoint();
                // Swap-walk: cycle the line above through the block.
                for r in start_row..=end_row {
                    self.swap_lines(r - 1, r);
                }
                let cur_line = self.current_line();
                let new_line = cur_line.saturating_sub(1);
                let col = self.goal_col();
                self.cursor = self.byte_at_col(new_line, col);
                // Shift the anchor too so the selection follows.
                if let Some(a) = self.anchor {
                    let (ar, ac) = self.row_col_at(a);
                    self.anchor = Some(self.byte_at_col(ar.saturating_sub(1), ac));
                }
                out.buffer_changed = true;
            }
            MoveLineDown => {
                let (start_row, end_row) = self
                    .selection()
                    .map(|(lo, hi)| {
                        (self.row_col_at(lo).0, {
                            let (r, c) = self.row_col_at(hi);
                            if c == 0 && r > self.row_col_at(lo).0 {
                                r - 1
                            } else {
                                r
                            }
                        })
                    })
                    .unwrap_or_else(|| {
                        let l = self.current_line();
                        (l, l)
                    });
                if end_row + 1 >= self.line_count() {
                    return;
                }
                self.checkpoint();
                for r in (start_row..=end_row).rev() {
                    self.swap_lines(r, r + 1);
                }
                let cur_line = self.current_line();
                let new_line = (cur_line + 1).min(self.line_count().saturating_sub(1));
                let col = self.goal_col();
                self.cursor = self.byte_at_col(new_line, col);
                if let Some(a) = self.anchor {
                    let (ar, ac) = self.row_col_at(a);
                    self.anchor = Some(self.byte_at_col(ar + 1, ac));
                }
                out.buffer_changed = true;
            }
            DuplicateLine => {
                self.checkpoint();
                let line = self.current_line();
                let bol = self.line_start(line);
                let eol = self.line_end(line);
                // Insert `\n<line-text>` right after the current line content.
                // (Works for the last line — no trailing newline needed beyond
                // what gets inserted.)
                let body = self.text[bol..eol].to_string();
                self.text.insert(eol, '\n');
                self.text.insert_str(eol + 1, &body);
                // Move the cursor to the same column on the new line.
                let col = self.col_at_byte(self.cursor);
                self.cursor = self.byte_at_col(line + 1, col);
                out.buffer_changed = true;
            }
            ToggleCaseChar => {
                // vim `~` — toggle the ASCII letter under the cursor + advance.
                if self.cursor < self.text.len() {
                    let b = self.text.as_bytes()[self.cursor];
                    if b.is_ascii_alphabetic() {
                        self.checkpoint();
                        let toggled = if b.is_ascii_uppercase() {
                            b.to_ascii_lowercase()
                        } else {
                            b.to_ascii_uppercase()
                        };
                        // Single-byte ASCII swap; replace_range keeps it safe.
                        let s = std::str::from_utf8(&[toggled]).unwrap().to_string();
                        self.text.replace_range(self.cursor..self.cursor + 1, &s);
                        out.buffer_changed = true;
                    }
                    // Advance to the next char boundary (handles multi-byte).
                    let mut next = self.cursor + 1;
                    while next < self.text.len() && !self.text.is_char_boundary(next) {
                        next += 1;
                    }
                    self.cursor = next;
                }
            }
            ChangeNumberAtCursor { delta } => {
                // Smart pre-pass: try to bump a "smart" token under the
                // cursor (booleans, day-of-week names, month names, ISO
                // dates). Falls through to the number path on no match.
                if let Some((start, end, new_str)) =
                    smart_increment_at(&self.text, self.cursor, self.current_line(), delta)
                {
                    self.checkpoint();
                    self.text.replace_range(start..end, &new_str);
                    self.cursor = start + new_str.len().saturating_sub(1);
                    self.anchor = None;
                    out.buffer_changed = true;
                    return;
                }
                let line = self.current_line();
                let bol = self.line_start(line);
                let eol = self.line_end(line);
                let bytes = self.text.as_bytes();
                // Walk forward from cursor on this line until we hit a digit.
                let mut digit_pos = self.cursor.max(bol);
                while digit_pos < eol && !bytes[digit_pos].is_ascii_digit() {
                    digit_pos += 1;
                }
                if digit_pos >= eol {
                    return;
                }
                // The number's start: walk back through digits.
                let mut start = digit_pos;
                while start > bol && bytes[start - 1].is_ascii_digit() {
                    start -= 1;
                }
                // Maybe a leading `-` sign — qualifies when the char *before*
                // it isn't an identifier char (digit / letter / `_`).
                if start > bol && bytes[start - 1] == b'-' {
                    let qualifies = start - 1 == bol
                        || !(bytes[start - 2].is_ascii_alphanumeric() || bytes[start - 2] == b'_');
                    if qualifies {
                        start -= 1;
                    }
                }
                // The number's end: walk forward through digits.
                let mut end = digit_pos;
                while end < eol && bytes[end].is_ascii_digit() {
                    end += 1;
                }
                let num_str = &self.text[start..end];
                let Ok(n) = num_str.parse::<i64>() else {
                    return;
                };
                let new_n = n.saturating_add(delta);
                let new_str = new_n.to_string();
                if new_str == num_str {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(start..end, &new_str);
                // Cursor lands on the last char of the new number (vim).
                self.cursor = start + new_str.len().saturating_sub(1);
                self.anchor = None;
                out.buffer_changed = true;
            }
            ReflowParagraph { width } => {
                let (start, end) = self.paragraph_bounds(false);
                if end <= start {
                    return;
                }
                let body = &self.text[start..end];
                if body.trim().is_empty() {
                    return;
                }
                // Keep the leading whitespace of the first line as the
                // common indent — applied to every wrapped line so indented
                // prose stays indented.
                let first_line_end = body.find('\n').unwrap_or(body.len());
                let indent: String = body[..first_line_end]
                    .chars()
                    .take_while(|c| c.is_whitespace())
                    .collect();
                // Greedy word-wrap. Words = runs of non-whitespace; the
                // separator between them is always a single space (no
                // attempt to preserve double-space-after-period etc.).
                let words: Vec<&str> = body.split_whitespace().filter(|w| !w.is_empty()).collect();
                if words.is_empty() {
                    return;
                }
                let target = width.max(indent.chars().count() + 8);
                let mut wrapped = String::with_capacity(body.len());
                let mut line_chars = 0usize;
                for (i, w) in words.iter().enumerate() {
                    let wlen = w.chars().count();
                    if i == 0 {
                        wrapped.push_str(&indent);
                        wrapped.push_str(w);
                        line_chars = indent.chars().count() + wlen;
                    } else if line_chars + 1 + wlen > target {
                        wrapped.push('\n');
                        wrapped.push_str(&indent);
                        wrapped.push_str(w);
                        line_chars = indent.chars().count() + wlen;
                    } else {
                        wrapped.push(' ');
                        wrapped.push_str(w);
                        line_chars += 1 + wlen;
                    }
                }
                if wrapped == body {
                    return;
                }
                self.checkpoint();
                self.text.replace_range(start..end, &wrapped);
                self.cursor = start;
                self.anchor = None;
                out.buffer_changed = true;
            }
            TransformSelectionCase(kind) => {
                if let Some((lo, hi)) = self.selection() {
                    let original = &self.text[lo..hi];
                    let transformed: String = match kind {
                        CaseTransform::Lower => original.to_lowercase(),
                        CaseTransform::Upper => original.to_uppercase(),
                        CaseTransform::Toggle => original
                            .chars()
                            .map(|c| {
                                if c.is_ascii_uppercase() {
                                    c.to_ascii_lowercase()
                                } else if c.is_ascii_lowercase() {
                                    c.to_ascii_uppercase()
                                } else {
                                    c
                                }
                            })
                            .collect(),
                    };
                    if transformed != original {
                        self.checkpoint();
                        self.text.replace_range(lo..hi, &transformed);
                        // Cursor lands at the end of the transformed range
                        // (vim parks it at the start, but landing at the end
                        // is more useful when chaining; both are common).
                        self.cursor = lo + transformed.len();
                        self.anchor = None;
                        out.buffer_changed = true;
                    } else {
                        // No actual change (e.g. lowercasing all-lowercase
                        // text) — still drop the selection like vim does.
                        self.cursor = lo;
                        self.anchor = None;
                    }
                }
            }
            AlignSelection { on_char } => {
                if let Some((lo, hi)) = self.selection() {
                    let first_line = self.text[..lo].bytes().filter(|&b| b == b'\n').count();
                    let mut last_line = self.text[..hi].bytes().filter(|&b| b == b'\n').count();
                    if hi > lo && hi > 0 && self.text.as_bytes()[hi - 1] == b'\n' {
                        last_line = last_line.saturating_sub(1);
                    }
                    if last_line >= first_line {
                        let mut targets: Vec<(usize, usize)> = Vec::new();
                        let mut max_col: usize = 0;
                        for line in first_line..=last_line {
                            let bol = self.line_start(line);
                            let eol = self.line_end(line);
                            let mut byte = bol;
                            let mut hit = None;
                            for (col, c) in self.text[bol..eol].chars().enumerate() {
                                if c == on_char {
                                    hit = Some((byte, col));
                                    break;
                                }
                                byte += c.len_utf8();
                            }
                            if let Some((b, c)) = hit {
                                targets.push((b, c));
                                if c > max_col {
                                    max_col = c;
                                }
                            }
                        }
                        let needs_change = targets.iter().any(|(_, c)| max_col - c > 0);
                        if needs_change {
                            self.checkpoint();
                            // Insert padding descending so earlier byte offsets stay valid.
                            for &(byte, col) in targets.iter().rev() {
                                let pad = max_col - col;
                                if pad > 0 {
                                    self.text.insert_str(byte, &" ".repeat(pad));
                                }
                            }
                            self.cursor = self.line_start(first_line).min(self.text.len());
                            self.anchor = None;
                            out.buffer_changed = true;
                        } else {
                            // Already aligned (or no `on_char` found on any line).
                            // Drop the selection — matches case-transform ops.
                            self.cursor = lo;
                            self.anchor = None;
                        }
                    }
                }
            }
            JoinLines { keep_space } => {
                // vim `J` (keep_space=true) / `gJ` (keep_space=false).
                let line = self.current_line();
                let total = self.line_count();
                if line + 1 < total {
                    self.checkpoint();
                    let bol = self.line_start(line);
                    let eol = self.line_end(line);
                    // Walk back from end-of-line past trailing whitespace
                    // (only when we're keeping the space — `gJ` preserves
                    // *all* whitespace verbatim, vim convention).
                    let mut trim_end = eol;
                    if keep_space {
                        while trim_end > bol {
                            let b = self.text.as_bytes()[trim_end - 1];
                            if b == b' ' || b == b'\t' {
                                trim_end -= 1;
                            } else {
                                break;
                            }
                        }
                    }
                    // Same for leading whitespace on the next line — `gJ`
                    // keeps it; `J` eats it.
                    let next_bol = eol + 1;
                    let next_eol = self.line_end(line + 1);
                    let mut next_first = next_bol;
                    if keep_space {
                        while next_first < next_eol {
                            let b = self.text.as_bytes()[next_first];
                            if b == b' ' || b == b'\t' {
                                next_first += 1;
                            } else {
                                break;
                            }
                        }
                    }
                    // Insert " " between unless we're in `gJ` mode, OR the
                    // (post-trim) current line is empty.
                    let separator = if !keep_space || trim_end == bol {
                        ""
                    } else {
                        " "
                    };
                    self.text.replace_range(trim_end..next_first, separator);
                    // Cursor lands ON the inserted space (or at the join
                    // boundary when none was inserted).
                    self.cursor = trim_end;
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }

            // ── clipboard / registers ──
            SetRegisterHint(reg) => {
                clip.set_pending_register(reg);
            }
            YankLine => {
                let line = self.current_line();
                let (line_start, line_end) = self.line_byte_range(line);
                let mut s = self.line_str(line).to_string();
                s.push('\n');
                clip.set_yank(s.clone(), true);
                out.clipboard_set = Some(s);
                out.clipboard_linewise = true;
                // Include the trailing newline if there is one — the flash
                // should cover the whole "line" the user yanked.
                let end = line_end + if line_end < self.text.len() { 1 } else { 0 };
                out.yanked_range = Some((line_start, end));
            }
            YankLinesCount(n) => {
                if n == 0 {
                    return;
                }
                let start_line = self.current_line();
                let total_lines = self.line_count();
                let end_line = (start_line + n as usize)
                    .saturating_sub(1)
                    .min(total_lines.saturating_sub(1));
                let (start, _) = self.line_byte_range(start_line);
                let (_, last_end) = self.line_byte_range(end_line);
                // Include trailing newline if present so paste behaves
                // linewise (drops onto a new line rather than the tail
                // of an existing one).
                let end = last_end + if last_end < self.text.len() { 1 } else { 0 };
                let s = self.text[start..end].to_string();
                let s = if s.ends_with('\n') {
                    s
                } else {
                    format!("{s}\n")
                };
                clip.set_yank(s.clone(), true);
                out.clipboard_set = Some(s);
                out.clipboard_linewise = true;
                out.yanked_range = Some((start, end));
            }
            BlockSelectStart => {
                self.block_anchor = Some(self.cursor);
                // Block mode is independent of charwise; clear any
                // lingering charwise anchor.
                self.anchor = None;
            }
            BlockSelectClear => {
                self.block_anchor = None;
            }
            YankBlock => {
                if let Some((rmin, cmin, rmax, cmax)) = self.block_selection() {
                    let ranges = self.block_ranges(rmin, cmin, rmax, cmax);
                    let mut parts: Vec<String> = Vec::with_capacity(ranges.len());
                    for (s, e) in &ranges {
                        parts.push(self.text[*s..*e].to_string());
                    }
                    let joined = parts.join("\n");
                    clip.set_yank(joined.clone(), false);
                    out.clipboard_set = Some(joined);
                    // Flash the rectangle's bounding byte range (from the
                    // first range's start to the last range's end).
                    if let (Some(&(lo, _)), Some(&(_, hi))) = (ranges.first(), ranges.last()) {
                        out.yanked_range = Some((lo, hi));
                    }
                    self.block_anchor = None;
                }
            }
            DeleteBlock => {
                if let Some((rmin, cmin, rmax, cmax)) = self.block_selection() {
                    let ranges = self.block_ranges(rmin, cmin, rmax, cmax);
                    // Yank into clipboard first (vim convention — `d` yanks).
                    let mut parts: Vec<String> = Vec::with_capacity(ranges.len());
                    for (s, e) in &ranges {
                        parts.push(self.text[*s..*e].to_string());
                    }
                    let joined = parts.join("\n");
                    clip.push_delete(joined.clone(), false);
                    out.clipboard_set = Some(joined);
                    // Splice descending so earlier byte offsets stay valid.
                    self.checkpoint();
                    let mut sorted = ranges.clone();
                    sorted.sort_by_key(|r| std::cmp::Reverse(r.0));
                    for (s, e) in sorted {
                        if s < e {
                            self.text.replace_range(s..e, "");
                        }
                    }
                    // Land cursor at the rectangle's top-left (the byte at
                    // rmin's start-of-line + cmin chars, clamped to the
                    // post-edit line content).
                    let (line_s, line_e) = self.line_byte_range(rmin);
                    let line_text = &self.text[line_s..line_e];
                    let mut b = line_s;
                    for (col, ch) in line_text.chars().enumerate() {
                        if col == cmin {
                            break;
                        }
                        b += ch.len_utf8();
                    }
                    self.cursor = b;
                    self.block_anchor = None;
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            YankSelection => {
                // Multi-cursor: collect every (anchor, cursor) range, join
                // with `\n`, yank the lot. Each extra's selection ends.
                let extras_have_sel = self
                    .extra_anchors
                    .iter()
                    .any(|a| a.is_some_and(|av| av != self.cursor));
                if extras_have_sel {
                    let mut ranges: Vec<(usize, usize)> = Vec::new();
                    if let Some(a) = self.anchor
                        && a != self.cursor
                    {
                        let (lo, hi) = if a < self.cursor {
                            (a, self.cursor)
                        } else {
                            (self.cursor, a)
                        };
                        ranges.push((lo, hi));
                    }
                    for (i, c) in self.extra_cursors.iter().enumerate() {
                        if let Some(a) = self.extra_anchors[i]
                            && a != *c
                        {
                            let (lo, hi) = if a < *c { (a, *c) } else { (*c, a) };
                            ranges.push((lo, hi));
                        }
                    }
                    ranges.sort_unstable();
                    let joined = ranges
                        .iter()
                        .map(|&(lo, hi)| self.text[lo..hi].to_string())
                        .collect::<Vec<_>>()
                        .join("\n");
                    if !joined.is_empty() {
                        clip.set_yank(joined.clone(), false);
                        out.clipboard_set = Some(joined);
                    }
                    self.remember_selection();
                    return;
                }
                if let Some((lo, hi)) = self.selection() {
                    let s = self.text[lo..hi].to_string();
                    clip.set_yank(s.clone(), false);
                    out.clipboard_set = Some(s);
                    out.yanked_range = Some((lo, hi));
                    self.remember_selection();
                }
            }
            YankSelectionLinewise => {
                // Mirror of `YankSelection` for V-mode. Marks the
                // clipboard linewise so `p` puts the yank onto a new
                // line below the cursor rather than gluing onto the
                // current line's tail. nvchad-round-11 SEV-2
                // 2026-07-12.
                if let Some((lo, hi)) = self.selection() {
                    let mut s = self.text[lo..hi].to_string();
                    // Ensure the payload ends in `\n` so PasteAfter's
                    // linewise-shape assumption holds.
                    if !s.ends_with('\n') {
                        s.push('\n');
                    }
                    clip.set_yank(s.clone(), true);
                    out.clipboard_set = Some(s);
                    out.clipboard_linewise = true;
                    out.yanked_range = Some((lo, hi));
                    self.remember_selection();
                }
            }
            CutSelection => {
                if let Some((lo, hi)) = self.selection() {
                    let s = self.text[lo..hi].to_string();
                    clip.push_delete(s.clone(), false);
                    out.clipboard_set = Some(s);
                    self.checkpoint();
                    self.text.replace_range(lo..hi, "");
                    self.cursor = lo;
                    self.anchor = None;
                    out.buffer_changed = true;
                }
            }
            PasteAfter => {
                let s = clip.text();
                if s.is_empty() {
                    return;
                }
                self.checkpoint();
                // Multi-cursor distributed paste: if the clipboard splits
                // into exactly N lines (one per cursor), each cursor gets
                // one line. Otherwise fall back to inserting the whole
                // clipboard at every cursor.
                if !self.extra_cursors.is_empty() {
                    let parts: Vec<&str> = s.split('\n').collect();
                    let total_cursors = self.extra_cursors.len() + 1;
                    if parts.len() == total_cursors {
                        self.multi_paste_distribute(&parts, true);
                    } else {
                        self.multi_insert_str(&s);
                    }
                    self.anchor = None;
                    for a in self.extra_anchors.iter_mut() {
                        *a = None;
                    }
                    out.buffer_changed = true;
                    return;
                }
                if clip.is_linewise() {
                    let line = self.current_line();
                    let eol = self.line_end(line);
                    let insert_at = if eol < self.text.len() { eol + 1 } else { eol };
                    let mut payload = s.clone();
                    if eol >= self.text.len() && !self.text.is_empty() {
                        payload = format!("\n{}", s.trim_end_matches('\n'));
                    }
                    self.text.insert_str(insert_at, &payload);
                    self.cursor = if eol < self.text.len() {
                        insert_at
                    } else {
                        insert_at + 1
                    };
                } else {
                    let at = self.next_char_boundary(self.cursor).min(self.text.len());
                    self.text.insert_str(at, &s);
                    self.cursor = at + s.len();
                }
                self.anchor = None;
                out.buffer_changed = true;
            }
            PasteBefore => {
                let s = clip.text();
                if s.is_empty() {
                    return;
                }
                self.checkpoint();
                if !self.extra_cursors.is_empty() {
                    let parts: Vec<&str> = s.split('\n').collect();
                    let total_cursors = self.extra_cursors.len() + 1;
                    if parts.len() == total_cursors {
                        self.multi_paste_distribute(&parts, false);
                    } else {
                        // Insert at each cursor (not next-char-boundary). We
                        // reuse multi_insert_str which inserts at `self.cursor`
                        // / each extra cursor — exactly the "before" semantics.
                        self.multi_insert_str(&s);
                    }
                    self.anchor = None;
                    for a in self.extra_anchors.iter_mut() {
                        *a = None;
                    }
                    out.buffer_changed = true;
                    return;
                }
                if clip.is_linewise() {
                    let line = self.current_line();
                    let bol = self.line_start(line);
                    self.text.insert_str(bol, &s);
                    self.cursor = bol;
                } else {
                    self.text.insert_str(self.cursor, &s);
                    self.cursor += s.len();
                }
                self.anchor = None;
                out.buffer_changed = true;
            }
            PasteAfterEnd => {
                let s = clip.text();
                if s.is_empty() {
                    return;
                }
                self.checkpoint();
                if clip.is_linewise() {
                    let line = self.current_line();
                    let eol = self.line_end(line);
                    let insert_at = if eol < self.text.len() { eol + 1 } else { eol };
                    let mut payload = s.clone();
                    if eol >= self.text.len() && !self.text.is_empty() {
                        payload = format!("\n{}", s.trim_end_matches('\n'));
                    }
                    self.text.insert_str(insert_at, &payload);
                    // gp: cursor at END of pasted block (vim convention).
                    self.cursor = insert_at + payload.len();
                } else {
                    let at = self.next_char_boundary(self.cursor).min(self.text.len());
                    self.text.insert_str(at, &s);
                    self.cursor = at + s.len();
                }
                self.anchor = None;
                out.buffer_changed = true;
            }
            PasteBeforeEnd => {
                let s = clip.text();
                if s.is_empty() {
                    return;
                }
                self.checkpoint();
                if clip.is_linewise() {
                    let line = self.current_line();
                    let bol = self.line_start(line);
                    self.text.insert_str(bol, &s);
                    self.cursor = bol + s.len();
                } else {
                    self.text.insert_str(self.cursor, &s);
                    self.cursor += s.len();
                }
                self.anchor = None;
                out.buffer_changed = true;
            }
            Paste => {
                let s = clip.text();
                if s.is_empty() {
                    return;
                }
                // vscode-user SEV-2 2026-07-10: paste-over-selection
                // used to split into two undo steps because
                // `delete_selection_if_any` calls `checkpoint()` when
                // it deletes, and Paste then called `checkpoint()`
                // again before the insert. First Ctrl+Z rewound only
                // the insert, leaving the buffer showing the delete
                // half (looked like the file was wiped). Skip our own
                // checkpoint when the delete already made one; only
                // paste-without-selection needs its own.
                let deleted = self.delete_selection_if_any(out);
                if !deleted {
                    self.checkpoint();
                }
                self.text.insert_str(self.cursor, &s);
                self.cursor += s.len();
                self.anchor = None;
                out.buffer_changed = true;
            }

            // ── history ──
            // keyboard-round-12 SEV-2 2026-07-14 — clear extra
            // cursors on undo/redo so `Ctrl+Shift+L` + type +
            // `Ctrl+Z` doesn't leave the buffer restored but the
            // extras still armed (subsequent typing then hit every
            // dormant cursor — data integrity risk). VS Code
            // snapshots selection alongside text; mnml's Snapshot
            // struct doesn't yet include the extra_cursors /
            // extra_anchors vectors so match VS Code's UX at a
            // higher level: an undo/redo exits multi-cursor mode.
            // The user can always Ctrl+Shift+L again to restore
            // it.
            Undo => {
                if let Some(s) = self.undo.pop() {
                    let cur = self.snapshot();
                    self.redo.push(cur);
                    self.restore(s);
                    self.extra_cursors.clear();
                    self.extra_anchors.clear();
                    out.buffer_changed = true;
                }
            }
            Redo => {
                if let Some(s) = self.redo.pop() {
                    let cur = self.snapshot();
                    self.undo.push(cur);
                    self.restore(s);
                    self.extra_cursors.clear();
                    self.extra_anchors.clear();
                    out.buffer_changed = true;
                }
            }
        }
    }

    /// Pop the most recent undo snapshot back off — used when a "mutation" turned
    /// out to be a no-op so we don't leave a redundant undo step.
    fn pop_checkpoint(&mut self) {
        self.undo.pop();
    }

    /// Delete the active selection if there is one. Returns true if it deleted.
    fn delete_selection_if_any(&mut self, out: &mut EditOutcome) -> bool {
        let primary_has_sel = self.selection().is_some_and(|(lo, hi)| hi > lo);
        // vscode-user SEV-2 2026-07-10: an extra cursor added by
        // AddCursorAtNextWord (Ctrl+D) carries its own anchor pointing
        // at the start of its match — so the extra has its own
        // selection that ALSO needs deleting before the follow-on
        // insert. Old path only handled the primary; typing after
        // Ctrl+D N times left every non-primary selected word
        // untouched and inserted the new text at the wrong offset.
        let extras_have_sel = self
            .extra_cursors
            .iter()
            .zip(self.extra_anchors.iter())
            .any(|(&c, a)| a.is_some_and(|av| av != c));
        if !primary_has_sel && !extras_have_sel {
            self.anchor = None;
            return false;
        }
        self.remember_selection();
        self.checkpoint();
        if self.extra_cursors.is_empty() {
            let (lo, hi) = self.selection().expect("primary_has_sel implies Some");
            self.text.replace_range(lo..hi, "");
            self.cursor = lo;
            self.anchor = None;
            out.buffer_changed = true;
            return true;
        }
        // Multi-cursor: delete each cursor's OWN (anchor, cursor) range
        // via the existing per-cursor delete helper. Cursors without
        // their own selection get a no-op (p, p) range so they still
        // ride the shared shift logic and stay char-boundary-valid.
        // vscode-user SEV-1 (`is_char_boundary` panic) + SEV-2
        // (wrong-position insert) both close via this route.
        self.multi_delete_range_per_cursor(|ed, p| {
            let anchor = if p == ed.cursor {
                ed.anchor
            } else {
                ed.extra_cursors
                    .iter()
                    .position(|&c| c == p)
                    .and_then(|i| ed.extra_anchors.get(i).copied().flatten())
            };
            match anchor {
                Some(a) if a != p => (a.min(p), a.max(p)),
                _ => (p, p),
            }
        });
        self.anchor = None;
        for a in self.extra_anchors.iter_mut() {
            *a = None;
        }
        out.buffer_changed = true;
        true
    }

    // ─── motion internals ───────────────────────────────────────────
    fn move_horizontal(&mut self, dir: i32, _word: bool) {
        if dir < 0 {
            self.cursor = self.prev_char_boundary(self.cursor);
        } else {
            self.cursor = self.next_char_boundary(self.cursor);
        }
    }
    fn move_vertical(&mut self, dir: i32) {
        let line = self.current_line();
        let target = if dir < 0 {
            if line == 0 {
                return;
            }
            line - 1
        } else {
            if line + 1 >= self.line_count() {
                self.cursor = self.text.len();
                return;
            }
            line + 1
        };
        let gc = self.goal_col();
        self.cursor = self.byte_at_col(target, gc);
    }

    fn move_word_right(&mut self) {
        let len = self.text.len();
        if self.cursor >= len {
            return;
        }
        let mut i = self.cursor;
        // skip the current run (whatever class the char under the cursor is, if not space)
        if let Some(c) = self.char_at(i)
            && class_of(c) != CharClass::Space
        {
            let cls = class_of(c);
            while i < len {
                match self.char_at(i) {
                    Some(c) if class_of(c) == cls => i = self.next_char_boundary(i),
                    _ => break,
                }
            }
        }
        // skip whitespace
        while i < len {
            match self.char_at(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        self.cursor = i;
    }
    fn move_word_left(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let mut i = self.cursor;
        // step back over whitespace
        while i > 0 {
            match self.char_before(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        // step back over the run to its start
        if let Some(c) = self.char_before(i) {
            let cls = class_of(c);
            while i > 0 {
                match self.char_before(i) {
                    Some(c) if class_of(c) == cls => i = self.prev_char_boundary(i),
                    _ => break,
                }
            }
        }
        self.cursor = i;
    }
    fn move_word_end(&mut self) {
        let len = self.text.len();
        if self.cursor >= len {
            return;
        }
        let mut i = self.next_char_boundary(self.cursor);
        // skip whitespace
        while i < len {
            match self.char_at(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        // advance to the end of this run
        if let Some(c) = self.char_at(i) {
            let cls = class_of(c);
            while i < len {
                let nxt = self.next_char_boundary(i);
                match self.char_at(nxt) {
                    Some(c) if class_of(c) == cls => i = nxt,
                    _ => break,
                }
            }
        }
        self.cursor = i;
    }
    /// vim `ge` — end of the previous word. Two-phase: step back over the
    /// current word's run (so we're not still on it), then step back over
    /// whitespace, leaving the cursor on the last char of the prior word.
    fn move_word_end_back(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let mut i = self.prev_char_boundary(self.cursor);
        // step back over the current non-whitespace run
        let cur_class = self.char_at(i).map(class_of);
        if let Some(cls) = cur_class
            && cls != CharClass::Space
        {
            while i > 0 {
                match self.char_at(i) {
                    Some(c) if class_of(c) == cls => i = self.prev_char_boundary(i),
                    _ => break,
                }
            }
        }
        // step back over whitespace
        while i > 0 {
            match self.char_at(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        self.cursor = i;
    }
    /// vim `W` — start of next WORD (whitespace-delimited). Skips the current
    /// non-whitespace run, then any whitespace run, lands at the first char of
    /// the next non-whitespace run.
    fn move_big_word_right(&mut self) {
        let len = self.text.len();
        if self.cursor >= len {
            return;
        }
        let mut i = self.cursor;
        // skip current non-whitespace run
        while i < len {
            match self.char_at(i) {
                Some(c) if !c.is_whitespace() => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        // skip whitespace
        while i < len {
            match self.char_at(i) {
                Some(c) if c.is_whitespace() => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        self.cursor = i;
    }
    /// vim `B` — start of previous WORD (whitespace-delimited).
    fn move_big_word_left(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let mut i = self.cursor;
        // step back over whitespace
        while i > 0 {
            match self.char_before(i) {
                Some(c) if c.is_whitespace() => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        // step back to the start of the current non-whitespace run
        while i > 0 {
            match self.char_before(i) {
                Some(c) if !c.is_whitespace() => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        self.cursor = i;
    }
    /// vim `E` — end of current/next WORD (whitespace-delimited). Walks forward
    /// past any whitespace, then to the last char of the non-whitespace run.
    fn move_big_word_end(&mut self) {
        let len = self.text.len();
        if self.cursor >= len {
            return;
        }
        let mut i = self.next_char_boundary(self.cursor);
        // skip whitespace
        while i < len {
            match self.char_at(i) {
                Some(c) if c.is_whitespace() => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        // walk until the cell *after* i is whitespace or EOF
        while i < len {
            let nxt = self.next_char_boundary(i);
            match self.char_at(nxt) {
                Some(c) if !c.is_whitespace() => i = nxt,
                _ => break,
            }
        }
        self.cursor = i;
    }
    /// vim `gE` — end of previous WORD (whitespace-delimited). Two-phase:
    /// step back over the current non-whitespace run, then over whitespace,
    /// landing on the last char of the prior WORD.
    fn move_big_word_end_back(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let mut i = self.prev_char_boundary(self.cursor);
        // step back over the current non-whitespace run (we're inside or at
        // the end of the current WORD)
        while i > 0 {
            match self.char_at(i) {
                Some(c) if !c.is_whitespace() => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        // step back over whitespace
        while i > 0 {
            match self.char_at(i) {
                Some(c) if c.is_whitespace() => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        self.cursor = i;
    }
    fn word_left_target(&self) -> usize {
        self.word_left_target_from(self.cursor)
    }
    /// `word_left_target` parameterized on a starting byte offset — used by
    /// multi-cursor `DeleteWordLeft` to compute a target per cursor.
    fn word_left_target_from(&self, from: usize) -> usize {
        let mut i = from.min(self.text.len());
        while i > 0 {
            match self.char_before(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.prev_char_boundary(i),
                _ => break,
            }
        }
        if let Some(c) = self.char_before(i) {
            let cls = class_of(c);
            while i > 0 {
                match self.char_before(i) {
                    Some(c) if class_of(c) == cls => i = self.prev_char_boundary(i),
                    _ => break,
                }
            }
        }
        i
    }
    fn word_right_target(&self) -> usize {
        self.word_right_target_from(self.cursor)
    }
    /// `word_right_target` parameterized on a starting byte offset.
    fn word_right_target_from(&self, from: usize) -> usize {
        let len = self.text.len();
        let mut i = from.min(len);
        if let Some(c) = self.char_at(i)
            && class_of(c) != CharClass::Space
        {
            let cls = class_of(c);
            while i < len {
                match self.char_at(i) {
                    Some(c) if class_of(c) == cls => i = self.next_char_boundary(i),
                    _ => break,
                }
            }
        }
        while i < len {
            match self.char_at(i) {
                Some(c) if class_of(c) == CharClass::Space => i = self.next_char_boundary(i),
                _ => break,
            }
        }
        i
    }
    fn word_bounds_at(&self, byte: usize) -> (usize, usize) {
        let cls = self
            .char_at(byte)
            .or_else(|| self.char_before(byte))
            .map(class_of)
            .unwrap_or(CharClass::Space);
        let mut lo = byte;
        while lo > 0 {
            match self.char_before(lo) {
                Some(c) if class_of(c) == cls => lo = self.prev_char_boundary(lo),
                _ => break,
            }
        }
        let mut hi = byte;
        while hi < self.text.len() {
            match self.char_at(hi) {
                Some(c) if class_of(c) == cls => hi = self.next_char_boundary(hi),
                _ => break,
            }
        }
        (lo, hi)
    }

    /// Vim WORD (big-word) bounds: whitespace is the only boundary.
    /// Cursor on any non-whitespace char returns the maximal run of
    /// non-whitespace surrounding it; cursor on whitespace returns
    /// the whitespace run. Used by `iW`/`aW` text objects.
    /// nvchad-round-7 SEV-2 2026-07-11.
    fn big_word_bounds_at(&self, byte: usize) -> (usize, usize) {
        let is_ws = |c: char| c.is_whitespace();
        let center = self
            .char_at(byte)
            .or_else(|| self.char_before(byte))
            .map(is_ws)
            .unwrap_or(true);
        let mut lo = byte;
        while lo > 0 {
            match self.char_before(lo) {
                Some(c) if is_ws(c) == center => lo = self.prev_char_boundary(lo),
                _ => break,
            }
        }
        let mut hi = byte;
        while hi < self.text.len() {
            match self.char_at(hi) {
                Some(c) if is_ws(c) == center => hi = self.next_char_boundary(hi),
                _ => break,
            }
        }
        (lo, hi)
    }

    /// Byte range of the paragraph the cursor sits in. A "paragraph" is a
    /// maximal run of non-blank lines (blank = empty or whitespace-only).
    /// When `around` is true, the range also includes the trailing blank
    /// lines that immediately follow the paragraph (vim's `ap` semantic).
    /// If the cursor is on a blank line, returns the range of that blank
    /// run instead (graceful no-op for the operator).
    /// Public alias for `paragraph_bounds` so the App layer can use
    /// it (currently: `begin_filter_paragraph_from_cursor` for `!ip`
    /// / `!ap`). nvchad-round-10 SEV-3 2026-07-12.
    pub fn paragraph_bounds_public(&self, around: bool) -> (usize, usize) {
        self.paragraph_bounds(around)
    }

    fn paragraph_bounds(&self, around: bool) -> (usize, usize) {
        let n = self.line_count();
        let cur_line = self.current_line();
        let is_blank = |l: usize| self.line_str(l).trim().is_empty();
        // Walk up to the first blank line above (or buffer start).
        let mut start_line = cur_line;
        if is_blank(start_line) {
            // Cursor on a blank line — select the blank run.
            while start_line > 0 && is_blank(start_line - 1) {
                start_line -= 1;
            }
            let mut end_line = cur_line;
            while end_line + 1 < n && is_blank(end_line + 1) {
                end_line += 1;
            }
            return (self.line_start(start_line), self.line_end(end_line));
        }
        while start_line > 0 && !is_blank(start_line - 1) {
            start_line -= 1;
        }
        let mut end_line = cur_line;
        while end_line + 1 < n && !is_blank(end_line + 1) {
            end_line += 1;
        }
        if around {
            // Pull in trailing blank lines.
            while end_line + 1 < n && is_blank(end_line + 1) {
                end_line += 1;
            }
        }
        (self.line_start(start_line), self.line_end(end_line))
    }

    /// vim-indent-object — the contiguous run of lines whose indent is
    /// ≥ the cursor line's. Blank lines inside the run don't break it
    /// but are trimmed off the edges. `include_above` swallows the
    /// nearest less-indented header line above (the `def:` / `if:` /
    /// `key:`); `include_below` swallows the first non-blank line below
    /// the block (the closing-context line). Returns a `(line_start,
    /// line_end)` byte range; `None` for an all-blank buffer.
    fn indent_block_bounds(
        &self,
        include_above: bool,
        include_below: bool,
    ) -> Option<(usize, usize)> {
        let n = self.line_count();
        if n == 0 {
            return None;
        }
        let cur = self.current_line();
        let is_blank = |l: usize| self.line_str(l).trim().is_empty();
        let indent_of = |l: usize| line_indent(&self.text, self.line_start(l));
        // Reference indent: the cursor line's, or — when the cursor is
        // on a blank line — the nearest non-blank neighbour's.
        let ref_indent = if !is_blank(cur) {
            indent_of(cur)
        } else {
            {
                let l = (cur + 1..n)
                    .find(|&l| !is_blank(l))
                    .or_else(|| (0..cur).rev().find(|&l| !is_blank(l)))?;
                indent_of(l)
            }
        };
        let belongs = |l: usize| is_blank(l) || indent_of(l) >= ref_indent;
        let mut start = cur;
        while start > 0 && belongs(start - 1) {
            start -= 1;
        }
        let mut end = cur;
        while end + 1 < n && belongs(end + 1) {
            end += 1;
        }
        // Trim blank lines off both edges.
        while start < end && is_blank(start) {
            start += 1;
        }
        while end > start && is_blank(end) {
            end -= 1;
        }
        if is_blank(start) {
            return None;
        }
        if include_above
            && let Some(hdr) = (0..start).rev().find(|&l| !is_blank(l))
            && indent_of(hdr) < ref_indent
        {
            start = hdr;
        }
        if include_below && let Some(foot) = (end + 1..n).find(|&l| !is_blank(l)) {
            end = foot;
        }
        Some((self.line_start(start), self.line_end(end)))
    }

    /// Find the smallest bracket pair surrounding the cursor. `open` /
    /// `close` are the matching delimiter chars (e.g. `(` and `)`).
    /// Returns `(open_byte, close_byte)` (pointing at the bracket chars
    /// themselves), or `None` when the cursor isn't inside a pair.
    /// Walks the buffer with a depth counter so nested pairs are handled.
    /// Capped at 50k chars per side so a malformed file doesn't hang.
    pub fn enclosing_bracket_pair(&self, open: char, close: char) -> Option<(usize, usize)> {
        const BUDGET: usize = 50_000;
        // Walk backward to find the unmatched open.
        let mut depth: usize = 0;
        let mut i = self.cursor;
        let mut steps = 0;
        let open_byte = loop {
            if i == 0 {
                return None;
            }
            i = self.prev_char_boundary(i);
            let ch = self.text[i..].chars().next()?;
            if ch == close {
                depth += 1;
            } else if ch == open {
                if depth == 0 {
                    break i;
                }
                depth -= 1;
            }
            steps += 1;
            if steps > BUDGET {
                return None;
            }
        };
        // Walk forward to find the matching close.
        let mut depth: usize = 0;
        let mut j = self.cursor;
        let mut steps = 0;
        let close_byte = loop {
            if j >= self.text.len() {
                return None;
            }
            let ch = self.text[j..].chars().next()?;
            if ch == open {
                depth += 1;
            } else if ch == close {
                if depth == 0 {
                    break j;
                }
                depth -= 1;
            }
            j += ch.len_utf8();
            steps += 1;
            if steps > BUDGET {
                return None;
            }
        };
        Some((open_byte, close_byte))
    }

    /// Find the innermost enclosing function (`if` / `af`) or
    /// class-like (`ic` / `ac`) text object using `regex_outline` for
    /// the header lines and brace matching for the body.
    ///
    /// `header_kinds` filters which symbol kinds (`"fn"`, `"struct"`,
    /// etc) count as a candidate header. Returns the buffer-byte range
    /// (`start`, `end`) where:
    /// - `inner=true`: cursor lands just inside the braces (header
    ///   excluded, opening / closing `{}` excluded).
    /// - `inner=false`: cursor includes the whole header line through
    ///   one past the closing `}`.
    ///
    /// Indent-scoped languages (Python, Ruby, CoffeeScript, YAML)
    /// aren't supported here (returns None) — for the MVP we only
    /// handle braced bodies.
    /// Indent-scoped enclosing-scope range — for languages without
    /// brace-bounded bodies (Python, Ruby, CoffeeScript, YAML). The
    /// body is the run of
    /// lines whose indent strictly exceeds the header's; the scope
    /// closes at the first non-blank line whose indent ≤ the header's.
    /// For Ruby, the closing `end` line is included in `around` mode
    /// (vim-ish convention — `ad` matches `def…end`); Python has no
    /// `end` to include.
    ///
    /// `inner` ⇒ the body lines only (header excluded, closing `end`
    /// excluded). `around` ⇒ header through closing `end` (Ruby) or
    /// through the last body line (Python).
    pub fn enclosing_indent_scope(
        &self,
        ext: &str,
        header_kinds: &[&str],
        inner: bool,
    ) -> Option<(usize, usize)> {
        let text = self.text.as_str();
        let symbols = crate::regex_outline::extract_symbols(text, ext);
        if symbols.is_empty() {
            return None;
        }
        let (cur_row, _) = self.row_col();
        let total_lines = self.line_count();
        for s in symbols.iter().rev() {
            if s.line as usize > cur_row {
                continue;
            }
            if !header_kinds.contains(&s.kind) {
                continue;
            }
            let header_line_start = self.line_start(s.line as usize);
            let header_indent = line_indent(text, header_line_start);
            // Walk forward to find the first non-blank line whose
            // indent ≤ header_indent — that's the scope boundary.
            let mut body_end_excl = self.text.len();
            let mut closing_end_line: Option<usize> = None;
            let mut line_no = s.line as usize + 1;
            while line_no < total_lines {
                let ls = self.line_start(line_no);
                let (lo, hi) = self.line_byte_range(line_no);
                let line = &text[lo..hi];
                if line.trim().is_empty() {
                    line_no += 1;
                    continue;
                }
                let indent = line_indent(text, ls);
                if indent <= header_indent {
                    if ext == "rb" && line.trim_start().starts_with("end") {
                        closing_end_line = Some(line_no);
                    }
                    body_end_excl = ls;
                    break;
                }
                line_no += 1;
            }
            // Cursor must be inside the scope (header through end of
            // body) to count.
            let max_inclusive = match closing_end_line {
                Some(l) => self.line_byte_range(l).1,
                None => body_end_excl,
            };
            if self.cursor < header_line_start || self.cursor > max_inclusive {
                continue;
            }
            return Some(if inner {
                // Body = lines after the header up to (but not including)
                // the closing line.
                let body_start = if (s.line as usize) + 1 >= total_lines {
                    self.text.len()
                } else {
                    self.line_start((s.line as usize) + 1)
                };
                (body_start, body_end_excl)
            } else {
                // Around = header through closing `end` (Ruby) or through
                // last body line (Python).
                let end_byte = match closing_end_line {
                    Some(l) => self.line_byte_range(l).1,
                    None => body_end_excl,
                };
                (header_line_start, end_byte)
            });
        }
        None
    }

    pub fn enclosing_function_range(
        &self,
        ext: &str,
        header_kinds: &[&str],
        inner: bool,
    ) -> Option<(usize, usize)> {
        let text = self.text.as_str();
        let symbols = crate::regex_outline::extract_symbols(text, ext);
        if symbols.is_empty() {
            return None;
        }
        let (cur_row, _) = self.row_col();
        // Walk symbols in reverse — the innermost (highest line, still
        // ≤ cursor) wins first.
        for s in symbols.iter().rev() {
            if s.line as usize > cur_row {
                continue;
            }
            if !header_kinds.contains(&s.kind) {
                continue;
            }
            // From the header's line start, find the next `{` (or
            // `(` for Go/Rust func sigs with multi-line params — we
            // still want the body, so prefer `{`).
            let header_line_start = self.line_start(s.line as usize);
            let header_line_end_eof = self.text.len();
            let after_header = &text[header_line_start..header_line_end_eof];
            // Walk forward to the first `{` outside of strings/comments
            // (we keep this simple — bare `{` scan).
            let Some(rel_brace) = after_header.find('{') else {
                continue;
            };
            let open_byte = header_line_start + rel_brace;
            // Brace-match forward from `open_byte` (depth-counted).
            let close_byte = match_close_after(text, open_byte)?;
            // Only this scope counts if the cursor actually sits inside
            // it (or on its header line, which counts as `around`).
            if self.cursor < header_line_start || self.cursor > close_byte {
                continue;
            }
            return Some(if inner {
                let start = self.next_char_boundary(open_byte);
                (start, close_byte)
            } else {
                let end = self.next_char_boundary(close_byte);
                (header_line_start, end)
            });
        }
        None
    }

    /// Argument text object (`ia` / `aa`). Walks back to the innermost
    /// enclosing `(`, walks forward to its matching `)`, then splits
    /// the contents on top-level commas (depth-balanced over
    /// parens / brackets / braces; respects single-line `'…'` / `"…"`
    /// strings). Picks the arg slice the cursor sits inside.
    /// `inner` ⇒ just the slice; `around` ⇒ extends to include the
    /// trailing comma + leading whitespace (or the leading comma if at
    /// the last arg).
    pub fn enclosing_argument_range(&self, inner: bool) -> Option<(usize, usize)> {
        let (open, close) = self.enclosing_bracket_pair('(', ')')?;
        // Content range — one past the open `(` to (but not including)
        // the `)`.
        let body_start = self.next_char_boundary(open);
        let body_end = close;
        let text = self.text.as_str();
        // Split into argument byte-ranges (start, end) at top-level commas.
        let mut args: Vec<(usize, usize)> = Vec::new();
        let mut depth: i32 = 0;
        let mut in_str: Option<u8> = None;
        let mut arg_start = body_start;
        let bytes = text.as_bytes();
        let mut i = body_start;
        while i < body_end {
            let b = bytes[i];
            if let Some(q) = in_str {
                if b == q && (i == 0 || bytes[i - 1] != b'\\') {
                    in_str = None;
                }
            } else {
                match b {
                    b'"' | b'\'' | b'`' => in_str = Some(b),
                    b'(' | b'[' | b'{' => depth += 1,
                    b')' | b']' | b'}' => depth -= 1,
                    b',' if depth == 0 => {
                        args.push((arg_start, i));
                        arg_start = i + 1;
                    }
                    _ => {}
                }
            }
            i += 1;
        }
        args.push((arg_start, body_end));
        // Pick the arg the cursor sits inside (cursor between the
        // start/end of an arg, inclusive on each side).
        let cur = self.cursor;
        let mut chosen: Option<usize> = None;
        for (i, &(s, e)) in args.iter().enumerate() {
            if cur >= s && cur <= e {
                chosen = Some(i);
                break;
            }
        }
        let idx = chosen?;
        let (s, e) = args[idx];
        // Trim leading whitespace for the inner variant (the comma
        // and any whitespace belong to "around").
        let mut s_trim = s;
        while s_trim < e && matches!(bytes[s_trim], b' ' | b'\t' | b'\n') {
            s_trim += 1;
        }
        let mut e_trim = e;
        while e_trim > s_trim && matches!(bytes[e_trim - 1], b' ' | b'\t' | b'\n') {
            e_trim -= 1;
        }
        if inner {
            return Some((s_trim, e_trim));
        }
        // `around` — extend to swallow the adjacent comma + adjacent
        // whitespace. Prefer the trailing comma when the arg isn't last
        // (vim's `aa` convention).
        let mut around_end = e;
        if idx + 1 < args.len() && around_end < body_end && bytes[around_end] == b',' {
            around_end += 1;
            while around_end < body_end && matches!(bytes[around_end], b' ' | b'\t') {
                around_end += 1;
            }
            return Some((s_trim, around_end));
        }
        // Last arg ⇒ pull the preceding comma + whitespace.
        let mut around_start = s_trim;
        while around_start > body_start && matches!(bytes[around_start - 1], b' ' | b'\t') {
            around_start -= 1;
        }
        if around_start > body_start && bytes[around_start - 1] == b',' {
            around_start -= 1;
        }
        Some((around_start, e_trim))
    }

    /// Find the surrounding pair of `q` characters on the cursor's line.
    /// Returns `(open_byte, close_byte)` (both pointing at the quote chars),
    /// or `None` when there isn't a matching pair flanking the cursor. Used
    /// by the `i"` / `a"` family of text objects — restricted to a single
    /// line so a multi-line string elsewhere in the buffer can't fool the
    /// scan. Treats backslash-escaped quotes as literal.
    fn enclosing_quote_pair_on_line(&self, q: char) -> Option<(usize, usize)> {
        let line = self.current_line();
        let ls = self.line_start(line);
        let le = self.line_end(line);
        let line_text = &self.text[ls..le];
        // Find every unescaped occurrence of `q` on this line.
        let mut quotes: Vec<usize> = Vec::new();
        let bytes = line_text.as_bytes();
        let qb = q as u8;
        let mut i = 0;
        while i < line_text.len() {
            if bytes[i] == qb {
                let escaped = i > 0 && bytes[i - 1] == b'\\';
                if !escaped {
                    quotes.push(ls + i);
                }
            }
            i += 1;
        }
        if quotes.len() < 2 {
            return None;
        }
        // Pair up consecutively: (quotes[0], quotes[1]), (quotes[2], quotes[3]), …
        // Then find the pair whose range contains the cursor (or the cursor
        // exactly on a quote — vim picks the pair you're on).
        let cur = self.cursor;
        for pair in quotes.as_chunks::<2>().0 {
            let (a, b) = (pair[0], pair[1]);
            if cur >= a && cur <= b {
                return Some((a, b));
            }
        }
        None
    }

    /// Run `f(self, byte_of_line_start)` for each line touched by the selection
    /// (or just the current line if there's no selection). `f` returns the byte
    /// delta it applied at that line so subsequent line starts shift correctly.
    /// Returns true if anything changed. The cursor is left at its old column on
    /// the same logical line.
    fn for_each_selected_line(&mut self, mut f: impl FnMut(&mut Self, usize) -> isize) -> bool {
        let (cur_line, cur_col) = self.row_col();
        // Build the set of lines to operate on:
        //   - Selection (if any) spans first..=last
        //   - Otherwise the primary cursor's line
        //   - Plus each extra cursor's row (multi-cursor fan-out)
        let mut lines: Vec<usize> = match self.selection() {
            Some((lo, hi)) => {
                let fl = self.text[..lo].bytes().filter(|&b| b == b'\n').count();
                let hi_line = self.text[..hi].bytes().filter(|&b| b == b'\n').count();
                let ll = if hi > lo && hi == self.line_start(hi_line) && hi_line > fl {
                    hi_line - 1
                } else {
                    hi_line
                };
                (fl..=ll).collect()
            }
            None => vec![cur_line],
        };
        for &b in &self.extra_cursors {
            lines.push(self.row_col_at(b).0);
        }
        lines.sort_unstable();
        lines.dedup();
        let mut changed = false;
        for line in lines {
            let bol = self.line_start(line);
            let delta = f(&mut *self, bol);
            if delta != 0 {
                changed = true;
            }
        }
        // restore primary cursor to (cur_line, cur_col), clamped
        self.cursor = self.byte_at_col(cur_line.min(self.line_count().saturating_sub(1)), cur_col);
        self.anchor = None;
        changed
    }

    fn swap_lines(&mut self, a: usize, b: usize) {
        debug_assert!(a < b);
        let a_start = self.line_start(a);
        let a_end = self.line_end(a);
        let b_start = self.line_start(b);
        let b_end = self.line_end(b);
        let a_text = self.text[a_start..a_end].to_string();
        let b_text = self.text[b_start..b_end].to_string();
        // replace b first (later in the string) so a's offsets stay valid
        self.text.replace_range(b_start..b_end, &a_text);
        self.text.replace_range(a_start..a_end, &b_text);
    }
}

// ─── tests ──────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
    use super::*;
    use crate::edit_op::EditOp::*;

    fn ed(s: &str) -> (Editor, Clipboard) {
        (Editor::new(s, 4), Clipboard::detached())
    }
    fn run(e: &mut Editor, c: &mut Clipboard, ops: &[EditOp]) {
        for op in ops {
            e.apply(op.clone(), 10, c);
        }
    }

    /// nvchad-user SEV-2 2026-07-10 — dit/dat HTML tag text objects.
    #[test]
    fn tag_text_object_selects_inner_and_around() {
        // Simple pair: `<div>hello</div>`. Cursor inside "hello".
        let (mut e, mut c) = ed("<div>hello</div>");
        e.cursor = 7; // in "hello"
        e.apply(EditOp::SelectInnerTag, 10, &mut c);
        assert_eq!(e.selected_text(), "hello");

        let (mut e, mut c) = ed("<div>hello</div>");
        e.cursor = 7;
        e.apply(EditOp::SelectAroundTag, 10, &mut c);
        assert_eq!(e.selected_text(), "<div>hello</div>");

        // Nested: cursor in inner-most.
        let (mut e, mut c) = ed("<a><b>nested</b></a>");
        e.cursor = 8; // in "nested"
        e.apply(EditOp::SelectInnerTag, 10, &mut c);
        assert_eq!(e.selected_text(), "nested");

        // Self-closing is skipped: cursor after `<br/>` should walk
        // out to the outer tag pair.
        let (mut e, mut c) = ed("<p>line<br/>more</p>");
        e.cursor = 12; // in "more"
        e.apply(EditOp::SelectInnerTag, 10, &mut c);
        assert_eq!(e.selected_text(), "line<br/>more");

        // No enclosing tag: no-op.
        let (mut e, mut c) = ed("just plain text");
        e.cursor = 5;
        e.apply(EditOp::SelectInnerTag, 10, &mut c);
        assert_eq!(e.selected_text(), "");
    }

    /// vscode-user SEV-2 2026-07-10 — paste-over-selection was split
    /// into two undo checkpoints (one for the delete inside
    /// `delete_selection_if_any`, one at the top of the `Paste` arm),
    /// so a single Ctrl+Z only rewound the insert half — leaving the
    /// buffer showing the empty post-delete state.
    #[test]
    fn paste_over_selection_undoes_atomically() {
        let (mut e, mut c) = ed("hello world");
        c.set("REPLACED", false);
        // Select "hello" (bytes 0..5).
        e.cursor = 0;
        e.anchor = Some(5);
        e.apply(EditOp::Paste, 10, &mut c);
        assert_eq!(e.text(), "REPLACED world");
        // ONE undo restores everything.
        e.apply(EditOp::Undo, 10, &mut c);
        assert_eq!(e.text(), "hello world");
    }

    /// vscode-user SEV-2 2026-07-10 — Ctrl+D on `foo bar foo` selects
    /// `foo`, second Ctrl+D adds an extra at the second `foo` with
    /// its own anchor+cursor selection. Typing `X` should delete both
    /// selections and insert `X` at both positions.
    #[test]
    fn ctrl_d_add_cursor_to_next_word_typing_replaces_both_matches() {
        let (mut e, mut c) = ed("foo bar foo baz");
        // Cursor inside first "foo".
        e.cursor = 1;
        e.apply(EditOp::AddCursorAtNextWord, 10, &mut c); // selects "foo"
        assert_eq!(e.selected_text(), "foo");
        assert!(e.extra_cursors.is_empty());
        e.apply(EditOp::AddCursorAtNextWord, 10, &mut c); // adds extra at 2nd "foo"
        assert_eq!(e.extra_cursors.len(), 1);
        // Both cursors have their own selection.
        assert!(e.anchor.is_some());
        assert!(e.extra_anchors[0].is_some());
        e.apply(EditOp::InsertChar('X'), 10, &mut c);
        // Both "foo"s become "X" — the SEV-2 fix. Pre-fix: the extra's
        // selection was left in place ("foo") and the insert happened
        // at a stale offset, producing "X bar Xfoo baz" or similar.
        assert_eq!(e.text(), "X bar X baz");
    }

    /// vscode-user SEV-1 2026-07-10 — `is_char_boundary` panic in
    /// multi-cursor typing after a selection-delete on the primary
    /// cursor. `delete_selection_if_any` shrunk `self.text` but left
    /// `extra_cursors` at their pre-delete byte offsets; the next
    /// InsertChar's multi-cursor branch then called
    /// `insert_str(stale_offset, …)`, which either wrote to the wrong
    /// place (ASCII) or panicked mid-codepoint (UTF-8). This test
    /// covers both shapes: an ASCII buffer to verify positions, and a
    /// UTF-8 buffer to verify no panic.
    #[test]
    fn selection_delete_shifts_extra_cursors_before_multi_insert() {
        // ASCII: "abcdefgh". Primary selects "cd" (bytes 2..4), extra
        // cursor at 6 (between "f" and "g"). After delete_selection +
        // insert 'X', both cursors should insert 'X' at their now-valid
        // positions.
        let (mut e, mut c) = ed("abcdefgh");
        e.cursor = 2;
        e.anchor = Some(4); // selection [2..4] = "cd"
        e.extra_cursors = vec![6];
        e.extra_anchors = vec![None];
        e.apply(EditOp::InsertChar('X'), 10, &mut c);
        // After delete, text was "abefgh"; extra cursor 6 shifted to 4
        // (past the removed range). Multi-cursor insert wrote 'X' at
        // both 2 and 4 → "abXefXgh".
        assert_eq!(e.text(), "abXefXgh");

        // UTF-8: "aébécédé" — 8 chars, 12 bytes (each é = 2 bytes).
        // Byte layout: a(0) é(1-2) b(3) é(4-5) c(6) é(7-8) d(9) é(10-11).
        // Selection deletes the first é (bytes 1..3). Extra cursor at
        // byte 6 (start of 'c', a valid boundary). WITHOUT the shift
        // fix, byte 6 would remain at 6 after the delete, but the
        // buffer contracted by 2 bytes so byte 6 is now mid-'é'
        // (which is now at bytes 5-6). The next multi-cursor
        // insert would then hit `insert_str`'s `is_char_boundary`
        // assertion and panic. With the fix, extras shift 6→4
        // (past hi=3, shift by removed=2), which lands on the new
        // 'c' — still a valid boundary.
        let (mut e, mut c) = ed("aébécédé");
        e.cursor = 1;
        e.anchor = Some(3);
        e.extra_cursors = vec![6];
        e.extra_anchors = vec![None];
        e.apply(EditOp::InsertChar('X'), 10, &mut c); // must not panic
        // After delete: "abécédé" (10 bytes). Extra shifted 6→4 (valid
        // — 'c'). Primary at 1. Multi-insert (descending order): 'X' at
        // 4 (before 'c') then at 1 (before 'b') → "aXbéXcédé".
        assert_eq!(e.text(), "aXbéXcédé");
    }

    /// Regression for the 2026-06-07 bug-hunt SEV-3 finding:
    /// `wc -l` semantics. The trailing newline is the terminator
    /// for the last line, not an extra empty line.
    #[test]
    fn line_count_matches_wc_l() {
        // Empty.
        assert_eq!(ed("").0.line_count(), 1);
        // No trailing newline.
        assert_eq!(ed("a").0.line_count(), 1);
        assert_eq!(ed("a\nb").0.line_count(), 2);
        // Trailing newline — Unix-correct, line_count == wc -l.
        assert_eq!(ed("a\n").0.line_count(), 1);
        assert_eq!(ed("a\nb\n").0.line_count(), 2);
        assert_eq!(ed("a\nb\nc\n").0.line_count(), 3);
        // Multiple trailing newlines = empty trailing lines.
        assert_eq!(ed("a\n\n").0.line_count(), 2);
        assert_eq!(ed("a\n\n\n").0.line_count(), 3);
    }

    #[test]
    fn insert_and_undo_coalesce() {
        let (mut e, mut c) = ed("");
        run(
            &mut e,
            &mut c,
            &[InsertChar('a'), InsertChar('b'), InsertChar('c')],
        );
        assert_eq!(e.text(), "abc");
        e.apply(Undo, 10, &mut c);
        assert_eq!(e.text(), ""); // whole burst undone as one group
        e.apply(Redo, 10, &mut c);
        assert_eq!(e.text(), "abc");
    }

    #[test]
    fn motion_breaks_the_insert_run() {
        let (mut e, mut c) = ed("");
        run(&mut e, &mut c, &[InsertChar('a'), InsertChar('b')]);
        e.apply(MoveLeft, 10, &mut c);
        run(&mut e, &mut c, &[InsertChar('X')]);
        assert_eq!(e.text(), "aXb");
        e.apply(Undo, 10, &mut c);
        assert_eq!(e.text(), "ab");
        e.apply(Undo, 10, &mut c);
        assert_eq!(e.text(), "");
    }

    #[test]
    fn new_edit_clears_redo() {
        let (mut e, mut c) = ed("");
        run(&mut e, &mut c, &[InsertChar('a')]);
        e.apply(Undo, 10, &mut c);
        run(&mut e, &mut c, &[InsertChar('b')]);
        e.apply(Redo, 10, &mut c); // nothing to redo
        assert_eq!(e.text(), "b");
    }

    #[test]
    fn utf8_boundaries() {
        let (mut e, mut c) = ed("héllo");
        // move right twice → past 'h' and 'é'
        e.apply(MoveRight, 10, &mut c);
        e.apply(MoveRight, 10, &mut c);
        assert_eq!(e.cursor(), "".len());
        e.apply(Backspace, 10, &mut c);
        assert_eq!(e.text(), "hllo");
    }

    #[test]
    fn word_motions() {
        let (mut e, mut c) = ed("foo bar.baz qux");
        e.apply(MoveWordRight, 10, &mut c);
        assert_eq!(e.cursor(), "foo ".len()); // start of "bar"
        e.apply(MoveWordRight, 10, &mut c);
        assert_eq!(e.cursor(), "foo bar".len()); // start of "."
        e.apply(MoveWordRight, 10, &mut c);
        assert_eq!(e.cursor(), "foo bar.".len()); // start of "baz"
        e.apply(MoveWordLeft, 10, &mut c);
        assert_eq!(e.cursor(), "foo bar".len());
    }

    #[test]
    fn vertical_keeps_goal_col() {
        let (mut e, mut c) = ed("abcdef\nxy\nlongline");
        // go to col 5 on line 0
        for _ in 0..5 {
            e.apply(MoveRight, 10, &mut c);
        }
        assert_eq!(e.row_col(), (0, 5));
        e.apply(MoveDown, 10, &mut c); // line 1 only has 2 chars → clamp to col 2
        assert_eq!(e.row_col(), (1, 2));
        e.apply(MoveDown, 10, &mut c); // line 2 long enough → back to col 5
        assert_eq!(e.row_col(), (2, 5));
    }

    #[test]
    fn line_nav_and_to_line() {
        let (mut e, mut c) = ed("one\n  two\nthree");
        e.apply(MoveToLine(2), 10, &mut c);
        assert_eq!(e.row_col(), (1, 0));
        e.apply(MoveLineFirstNonWs, 10, &mut c);
        assert_eq!(e.row_col(), (1, 2));
        e.apply(MoveLineEnd, 10, &mut c);
        assert_eq!(e.row_col(), (1, 5));
        // Vim `G` — land on the START of the last line, not past EOF.
        // 2026-06-13 nvchad-user SEV-2 S2-05 behavior change.
        e.apply(MoveBufferEnd, 10, &mut c);
        assert_eq!(e.row_col(), (2, 0));
        e.apply(MoveBufferStart, 10, &mut c);
        assert_eq!(e.cursor(), 0);
    }

    #[test]
    fn block_selection_yank_and_delete() {
        // 4 lines of "abcdef" — yank the column 1..=2 rectangle on rows 0..=2
        let (mut e, mut c) = ed("abcdef\nghijkl\nmnopqr\nstuvwx");
        // Cursor at (0,1)
        e.apply(MoveRight, 10, &mut c); // → cursor at byte 1, row 0 col 1
        e.apply(BlockSelectStart, 10, &mut c);
        // Move down 2 (row 2) and right 1 (col 2)
        e.apply(MoveDown, 10, &mut c);
        e.apply(MoveDown, 10, &mut c);
        e.apply(MoveRight, 10, &mut c);
        let rect = e.block_selection().unwrap();
        assert_eq!(rect, (0, 1, 2, 2));
        // Yank — clipboard should hold "bc\nhi\nno" (rows 0..=2, cols 1..=2)
        e.apply(YankBlock, 10, &mut c);
        assert_eq!(c.text(), "bc\nhi\nno");
        assert!(e.block_selection().is_none()); // cleared after yank

        // Delete: re-establish at (0,1)..(2,2), delete the rectangle
        let (mut e, mut c) = ed("abcdef\nghijkl\nmnopqr\nstuvwx");
        e.apply(MoveRight, 10, &mut c);
        e.apply(BlockSelectStart, 10, &mut c);
        e.apply(MoveDown, 10, &mut c);
        e.apply(MoveDown, 10, &mut c);
        e.apply(MoveRight, 10, &mut c);
        e.apply(DeleteBlock, 10, &mut c);
        assert_eq!(e.text(), "adef\ngjkl\nmpqr\nstuvwx");
    }

    #[test]
    fn selection_and_replace() {
        let (mut e, mut c) = ed("hello world");
        e.apply(SelectStart, 10, &mut c);
        for _ in 0..5 {
            e.apply(MoveRight, 10, &mut c);
        }
        assert_eq!(e.selection(), Some((0, 5)));
        e.apply(ReplaceSelection("HI".to_string()), 10, &mut c);
        assert_eq!(e.text(), "HI world");
        e.apply(Undo, 10, &mut c);
        assert_eq!(e.text(), "hello world");
    }

    #[test]
    fn delete_selection_via_typing() {
        let (mut e, mut c) = ed("abcdef");
        e.apply(SelectStart, 10, &mut c);
        for _ in 0..3 {
            e.apply(MoveRight, 10, &mut c);
        }
        e.apply(InsertChar('Z'), 10, &mut c); // replaces "abc"
        assert_eq!(e.text(), "Zdef");
    }

    #[test]
    fn delete_line_middle_first_last() {
        let (mut e, mut c) = ed("a\nb\nc");
        e.apply(MoveToLine(2), 10, &mut c);
        e.apply(DeleteLine, 10, &mut c);
        assert_eq!(e.text(), "a\nc");
        // delete first
        e.apply(MoveBufferStart, 10, &mut c);
        e.apply(DeleteLine, 10, &mut c);
        assert_eq!(e.text(), "c");
        // delete last (== only)
        e.apply(DeleteLine, 10, &mut c);
        assert_eq!(e.text(), "");
    }

    #[test]
    fn yank_line_and_paste() {
        let (mut e, mut c) = ed("alpha\nbeta");
        e.apply(YankLine, 10, &mut c); // yanks "alpha\n" linewise
        e.apply(PasteAfter, 10, &mut c); // after line 0
        assert_eq!(e.text(), "alpha\nalpha\nbeta");
        e.apply(MoveBufferStart, 10, &mut c);
        e.apply(PasteBefore, 10, &mut c);
        assert_eq!(e.text(), "alpha\nalpha\nalpha\nbeta");
    }

    #[test]
    fn cut_copy_paste_charwise() {
        let (mut e, mut c) = ed("foobar");
        e.apply(SelectStart, 10, &mut c);
        for _ in 0..3 {
            e.apply(MoveRight, 10, &mut c);
        }
        e.apply(CutSelection, 10, &mut c); // cut "foo"
        assert_eq!(e.text(), "bar");
        // Move to end of last line via MoveLineEnd (was MoveBufferEnd,
        // but G now lands on start-of-last-line per vim convention —
        // 2026-06-13 S2-05 fix).
        e.apply(MoveLineEnd, 10, &mut c);
        e.apply(Paste, 10, &mut c);
        assert_eq!(e.text(), "barfoo");
    }

    #[test]
    fn repeat_op() {
        let (mut e, mut c) = ed("alpha beta gamma delta");
        e.apply(Repeat(3, Box::new(MoveWordRight)), 10, &mut c);
        assert_eq!(e.cursor(), "alpha beta gamma ".len());
    }

    #[test]
    fn indent_outdent_selection() {
        let (mut e, mut c) = ed("a\nb\nc");
        e.apply(SelectAll, 10, &mut c);
        e.apply(Indent, 10, &mut c);
        assert_eq!(e.text(), "    a\n    b\n    c");
        e.apply(SelectAll, 10, &mut c);
        e.apply(Outdent, 10, &mut c);
        assert_eq!(e.text(), "a\nb\nc");
    }

    #[test]
    fn toggle_line_comment() {
        let (mut e, mut c) = ed("foo();\nbar();");
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(e.text(), "// foo();\n// bar();");
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(e.text(), "foo();\nbar();");
    }

    #[test]
    fn toggle_line_comment_html_wraps_with_close_token() {
        // HTML uses `<!-- ... -->` — open + close tokens must round-trip.
        let (mut e, mut c) = ed("<div>foo</div>\n<span>bar</span>");
        e.set_comment_token("<!-- ");
        e.set_comment_token_close(" -->");
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(
            e.text(),
            "<!-- <div>foo</div> -->\n<!-- <span>bar</span> -->"
        );
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(e.text(), "<div>foo</div>\n<span>bar</span>");
    }

    #[test]
    fn toggle_line_comment_css_wraps_with_close_token() {
        // CSS uses `/* ... */`.
        let (mut e, mut c) = ed("body { color: red; }");
        e.set_comment_token("/* ");
        e.set_comment_token_close(" */");
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(e.text(), "/* body { color: red; } */");
        e.apply(SelectAll, 10, &mut c);
        e.apply(ToggleLineComment, 10, &mut c);
        assert_eq!(e.text(), "body { color: red; }");
    }

    #[test]
    fn move_line_up_down() {
        let (mut e, mut c) = ed("one\ntwo\nthree");
        e.apply(MoveToLine(2), 10, &mut c); // on "two"
        e.apply(MoveLineUp, 10, &mut c);
        assert_eq!(e.text(), "two\none\nthree");
        e.apply(MoveLineDown, 10, &mut c);
        assert_eq!(e.text(), "one\ntwo\nthree");
    }

    #[test]
    fn open_lines() {
        let (mut e, mut c) = ed("a\nb");
        e.apply(InsertNewlineBelow, 10, &mut c);
        assert_eq!(e.text(), "a\n\nb");
        assert_eq!(e.row_col(), (1, 0));
        e.apply(MoveBufferStart, 10, &mut c);
        e.apply(InsertNewlineAbove, 10, &mut c);
        assert_eq!(e.text(), "\na\n\nb");
        assert_eq!(e.row_col(), (0, 0));
    }

    #[test]
    fn auto_pair_inserts_close_and_keeps_cursor_between() {
        let (mut e, mut c) = ed("");
        e.auto_pair = true;
        e.apply(InsertChar('('), 10, &mut c);
        assert_eq!(e.text(), "()");
        assert_eq!(e.cursor(), 1);
    }

    #[test]
    fn auto_pair_skips_over_existing_close() {
        let (mut e, mut c) = ed("");
        e.auto_pair = true;
        e.apply(InsertChar('('), 10, &mut c); // → "()" with cursor at 1
        // Typing the close char while sitting on it: just step over.
        e.apply(InsertChar(')'), 10, &mut c);
        assert_eq!(e.text(), "()");
        assert_eq!(e.cursor(), 2);
    }

    #[test]
    fn auto_pair_skipped_when_next_char_is_word() {
        // Typing `(` right before a word — we'd be wrapping live code, so don't.
        let (mut e, mut c) = ed("name");
        e.auto_pair = true;
        e.apply(InsertChar('('), 10, &mut c);
        assert_eq!(e.text(), "(name");
        assert_eq!(e.cursor(), 1);
    }

    #[test]
    fn duplicate_line_inserts_copy_below() {
        let (mut e, mut c) = ed("foo\nbar");
        e.apply(MoveBufferStart, 10, &mut c);
        e.apply(DuplicateLine, 10, &mut c);
        assert_eq!(e.text(), "foo\nfoo\nbar");
        // Cursor moved to the duplicate (same col on the new line).
        assert_eq!(e.row_col().0, 1);
    }

    #[test]
    fn duplicate_last_line_no_trailing_newline() {
        let (mut e, mut c) = ed("only");
        e.apply(DuplicateLine, 10, &mut c);
        assert_eq!(e.text(), "only\nonly");
    }

    #[test]
    fn join_lines_inserts_single_space_eating_indent() {
        let (mut e, mut c) = ed("foo \n   bar");
        e.cursor = 0;
        e.apply(JoinLines { keep_space: true }, 10, &mut c);
        // Trailing ws on first line + leading ws on second eaten; one space.
        assert_eq!(e.text(), "foo bar");
        // Cursor lands at the join boundary (where the inserted space is).
        assert_eq!(e.cursor(), 3);
    }

    #[test]
    fn join_lines_no_separator_for_empty_first_line() {
        let (mut e, mut c) = ed("\nbar");
        e.cursor = 0;
        e.apply(JoinLines { keep_space: true }, 10, &mut c);
        // Empty first line → no separator inserted.
        assert_eq!(e.text(), "bar");
        assert_eq!(e.cursor(), 0);
    }

    #[test]
    fn join_lines_noop_on_last_line() {
        let (mut e, mut c) = ed("only");
        e.apply(JoinLines { keep_space: true }, 10, &mut c);
        assert_eq!(e.text(), "only");
    }

    #[test]
    fn join_lines_count_chains_two_joins() {
        let (mut e, mut c) = ed("a\nb\nc");
        e.cursor = 0;
        // 3J ⇒ 2 join ops; should pull both lines up.
        e.apply(JoinLines { keep_space: true }, 10, &mut c);
        e.apply(JoinLines { keep_space: true }, 10, &mut c);
        assert_eq!(e.text(), "a b c");
    }

    #[test]
    fn join_lines_no_space_preserves_whitespace() {
        // vim `gJ` — concatenates the lines verbatim, keeping any
        // trailing/leading whitespace.
        let (mut e, mut c) = ed("foo \n   bar");
        e.cursor = 0;
        e.apply(JoinLines { keep_space: false }, 10, &mut c);
        assert_eq!(e.text(), "foo    bar");
    }

    #[test]
    fn case_transform_lowercases_selection() {
        let (mut e, mut c) = ed("HELLO World");
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(
            TransformSelectionCase(crate::edit_op::CaseTransform::Lower),
            10,
            &mut c,
        );
        assert_eq!(e.text(), "hello world");
    }

    #[test]
    fn case_transform_uppercases_selection() {
        let (mut e, mut c) = ed("Hello World");
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(
            TransformSelectionCase(crate::edit_op::CaseTransform::Upper),
            10,
            &mut c,
        );
        assert_eq!(e.text(), "HELLO WORLD");
    }

    #[test]
    fn case_transform_toggle_swaps_each_letter() {
        let (mut e, mut c) = ed("Hello, World!");
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(
            TransformSelectionCase(crate::edit_op::CaseTransform::Toggle),
            10,
            &mut c,
        );
        // Punctuation untouched; each ASCII letter swapped.
        assert_eq!(e.text(), "hELLO, wORLD!");
    }

    #[test]
    fn inner_function_selects_braced_body() {
        let src = "fn outer() {\n    let x = 1;\n    let y = 2;\n}\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("rs".into());
        // Place cursor inside the body (after the `\n` at end of line 1).
        e.cursor = src.find("let x").unwrap();
        e.apply(SelectInnerFunction, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("let x = 1;"));
        assert!(body.contains("let y = 2;"));
        assert!(!body.contains("fn outer"));
        assert!(!body.contains('}'));
    }

    #[test]
    fn around_function_selects_header_and_braces() {
        let src = "fn outer() {\n    let x = 1;\n}\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("rs".into());
        e.cursor = src.find("let x").unwrap();
        e.apply(SelectAroundFunction, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let around = &e.text()[sel.0..sel.1];
        assert!(around.starts_with("fn outer()"));
        assert!(around.contains('}'));
    }

    #[test]
    fn inner_function_python_indent_scoped() {
        let src = "def outer():\n    a = 1\n    b = 2\n\nother = 0\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("py".into());
        e.cursor = src.find("a = 1").unwrap();
        e.apply(SelectInnerFunction, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("a = 1"), "body: {body:?}");
        assert!(body.contains("b = 2"));
        assert!(!body.contains("def outer"));
        assert!(!body.contains("other = 0"));
    }

    #[test]
    fn around_function_ruby_includes_end() {
        let src = "def hello\n  puts 'hi'\n  puts 'bye'\nend\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("rb".into());
        e.cursor = src.find("puts 'hi'").unwrap();
        e.apply(SelectAroundFunction, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let around = &e.text()[sel.0..sel.1];
        assert!(around.starts_with("def hello"), "around: {around:?}");
        assert!(around.trim_end().ends_with("end"));
    }

    #[test]
    fn inner_class_python_indent_scoped() {
        let src = "class Foo:\n    def a(self):\n        pass\n    def b(self):\n        pass\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("py".into());
        e.cursor = src.find("def a").unwrap();
        e.apply(SelectInnerClass, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("def a(self)"));
        assert!(body.contains("def b(self)"));
        assert!(!body.contains("class Foo"));
    }

    #[test]
    fn around_function_coffeescript_indent_scoped() {
        let src = "greet = (name) ->\n  console.log name\n  return\n\nx = 0\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("coffee".into());
        e.cursor = src.find("console.log").unwrap();
        e.apply(SelectAroundFunction, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let around = &e.text()[sel.0..sel.1];
        assert!(
            around.starts_with("greet = (name) ->"),
            "around: {around:?}"
        );
        assert!(around.contains("console.log name"));
        assert!(!around.contains("x = 0"));
    }

    #[test]
    fn inner_class_coffeescript_indent_scoped() {
        let src = "class Animal\n  speak: ->\n    'noise'\n  move: ->\n    'walk'\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("coffee".into());
        e.cursor = src.find("speak").unwrap();
        e.apply(SelectInnerClass, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("speak: ->"));
        assert!(body.contains("move: ->"));
        assert!(!body.contains("class Animal"));
    }

    #[test]
    fn inner_class_yaml_block_indent_scoped() {
        // YAML block-heading keys are emitted as `namespace` symbols, so
        // `ic` selects the nested block under the cursor's key.
        let src = "server:\n  host: localhost\n  port: 8080\ndatabase:\n  name: app\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("yaml".into());
        e.cursor = src.find("host: localhost").unwrap();
        e.apply(SelectInnerClass, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("host: localhost"), "body: {body:?}");
        assert!(body.contains("port: 8080"));
        assert!(!body.contains("server:"));
        assert!(!body.contains("database:"));
    }

    #[test]
    fn inner_indent_block_selects_the_indented_run() {
        // Language-agnostic — no language_ext set.
        let src = "header:\n  a: 1\n  b: 2\nother: 3\n";
        let (mut e, mut c) = ed(src);
        e.cursor = src.find("a: 1").unwrap();
        e.apply(SelectInnerIndentBlock, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("a: 1"), "body: {body:?}");
        assert!(body.contains("b: 2"));
        assert!(!body.contains("header:"));
        assert!(!body.contains("other: 3"));
    }

    #[test]
    fn around_indent_block_includes_header_line() {
        let src = "header:\n  a: 1\n  b: 2\nother: 3\n";
        let (mut e, mut c) = ed(src);
        e.cursor = src.find("b: 2").unwrap();
        e.apply(SelectAroundIndentBlock, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.starts_with("header:"), "body: {body:?}");
        assert!(body.contains("a: 1"));
        assert!(!body.contains("other: 3"));
    }

    #[test]
    fn inner_indent_block_spans_internal_blank_lines() {
        let src = "head:\n  a: 1\n\n  b: 2\ntail: 3\n";
        let (mut e, mut c) = ed(src);
        e.cursor = src.find("a: 1").unwrap();
        e.apply(SelectInnerIndentBlock, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("a: 1"), "body: {body:?}");
        assert!(body.contains("b: 2"));
        assert!(!body.contains("tail"));
    }

    #[test]
    fn outer_indent_block_includes_header_and_line_below() {
        let src = "header:\n  a: 1\n  b: 2\nfooter: 3\nmore: 4\n";
        let (mut e, mut c) = ed(src);
        e.cursor = src.find("a: 1").unwrap();
        e.apply(SelectOuterIndentBlock, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.starts_with("header:"), "body: {body:?}");
        assert!(body.contains("b: 2"));
        assert!(body.contains("footer: 3")); // the line below
        assert!(!body.contains("more: 4")); // only one line below
    }

    #[test]
    fn inner_class_selects_struct_body() {
        let src = "pub struct Foo {\n    a: i32,\n    b: i32,\n}\n";
        let (mut e, mut c) = ed(src);
        e.language_ext = Some("rs".into());
        e.cursor = src.find("a: i32").unwrap();
        e.apply(SelectInnerClass, 10, &mut c);
        let sel = e.selection().expect("selection set");
        let body = &e.text()[sel.0..sel.1];
        assert!(body.contains("a: i32"));
        assert!(body.contains("b: i32"));
        assert!(!body.contains("pub struct"));
    }

    #[test]
    fn inner_argument_selects_one_arg() {
        // cursor on the `b` in `bar`
        let src = "call(foo, bar, baz)";
        let (mut e, mut c) = ed(src);
        e.cursor = src.find("bar").unwrap();
        e.apply(SelectInnerArgument, 10, &mut c);
        let sel = e.selection().expect("selection set");
        assert_eq!(&e.text()[sel.0..sel.1], "bar");
    }

    #[test]
    fn around_argument_pulls_trailing_comma() {
        let src = "call(foo, bar, baz)";
        let (mut e, mut c) = ed(src);
        // cursor on `b` of "bar" — not the last arg, so `around` extends
        // forward to include the trailing comma + space.
        e.cursor = src.find("bar").unwrap();
        e.apply(SelectAroundArgument, 10, &mut c);
        let sel = e.selection().expect("selection set");
        assert_eq!(&e.text()[sel.0..sel.1], "bar, ");
    }

    #[test]
    fn inner_argument_handles_nested_call() {
        // Nested paren — the cursor's enclosing args are `inner(2)` + `3`.
        let src = "outer(inner(1, 2), 3)";
        let (mut e, mut c) = ed(src);
        // cursor on `2` — should select `2`, not `inner(1, 2)`
        e.cursor = src.find('2').unwrap();
        e.apply(SelectInnerArgument, 10, &mut c);
        let sel = e.selection().expect("selection set");
        assert_eq!(&e.text()[sel.0..sel.1], "2");
    }

    #[test]
    fn align_selection_pads_lines_on_eq() {
        // Three lines with `=` at different columns. Selection covers all
        // three; AlignSelection('=') pads each line so the `=` line up.
        let (mut e, mut c) = ed("let a = 1\nlet bb = 2\nlet ccc = 3");
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(AlignSelection { on_char: '=' }, 10, &mut c);
        let lines: Vec<&str> = e.text().lines().collect();
        assert_eq!(lines.len(), 3);
        let eq_cols: Vec<usize> = lines
            .iter()
            .map(|l| l.chars().position(|c| c == '=').unwrap())
            .collect();
        assert_eq!(eq_cols[0], eq_cols[1]);
        assert_eq!(eq_cols[1], eq_cols[2]);
        // The widest pre-`=` segment was "let ccc " — every line should be
        // padded to that same width.
        assert_eq!(lines[2], "let ccc = 3");
    }

    #[test]
    fn align_selection_no_op_when_already_aligned() {
        // Already aligned ⇒ no edit (also covers the "selection cleared"
        // post-condition).
        let (mut e, mut c) = ed("foo = 1\nbar = 2");
        let before = e.text().to_string();
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(AlignSelection { on_char: '=' }, 10, &mut c);
        assert_eq!(e.text(), before);
        assert!(e.anchor.is_none());
    }

    #[test]
    fn align_selection_skips_lines_without_char() {
        // Middle line has no `=`; it should be left alone, the others
        // aligned against each other.
        let (mut e, mut c) = ed("a = 1\nblank line here\nccc = 3");
        e.cursor = 0;
        e.apply(SelectAll, 10, &mut c);
        e.apply(AlignSelection { on_char: '=' }, 10, &mut c);
        let lines: Vec<&str> = e.text().lines().collect();
        assert_eq!(lines[1], "blank line here");
        let eq0 = lines[0].chars().position(|c| c == '=').unwrap();
        let eq2 = lines[2].chars().position(|c| c == '=').unwrap();
        assert_eq!(eq0, eq2);
    }

    #[test]
    fn reflow_paragraph_wraps_long_line_to_width() {
        // Long single-line paragraph wraps to the requested width.
        let (mut e, mut c) = ed("the quick brown fox jumps over the lazy dog");
        e.cursor = 0;
        e.apply(ReflowParagraph { width: 16 }, 10, &mut c);
        // Each line should be <= 16 chars.
        for line in e.text().lines() {
            assert!(line.chars().count() <= 16, "line longer than 16: {line:?}");
        }
        // Round-trip preserves the words in order.
        let words: Vec<&str> = e.text().split_whitespace().collect();
        assert_eq!(
            words,
            vec![
                "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"
            ]
        );
    }

    #[test]
    fn reflow_paragraph_collapses_multi_line_paragraph() {
        let (mut e, mut c) = ed("alpha\nbeta\ngamma");
        e.cursor = 0;
        // Wide enough for everything on one line.
        e.apply(ReflowParagraph { width: 80 }, 10, &mut c);
        assert_eq!(e.text(), "alpha beta gamma");
    }

    #[test]
    fn reflow_paragraph_preserves_first_line_indent() {
        let (mut e, mut c) = ed("    indented prose that goes on for a while now");
        e.cursor = 0;
        e.apply(ReflowParagraph { width: 24 }, 10, &mut c);
        // Every line starts with the 4-space indent.
        for line in e.text().lines() {
            assert!(line.starts_with("    "), "line missing indent: {line:?}");
        }
    }

    #[test]
    fn reflow_paragraph_skips_blank_paragraph() {
        let (mut e, mut c) = ed("\n\n");
        e.apply(ReflowParagraph { width: 20 }, 10, &mut c);
        assert_eq!(e.text(), "\n\n");
    }

    #[test]
    fn toggle_case_char_swaps_and_advances() {
        let (mut e, mut c) = ed("aBc");
        e.cursor = 0;
        e.apply(ToggleCaseChar, 10, &mut c);
        assert_eq!(e.text(), "ABc");
        assert_eq!(e.cursor(), 1);
        e.apply(ToggleCaseChar, 10, &mut c);
        assert_eq!(e.text(), "Abc");
        assert_eq!(e.cursor(), 2);
    }

    #[test]
    fn toggle_case_char_skips_non_alpha_but_advances() {
        let (mut e, mut c) = ed("a 1");
        e.cursor = 1; // on the space
        e.apply(ToggleCaseChar, 10, &mut c);
        assert_eq!(e.text(), "a 1"); // unchanged
        assert_eq!(e.cursor(), 2); // advanced past
    }

    #[test]
    fn change_number_increments_at_cursor() {
        let (mut e, mut c) = ed("count = 41");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "count = 42");
        // Cursor lands on the last digit.
        assert_eq!(e.cursor(), 9);
    }

    #[test]
    fn change_number_decrements_with_count() {
        let (mut e, mut c) = ed("v=10");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: -3 }, 10, &mut c);
        assert_eq!(e.text(), "v=7");
    }

    #[test]
    fn change_number_picks_up_negative_sign_in_parens() {
        let (mut e, mut c) = ed("(-5)");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "(-4)");
    }

    #[test]
    fn tag_match_simple_pair() {
        // Cursor on the `<` of `<div>`.
        let text = "<div>hello</div>";
        // pos 0 = `<` of `<div>`
        let m = super::tag_match_at(text, 0);
        // The matching tag starts at `</div>` which is at position 10.
        assert_eq!(m, Some(10));
        // From inside `</div>` look back to `<div>`.
        let m2 = super::tag_match_at(text, 11);
        assert_eq!(m2, Some(0));
    }

    #[test]
    fn tag_match_handles_nesting() {
        let text = "<a><a>inner</a></a>";
        // Cursor on the outermost `<a>`.
        let m = super::tag_match_at(text, 1);
        // Outer closing `</a>` is at position 15.
        assert_eq!(m, Some(15));
    }

    #[test]
    fn tag_match_skips_self_closing() {
        let text = "<root><Foo /></root>";
        let m = super::tag_match_at(text, 0);
        // Outer `<root>` closes at `</root>` at position 13.
        assert_eq!(m, Some(13));
    }

    #[test]
    fn change_number_toggles_boolean_words() {
        let (mut e, mut c) = ed("flag = true");
        e.cursor = 7;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "flag = false");
        e.cursor = 7;
        e.apply(ChangeNumberAtCursor { delta: -1 }, 10, &mut c);
        assert_eq!(e.text(), "flag = true");
    }

    #[test]
    fn change_number_cycles_day_of_week() {
        let (mut e, mut c) = ed("Mon");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "Tue");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: 2 }, 10, &mut c);
        assert_eq!(e.text(), "Thu");
    }

    #[test]
    fn change_number_bumps_iso_date() {
        let (mut e, mut c) = ed("2026-05-16");
        e.cursor = 4;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "2026-05-17");
        e.cursor = 4;
        e.apply(ChangeNumberAtCursor { delta: 30 }, 10, &mut c);
        assert_eq!(e.text(), "2026-06-16");
    }

    #[test]
    fn change_number_iso_date_handles_leap_year() {
        let (mut e, mut c) = ed("2024-02-28");
        e.cursor = 4;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "2024-02-29");
        e.cursor = 4;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "2024-03-01");
    }

    #[test]
    fn change_number_doesnt_steal_id_minus() {
        // `x-5` is "5 with no sign" — the `-` is part of the prior identifier.
        let (mut e, mut c) = ed("x-5");
        e.cursor = 0;
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "x-6");
    }

    #[test]
    fn change_number_noop_when_no_digit_on_line() {
        let (mut e, mut c) = ed("just words");
        e.apply(ChangeNumberAtCursor { delta: 1 }, 10, &mut c);
        assert_eq!(e.text(), "just words");
    }

    #[test]
    fn case_transform_no_selection_is_noop() {
        let (mut e, mut c) = ed("Hello");
        e.cursor = 0;
        e.apply(
            TransformSelectionCase(crate::edit_op::CaseTransform::Upper),
            10,
            &mut c,
        );
        assert_eq!(e.text(), "Hello");
    }

    #[test]
    fn find_char_on_line_forward_and_backward() {
        let (mut e, mut c) = ed("hello world\nfoobar");
        e.cursor = 0;
        // f-o → move to first 'o'
        e.apply(
            EditOp::FindCharOnLine {
                ch: 'o',
                forward: true,
                before: false,
                inclusive: false,
            },
            10,
            &mut c,
        );
        assert_eq!(e.cursor, 4);
        // f-o again from there → second 'o' on the same line
        e.apply(
            EditOp::FindCharOnLine {
                ch: 'o',
                forward: true,
                before: false,
                inclusive: false,
            },
            10,
            &mut c,
        );
        assert_eq!(e.cursor, 7);
        // F-h → backward to 'h'
        e.apply(
            EditOp::FindCharOnLine {
                ch: 'h',
                forward: false,
                before: false,
                inclusive: false,
            },
            10,
            &mut c,
        );
        assert_eq!(e.cursor, 0);
        // t-w forward from 'h' → just before 'w'
        e.apply(
            EditOp::FindCharOnLine {
                ch: 'w',
                forward: true,
                before: true,
                inclusive: false,
            },
            10,
            &mut c,
        );
        assert_eq!(e.cursor, 5); // 'w' is at 6, before is 5
        // f-x (not on this line) → no-op
        let before = e.cursor;
        e.apply(
            EditOp::FindCharOnLine {
                ch: 'x',
                forward: true,
                before: false,
                inclusive: false,
            },
            10,
            &mut c,
        );
        assert_eq!(e.cursor, before);
    }

    #[test]
    fn restore_last_selection_brings_it_back() {
        let (mut e, mut c) = ed("hello world");
        // Make a selection [0, 5)
        e.cursor = 0;
        e.apply(EditOp::SelectStart, 10, &mut c);
        e.cursor = 5;
        // YankSelection captures last_selection, then explicit SelectClear.
        e.apply(EditOp::YankSelection, 10, &mut c);
        e.apply(EditOp::SelectClear, 10, &mut c);
        assert!(e.selection().is_none());
        e.cursor = 7; // move somewhere
        e.apply(EditOp::RestoreLastSelection, 10, &mut c);
        assert_eq!(e.selection(), Some((0, 5)));
        assert_eq!(e.cursor, 5);
    }

    #[test]
    fn enclosing_bracket_pair_finds_nested() {
        let (mut e, _) = ed("fn f() { let x = (1 + (2 * 3)) }");
        // Cursor inside the inner (2 * 3)
        let inner = e.text().find("2 * 3").unwrap() + 1;
        e.cursor = inner;
        let pair = e.enclosing_bracket_pair('(', ')').unwrap();
        // Should be the inner ( and matching )
        let open = e.text().find("(2").unwrap();
        let close = e.text()[open..].find(')').unwrap() + open;
        assert_eq!(pair, (open, close));
        // Cursor inside braces — bracket-pair for `{` `}`
        let bi = e.text().find("let").unwrap();
        e.cursor = bi;
        let pair = e.enclosing_bracket_pair('{', '}').unwrap();
        let bo = e.text().find('{').unwrap();
        let bc = e.text().rfind('}').unwrap();
        assert_eq!(pair, (bo, bc));
    }

    #[test]
    fn enclosing_quote_pair_on_line_finds_inner_range() {
        let (mut e, _) = ed("let s = \"hello world\";\nother line");
        // Cursor inside the string (col 12 = inside "hello world")
        e.place_cursor(0, 12);
        let pair = e.enclosing_quote_pair_on_line('"').unwrap();
        // Open quote at col 8, close at col 20 (chars)
        // Convert by re-deriving from text
        let text = e.text();
        let open = text.find('"').unwrap();
        let close = text[open + 1..].find('"').unwrap() + open + 1;
        assert_eq!(pair, (open, close));
        // Cursor outside any string → None.
        e.place_cursor(0, 3);
        assert_eq!(e.enclosing_quote_pair_on_line('"'), None);
    }

    #[test]
    fn word_under_cursor_basic() {
        let (mut e, _) = ed("let foo = bar;\nfoo()");
        // Cursor at start — on 'l'.
        assert_eq!(e.word_under_cursor(), "let");
        // After "let "...
        e.place_cursor(0, 4);
        assert_eq!(e.word_under_cursor(), "foo");
        // On the `=` — empty.
        e.place_cursor(0, 8);
        assert_eq!(e.word_under_cursor(), "");
        // On line 2, cursor at "f" of "foo()".
        e.place_cursor(1, 0);
        assert_eq!(e.word_under_cursor(), "foo");
        // After the open paren — not in a word.
        e.place_cursor(1, 4);
        assert_eq!(e.word_under_cursor(), "");
    }

    #[test]
    fn bracket_match_open_to_close() {
        let (e, _) = ed("fn f() { x }");
        // Cursor at 0 — not on a bracket.
        assert_eq!(e.bracket_match(), None);
        // Place cursor on the `(`.
        let mut e = e;
        e.place_cursor(0, 4);
        let m = e.bracket_match().unwrap();
        assert_eq!(m, (0, 5)); // the `)` is at col 5
    }

    #[test]
    fn bracket_match_across_lines() {
        let mut e = ed("{\n  a\n  b\n}").0;
        // Place cursor on the `}` (row 3, col 0).
        e.place_cursor(3, 0);
        let m = e.bracket_match().unwrap();
        assert_eq!(m, (0, 0)); // matches the `{`
    }

    #[test]
    fn smart_pair_backspace_deletes_both() {
        let (mut e, mut c) = ed("");
        e.auto_pair = true;
        e.apply(InsertChar('('), 10, &mut c); // → "()" cursor at 1
        e.apply(Backspace, 10, &mut c);
        assert_eq!(e.text(), "");
        assert_eq!(e.cursor(), 0);
    }

    #[test]
    fn pair_backspace_skipped_when_no_pair() {
        // `(x` — backspace just deletes the `(`, not the trailing `x`.
        let (mut e, mut c) = ed("(x");
        e.auto_pair = true;
        e.apply(MoveLineStart, 10, &mut c);
        e.apply(MoveRight, 10, &mut c); // cursor between `(` and `x`
        e.apply(Backspace, 10, &mut c);
        assert_eq!(e.text(), "x");
    }

    #[test]
    fn auto_indent_carries_leading_whitespace() {
        let (mut e, mut c) = ed("    let x = 1;");
        e.auto_indent = true;
        // Cursor at end of line.
        e.apply(MoveLineEnd, 10, &mut c);
        e.apply(InsertNewline, 10, &mut c);
        // The new line starts with the same 4-space indent.
        assert_eq!(e.text(), "    let x = 1;\n    ");
    }

    #[test]
    fn auto_indent_only_copies_chars_before_cursor() {
        // Mid-line Enter shouldn't *expand* the indent — only the indent chars
        // before the split point carry forward.
        let (mut e, mut c) = ed("    abc");
        e.auto_indent = true;
        // Place cursor between the two leading spaces.
        e.place_cursor(0, 2);
        e.apply(InsertNewline, 10, &mut c);
        // The split leaves "  " on line 0, "  abc" on line 1; line 1's leading
        // indent (copied from line 0 prefix) is two spaces.
        assert_eq!(e.text(), "  \n    abc");
    }

    #[test]
    fn auto_indent_off_by_default() {
        let (mut e, mut c) = ed("    hi");
        e.apply(MoveLineEnd, 10, &mut c);
        e.apply(InsertNewline, 10, &mut c);
        assert_eq!(e.text(), "    hi\n");
    }

    #[test]
    fn auto_pair_off_by_default() {
        let (mut e, mut c) = ed("");
        e.apply(InsertChar('('), 10, &mut c);
        assert_eq!(e.text(), "(");
        assert_eq!(e.cursor(), 1);
    }

    #[test]
    fn persistent_undo_round_trips() {
        let d = tempfile::tempdir().unwrap();
        let file = d.path().join("a.txt");
        std::fs::write(&file, "abc").unwrap();
        let undo_path = undo_path_for(d.path(), &file);

        // Editor over the file; type a few chars to build an undo stack.
        let (mut e, mut c) = ed("abc");
        // MoveLineEnd lands AFTER the last char of the line; the
        // earlier MoveBufferEnd-as-text.len() coincided with that on
        // a single-line buffer, but G's new vim-correct semantic
        // (start of last line) doesn't. 2026-06-13 S2-05 fix.
        e.apply(MoveLineEnd, 10, &mut c);
        for ch in "DE".chars() {
            e.apply(InsertChar(ch), 10, &mut c);
        }
        e.apply(MoveLeft, 10, &mut c); // break the insert run so a snapshot lands
        assert_eq!(e.text(), "abcDE");
        assert!(e.can_undo());

        // Save it.
        assert!(save_history_to(&e, &undo_path));
        assert!(undo_path.exists());

        // Fresh editor over the same text — undo stack empty until restore.
        let (mut e2, _c) = ed("abcDE");
        assert!(!e2.can_undo());
        assert!(load_history_from(&mut e2, &undo_path));
        assert!(e2.can_undo());

        // Undo collapses back to "abc" — same as the original editor would.
        let mut c2 = Clipboard::detached();
        e2.apply(Undo, 10, &mut c2);
        assert_eq!(e2.text(), "abc");
    }

    #[test]
    fn persistent_undo_rejects_when_text_drifts() {
        let d = tempfile::tempdir().unwrap();
        let file = d.path().join("a.txt");
        let undo_path = undo_path_for(d.path(), &file);

        let (mut e, mut c) = ed("foo");
        e.apply(InsertChar('!'), 10, &mut c);
        e.apply(MoveLeft, 10, &mut c);
        assert!(save_history_to(&e, &undo_path));

        // Fresh editor over a *different* text (file changed outside mnml).
        let (mut e2, _c) = ed("totally different");
        assert!(!load_history_from(&mut e2, &undo_path));
        assert!(!e2.can_undo());
    }

    #[test]
    fn bracket_depths_track_nesting() {
        // ((a)) on one line — depths 0, 1, 1, 0.
        let d = bracket_depths_per_line("((a))");
        assert_eq!(d, vec![vec![(0, 0), (1, 1), (3, 1), (4, 0)]]);
        // Multi-line + mixed brackets.
        let t = "fn f(x) {\n  [y]\n}";
        let d = bracket_depths_per_line(t);
        // line 0: `(` depth 0 at col 4, `)` depth 0 at col 6, `{` depth 0 at col 8
        assert_eq!(d[0], vec![(4, 0), (6, 0), (8, 0)]);
        // line 1: `[` depth 1 at col 2, `]` depth 1 at col 4
        assert_eq!(d[1], vec![(2, 1), (4, 1)]);
        // line 2: `}` depth 0
        assert_eq!(d[2], vec![(0, 0)]);
    }

    #[test]
    fn big_word_motions() {
        // WORDs are whitespace-delimited — "foo.bar" is one WORD; "foo bar"
        // is two. The (non-big) word motions split on punctuation; the big
        // ones don't.
        let (mut e, mut c) = ed("foo.bar baz/qux");
        // Cursor at 0 ('f'). `W` ⇒ start of next WORD = byte 8 ('b').
        e.apply(MoveBigWordRight, 10, &mut c);
        assert_eq!(e.cursor(), 8, "W from 0");
        // `B` ⇒ start of previous WORD = byte 0.
        e.apply(MoveBigWordLeft, 10, &mut c);
        assert_eq!(e.cursor(), 0, "B from 8");
        // `E` ⇒ end of first WORD ("foo.bar") = byte 6 (the 'r').
        e.apply(MoveBigWordEnd, 10, &mut c);
        assert_eq!(e.cursor(), 6, "E from 0");
        // From byte 6, `E` again ⇒ end of "baz/qux" = byte 14.
        e.apply(MoveBigWordEnd, 10, &mut c);
        assert_eq!(e.cursor(), 14, "E from 6");
        // `gE` from byte 14 ⇒ end of previous WORD = byte 6.
        e.apply(MoveBigWordEndBack, 10, &mut c);
        assert_eq!(e.cursor(), 6, "gE from 14");
    }

    #[test]
    fn ge_jumps_to_end_of_prev_word() {
        let (mut e, mut c) = ed("hello world foo");
        // Cursor on 'f' (start of "foo", byte 12). `ge` ⇒ end of "world" = byte 10.
        e.cursor = 12;
        e.apply(MoveWordEndBack, 10, &mut c);
        assert_eq!(e.cursor(), 10);
        // From byte 10 ('d'), `ge` again ⇒ end of "hello" = byte 4 ('o').
        e.apply(MoveWordEndBack, 10, &mut c);
        assert_eq!(e.cursor(), 4);
    }

    /// 2026-06-13 nvchad-user SEV-2 S2-02 regression: `:%s/.../.../g`
    /// must undo in ONE step. atomic_undo wraps a multi-op edit so a
    /// single `Undo` reverts the whole group.
    #[test]
    fn atomic_undo_collapses_many_ops_into_one_step() {
        let (mut e, mut c) = ed("foo bar foo");
        let initial = e.text().to_string();
        // Three replacements: descending order so each keeps the
        // earlier byte offsets valid (mimics the :%s code path).
        e.atomic_undo(|ed| {
            // Replace "foo" at byte 8 with "BAZ", then "foo" at 0 with "BAZ".
            ed.apply(
                EditOp::ReplaceRange {
                    start: 8,
                    end: 11,
                    text: "BAZ".into(),
                },
                10,
                &mut c,
            );
            ed.apply(
                EditOp::ReplaceRange {
                    start: 0,
                    end: 3,
                    text: "BAZ".into(),
                },
                10,
                &mut c,
            );
        });
        assert_eq!(e.text(), "BAZ bar BAZ");
        // ONE undo reverts everything.
        e.apply(EditOp::Undo, 10, &mut c);
        assert_eq!(e.text(), initial);
    }

    /// Bench: measure per-edit latency on a real ~600 KB / 14k line
    /// file. Guarded by `#[ignore]` so it doesn't run in the normal
    /// `cargo test` sweep; invoke explicitly:
    ///
    /// ```sh
    /// export PATH="/opt/homebrew/opt/zig@0.15/bin:$PATH"
    /// cargo test --release editor::tests::bench_large_file_edits -- --ignored --nocapture
    /// ```
    ///
    /// Prints the elapsed time for each scenario. Compare across
    /// commits by running this before + after a change.
    #[test]
    #[ignore]
    fn bench_large_file_edits() {
        use std::time::Instant;
        // Read the source file, then repeat it to reach ~5 MB so we exercise
        // the "gets slow with bigger files" regime the user reported. If the
        // env var MNML_BENCH_ONESHOT is set, use the file as-is (small mode).
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/mod.rs");
        let base = std::fs::read_to_string(&path).expect("read app/mod.rs");
        let text = if std::env::var_os("MNML_BENCH_ONESHOT").is_some() {
            base
        } else {
            let mut t = String::with_capacity(5 * 1024 * 1024 + base.len());
            while t.len() < 5 * 1024 * 1024 {
                t.push_str(&base);
            }
            t
        };
        println!(
            "\nfile: {} bytes, {} lines\n",
            text.len(),
            text.lines().count()
        );
        let bench = |label: &str, f: &mut dyn FnMut()| {
            let start = Instant::now();
            f();
            println!("  {label:<40} {:?}", start.elapsed());
        };

        // 1. INSERT at position 0 — worst case for String::insert_str
        //    (shifts the entire buffer each time).
        {
            let mut e = Editor::new(&text, 4);
            let mut c = Clipboard::detached();
            bench("insert at start (100 chars, worst case)", &mut || {
                for _ in 0..100 {
                    e.cursor = 0;
                    e.apply(EditOp::InsertChar('x'), 10, &mut c);
                }
            });
        }

        // 2. INSERT at middle — half the buffer shifts.
        {
            let mut e = Editor::new(&text, 4);
            let mut c = Clipboard::detached();
            let mid_byte = text.len() / 2;
            bench("insert at middle (100 chars)", &mut || {
                for _ in 0..100 {
                    e.cursor = mid_byte;
                    e.apply(EditOp::InsertChar('y'), 10, &mut c);
                }
            });
        }

        // 3. INSERT at end — should be near-free (no shift).
        {
            let mut e = Editor::new(&text, 4);
            let mut c = Clipboard::detached();
            bench("insert at end (100 chars, best case)", &mut || {
                for _ in 0..100 {
                    e.cursor = e.text.len();
                    e.apply(EditOp::InsertChar('z'), 10, &mut c);
                }
            });
        }

        // 4. DELETE at start — worst case for String::replace_range.
        {
            let mut e = Editor::new(&text, 4);
            let mut c = Clipboard::detached();
            bench("delete at start (100 chars, worst case)", &mut || {
                for _ in 0..100 {
                    e.cursor = 0;
                    e.apply(EditOp::DeleteForward, 10, &mut c);
                }
            });
        }

        // 5. Line-count computation — proxy for byte→row/col conversions
        //    that fire on every render.
        {
            let e = Editor::new(&text, 4);
            bench("line_count (1000 calls)", &mut || {
                for _ in 0..1000 {
                    let _ = e.line_count();
                }
            });
        }

        // 6. Read `text()` 1000 times — proxy for hot-path readers.
        {
            let e = Editor::new(&text, 4);
            bench("text() (1000 calls, len)", &mut || {
                for _ in 0..1000 {
                    std::hint::black_box(e.text().len());
                }
            });
        }

        // 7. HIGHLIGHT — tree-sitter first parse on a fresh buffer.
        //    This is what the render path does when a file opens.
        {
            use tree_sitter::Tree;
            let mut tree: Option<Tree> = None;
            bench("highlight first parse (rs)", &mut || {
                let _ = crate::highlight::highlight_lines_with_cache(
                    &text,
                    "rs",
                    &mut tree,
                    &[],
                    &[],
                    Vec::new(),
                );
            });
        }

        // 8. HIGHLIGHT — incremental parse after one char inserted at end.
        //    Simulates what typing does to the highlight pipeline. Must feed
        //    prev_highlights back in — that's what production does via
        //    Buffer::refresh_highlights, and it's what gates the incremental
        //    fast path (see `do_incremental` in highlight.rs).
        {
            use crate::edit_op::TextEdit;
            use tree_sitter::Tree;
            let mut tree: Option<Tree> = None;
            let prev_h = crate::highlight::highlight_lines_with_cache(
                &text,
                "rs",
                &mut tree,
                &[],
                &[],
                Vec::new(),
            );
            let mut modified = text.clone();
            modified.push('x');
            let edit = TextEdit {
                start_byte: text.len(),
                old_end_byte: text.len(),
                new_end_byte: text.len() + 1,
            };
            let prev_line_starts: Vec<usize> = std::iter::once(0)
                .chain(
                    text.as_bytes()
                        .iter()
                        .enumerate()
                        .filter_map(|(i, &b)| (b == b'\n').then_some(i + 1)),
                )
                .collect();
            bench("highlight incremental (rs, 100 edits)", &mut || {
                let mut prev = prev_h.clone();
                for _ in 0..100 {
                    prev = crate::highlight::highlight_lines_with_cache(
                        &modified,
                        "rs",
                        &mut tree,
                        std::slice::from_ref(&edit),
                        &prev_line_starts,
                        prev,
                    );
                }
            });
        }
    }
}