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
//! Vim `:`-command interpreter — the giant `run_ex_command` match,
//! `:s/.../.../` substitute, `:sort`, `:move`, `:copy`, `:!cmd` filter,
//! and the quit-confirm accept handler.
//!
//! `run_ex_command` itself is still a ~3k-line single fn — splitting
//! its arms into per-topic helper methods is a true refactor, deferred.
//!
//! Sub-extracted from `app/editor_features.rs`. Non-destructive move.

use super::*;

/// Expand `:args {pattern}` under `ws` into a list of absolute paths.
/// Supports:
/// - literal (no wildcards): treated as a single path (skipped if not
///   an existing file).
/// - `*.EXT` / `foo*bar.rs`: basename glob at workspace root (non-
///   recursive).
/// - `dir/**/*.EXT` or plain `**/*.EXT`: recursive walk under `dir`
///   (or workspace root), matching the trailing `*.EXT` pattern.
///
/// Not vim-complete (no `[abc]`, no `{a,b}`) but covers `:args *.rs`
/// and `:args src/**/*.rs` — the two forms nvchad users hit ~always.
/// Uses `ignore::WalkBuilder` so `.gitignore` is respected during
/// recursive scans.
/// Split `:w | e other.txt` style command chains on ` | ` (space
/// pipe space). Returns `Some(parts)` when at least one split point
/// exists, else `None` so the caller doesn't need to recurse on
/// trivial cases. Skips pipes inside `s/…/…/` payloads (`s/foo|bar/`)
/// by detecting the substitute-shortcut head. nvchad-round-10 SEV-2
/// 2026-07-11.
fn split_ex_command_chain(line: &str) -> Option<Vec<String>> {
    let head_tok = line.split_whitespace().next().unwrap_or("");
    // If the head is a substitute (`s/…`, `:%s/…`, `:{range}s/…`),
    // don't split — the pipe is likely inside the pattern.
    if head_tok.starts_with("s/")
        || head_tok.starts_with("s#")
        || head_tok.starts_with("%s/")
        || head_tok.starts_with("g/")
        || head_tok.starts_with("v/")
    {
        return None;
    }
    // Look for ` | ` — space-pipe-space. This avoids splitting
    // pipes inside quoted args / URLs / regexes.
    if !line.contains(" | ") {
        return None;
    }
    let parts: Vec<String> = line
        .split(" | ")
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    (parts.len() > 1).then_some(parts)
}

fn arglist_expand(ws: &std::path::Path, pattern: &str) -> Vec<std::path::PathBuf> {
    let expanded = shellexpand_tilde(pattern);
    let has_wildcard = expanded.contains('*') || expanded.contains('?');
    if !has_wildcard {
        let p = if std::path::Path::new(&expanded).is_absolute() {
            std::path::PathBuf::from(&expanded)
        } else {
            ws.join(&expanded)
        };
        return if p.is_file() { vec![p] } else { Vec::new() };
    }
    // Split into root + relative pattern. If `**` is present, walk
    // recursively from the leading literal segment.
    let (walk_root, glob_tail) = if let Some(pos) = expanded.find("**") {
        let head = &expanded[..pos];
        let tail = &expanded[pos + 2..];
        let tail = tail.trim_start_matches('/');
        let head_trim = head.trim_end_matches('/');
        let root = if head_trim.is_empty() {
            ws.to_path_buf()
        } else if std::path::Path::new(head_trim).is_absolute() {
            std::path::PathBuf::from(head_trim)
        } else {
            ws.join(head_trim)
        };
        (root, tail.to_string())
    } else {
        // Non-recursive: split on last `/` if any.
        let (dir, base) = expanded
            .rsplit_once('/')
            .map(|(d, b)| (d.to_string(), b.to_string()))
            .unwrap_or_else(|| (String::new(), expanded.clone()));
        let root = if dir.is_empty() {
            ws.to_path_buf()
        } else if std::path::Path::new(&dir).is_absolute() {
            std::path::PathBuf::from(&dir)
        } else {
            ws.join(&dir)
        };
        (root, base)
    };
    let mut out: Vec<std::path::PathBuf> = Vec::new();
    let recursive = glob_tail.is_empty() || pattern.contains("**");
    for entry in ignore::WalkBuilder::new(&walk_root)
        .max_depth(if recursive { None } else { Some(1) })
        .build()
        .flatten()
    {
        let p = entry.path();
        if !p.is_file() {
            continue;
        }
        let name = match p.file_name().and_then(|n| n.to_str()) {
            Some(s) => s,
            None => continue,
        };
        let pat_for_match = if glob_tail.is_empty() {
            &pattern[pattern.rfind('/').map(|i| i + 1).unwrap_or(0)..]
        } else {
            glob_tail.as_str()
        };
        if simple_glob_match(pat_for_match, name) {
            out.push(p.to_path_buf());
        }
    }
    out.sort();
    out
}

/// `~` → `$HOME` prefix expansion. No env-var support (vim's `$VAR`
/// syntax); nvchad users just type paths.
fn shellexpand_tilde(s: &str) -> String {
    if let Some(rest) = s.strip_prefix("~/")
        && let Some(home) = std::env::var_os("HOME")
    {
        let mut p = std::path::PathBuf::from(home);
        p.push(rest);
        return p.to_string_lossy().into_owned();
    }
    s.to_string()
}

/// Public re-export of [`vim_pattern_to_regex`] for
/// `App::accept_find` / `update_live_find_preview` — vim regex
/// grammar in the `/search` prompt, not just `:s`.
/// nvchad-round-8 SEV-2 2026-07-11.
pub(crate) fn vim_pattern_to_regex_public(input: &str) -> String {
    vim_pattern_to_regex(input)
}

/// Translate vim's `:s/PATTERN/…/` grammar (the find side) to the
/// `regex` crate's grammar. Vim uses `\(…\)` for capture groups,
/// `\|` for alternation, `\<`/`\>` for word boundaries. The `regex`
/// crate uses `(…)`, `|`, `\b`. Keys we do NOT rewrite (they already
/// mean the same thing): `\d`, `\w`, `\s`, `\D`, `\W`, `\S`, `\b`.
///
/// nvchad-round-7 SEV-2 2026-07-11.
fn vim_pattern_to_regex(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('(') => out.push('('),
                Some(')') => out.push(')'),
                Some('|') => out.push('|'),
                Some('<') | Some('>') => out.push_str("\\b"),
                Some('{') => out.push('{'),
                Some('}') => out.push('}'),
                Some('+') => out.push('+'),
                Some('?') => out.push('?'),
                Some('=') => out.push('?'), // vim `\=` = optional (regex `?`)
                Some(next) => {
                    out.push('\\');
                    out.push(next);
                }
                None => out.push('\\'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Translate vim's `:s/…/REPLACEMENT/` grammar to the `regex` crate's
/// [`Replacer`] grammar. Vim uses `\1..\9` for capture groups, `&` /
/// `\0` for the whole match, and `\\` for a literal backslash. The
/// crate uses `$1..$9`, `$0`, and treats a bare `$` as the start of a
/// group reference — so literal `$` in the input must double as `$$`.
///
/// Grammar handled:
/// - `\0`  → `$0`
/// - `\1..\9` → `$1..$9`
/// - `\\`  → `\`
/// - `\&`  → `&` (literal)
/// - `&`   → `$0`  (whole match)
/// - `$`   → `$$` (escape crate's own metachar)
/// - `\n`  → `\n` newline (vim uses `\r` for newline in replacement,
///   but users routinely type `\n`; support both for tolerance)
/// - `\r`  → `\n` newline (vim canonical — `\n` in replacement means
///   NUL in strict vim, but every nvchad user types `\n` meaning
///   newline; we honor both)
/// - `\t`  → tab
/// - other `\X` → `X` literal
///
/// nvchad-round-7 SEV-1 2026-07-11.
fn vim_replacement_to_regex(input: &str) -> String {
    let mut out = String::with_capacity(input.len() + 8);
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.next() {
                Some(next) => match next {
                    '0'..='9' => {
                        out.push('$');
                        out.push(next);
                    }
                    '\\' => out.push('\\'),
                    '&' => out.push('&'),
                    'n' | 'r' => out.push('\n'),
                    't' => out.push('\t'),
                    other => out.push(other),
                },
                None => out.push('\\'),
            },
            '&' => out.push_str("$0"),
            '$' => out.push_str("$$"),
            other => out.push(other),
        }
    }
    out
}

/// `*` matches any run (incl. empty), `?` matches one char. No brace
/// or bracket expansion. Case-sensitive.
fn simple_glob_match(pat: &str, name: &str) -> bool {
    let pat = pat.as_bytes();
    let name = name.as_bytes();
    fn inner(pat: &[u8], name: &[u8]) -> bool {
        let mut pi = 0;
        let mut ni = 0;
        let mut star = None;
        let mut star_ni = 0;
        while ni < name.len() {
            if pi < pat.len() && pat[pi] == b'*' {
                star = Some(pi);
                star_ni = ni;
                pi += 1;
            } else if pi < pat.len() && (pat[pi] == b'?' || pat[pi] == name[ni]) {
                pi += 1;
                ni += 1;
            } else if let Some(sp) = star {
                pi = sp + 1;
                star_ni += 1;
                ni = star_ni;
            } else {
                return false;
            }
        }
        while pi < pat.len() && pat[pi] == b'*' {
            pi += 1;
        }
        pi == pat.len()
    }
    inner(pat, name)
}

impl App {
    /// `:%!cmd` / `:'<,'>!cmd` — pipe the whole buffer (or the active
    /// selection if `selection_only=true`) through `cmd` via `$SHELL -c`,
    /// replacing the input range with the command's stdout. Single edit op
    /// so undo restores. Non-zero exit ⇒ buffer untouched + toast.
    pub fn run_filter_through_shell(&mut self, cmd: &str, selection_only: bool) {
        if cmd.is_empty() {
            self.toast(":%! — command required");
            return;
        }
        let Some(idx) = self.active else {
            self.toast(":%! — no active editor");
            return;
        };
        let Some(Pane::Editor(b)) = self.panes.get(idx) else {
            self.toast(":%! — no active editor");
            return;
        };
        // Determine the input range.
        let (start, end) = if selection_only || (b.editor.has_selection() && !cmd.is_empty()) {
            match b.editor.selection() {
                Some((lo, hi)) => (lo, hi),
                None => (0, b.editor.text().len()),
            }
        } else {
            (0, b.editor.text().len())
        };
        let buf_len = b.editor.text().len();
        let input = b.editor.text()[start..end].to_string();
        // Spawn the shell synchronously, write input to stdin, capture stdout.
        // Use the active workspace as cwd so `:%!cmd` resolves relative
        // paths against the active workspace, not the launch primary.
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
        let workspace = self.active_workspace_path().to_path_buf();
        let result = std::thread::scope(|s| {
            let handle = s.spawn(|| {
                use std::io::Write;
                let mut child = match std::process::Command::new(&shell)
                    .arg("-c")
                    .arg(cmd)
                    .current_dir(&workspace)
                    .stdin(std::process::Stdio::piped())
                    .stdout(std::process::Stdio::piped())
                    .stderr(std::process::Stdio::piped())
                    .spawn()
                {
                    Ok(c) => c,
                    Err(e) => return Err(format!("spawn: {e}")),
                };
                if let Some(mut stdin) = child.stdin.take() {
                    let _ = stdin.write_all(input.as_bytes());
                }
                match child.wait_with_output() {
                    Ok(out) => {
                        if !out.status.success() {
                            let stderr = String::from_utf8_lossy(&out.stderr);
                            let preview: String = stderr.trim().chars().take(120).collect();
                            return Err(format!(
                                "exit {}{preview}",
                                out.status.code().unwrap_or(-1)
                            ));
                        }
                        Ok(String::from_utf8_lossy(&out.stdout).to_string())
                    }
                    Err(e) => Err(format!("wait: {e}")),
                }
            });
            handle.join().unwrap()
        });
        match result {
            Ok(stdout) => {
                let len = stdout.len();
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.apply_edit_ops(
                        vec![crate::edit_op::EditOp::ReplaceRange {
                            start,
                            end,
                            text: stdout,
                        }],
                        &mut self.clipboard,
                        0,
                    );
                }
                let scope_label = if selection_only || end - start < buf_len {
                    "selection"
                } else {
                    "buffer"
                };
                self.toast(format!(":! — {scope_label}{len}B"));
            }
            Err(e) => self.toast(format!(":! — {e}")),
        }
    }

    /// vim's `:sort [i]` — set `case_insensitive=true` to compare via
    /// lowercase form (ASCII; cheap, matches vim's default behavior).
    pub fn run_sort_lines_opts(&mut self, unique: bool, reverse: bool, case_insensitive: bool) {
        self.run_sort_lines_full(unique, reverse, case_insensitive, false, None);
    }

    /// `:{start},{end}sort [flags]` — sort a specific line range.
    /// nvchad-round-9 SEV-2 2026-07-11.
    pub fn run_sort_lines_range(
        &mut self,
        start_line: usize,
        end_line: usize,
        unique: bool,
        reverse: bool,
        case_insensitive: bool,
        numeric: bool,
    ) {
        self.run_sort_lines_full(
            unique,
            reverse,
            case_insensitive,
            numeric,
            Some((start_line, end_line)),
        );
    }

    fn run_sort_lines_full(
        &mut self,
        unique: bool,
        reverse: bool,
        case_insensitive: bool,
        numeric: bool,
        line_range: Option<(usize, usize)>,
    ) {
        let Some(b) = self.active_editor_mut() else {
            self.toast("no active editor");
            return;
        };
        let text = b.editor.text();
        let line_start = |t: &str, line: usize| -> usize {
            if line == 0 {
                return 0;
            }
            let mut seen = 0;
            for (i, ch) in t.bytes().enumerate() {
                if ch == b'\n' {
                    seen += 1;
                    if seen == line {
                        return i + 1;
                    }
                }
            }
            t.len()
        };
        let line_end = |t: &str, line: usize| -> usize {
            let s = line_start(t, line);
            t[s..].find('\n').map(|i| s + i).unwrap_or(t.len())
        };
        // Determine the line range — explicit range wins, else
        // selection, else whole buffer.
        let (start_byte, end_byte, start_line, end_line) = if let Some((sr, er)) = line_range {
            (line_start(text, sr), line_end(text, er), sr, er)
        } else if let Some((sel_lo, sel_hi)) = b.editor.selection() {
            let line_at = |byte: usize| text[..byte].bytes().filter(|&c| c == b'\n').count();
            let lo_line = line_at(sel_lo);
            let hi_line = line_at(sel_hi);
            (
                line_start(text, lo_line),
                line_end(text, hi_line),
                lo_line,
                hi_line,
            )
        } else {
            let line_count = text.bytes().filter(|&c| c == b'\n').count() + 1;
            (0, text.len(), 0, line_count.saturating_sub(1))
        };
        if start_byte >= end_byte {
            return;
        }
        // nvchad-round-9 SEV-2 2026-07-11 — the previous version's
        // `split('\n').collect()` returned an empty trailing element
        // when the range ended on a newline; that empty string sorted
        // to the top and produced a phantom blank line.
        let block = &text[start_byte..end_byte];
        let trailing_nl = block.ends_with('\n');
        let mut lines: Vec<&str> = if trailing_nl {
            block[..block.len() - 1].split('\n').collect()
        } else {
            block.split('\n').collect()
        };
        if numeric {
            // Vim `:sort n` sorts by the FIRST decimal number the line
            // contains; lines with no number sort first (vim canonical).
            let parse_num = |l: &str| -> Option<i64> {
                let bytes = l.as_bytes();
                let mut i = 0usize;
                while i < bytes.len() {
                    if bytes[i].is_ascii_digit() || bytes[i] == b'-' {
                        let start = i;
                        if bytes[i] == b'-' {
                            i += 1;
                        }
                        while i < bytes.len() && bytes[i].is_ascii_digit() {
                            i += 1;
                        }
                        if let Ok(n) = l[start..i].parse::<i64>() {
                            return Some(n);
                        }
                    }
                    i += 1;
                }
                None
            };
            lines.sort_by_key(|l| parse_num(l));
        } else if case_insensitive {
            lines.sort_by_key(|l| l.to_ascii_lowercase());
        } else {
            lines.sort();
        }
        if unique {
            if case_insensitive {
                lines.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
            } else {
                lines.dedup();
            }
        }
        if reverse {
            lines.reverse();
        }
        let mut new_block = lines.join("\n");
        if trailing_nl {
            new_block.push('\n');
        }
        if new_block == block {
            return;
        }
        let ops = vec![crate::edit_op::EditOp::ReplaceRange {
            start: start_byte,
            end: end_byte,
            text: new_block,
        }];
        let mut clip = crate::clipboard::Clipboard::new();
        b.apply_edit_ops(ops, &mut clip, 0);
        self.toast(format!(
            ":sort{}{}{}{}{} line(s)",
            if unique { "u" } else { "" },
            if reverse { "r" } else { "" },
            if case_insensitive { "i" } else { "" },
            if numeric { "n" } else { "" },
            end_line + 1 - start_line
        ));
    }

    /// `:retab` — replace every TAB with `[editor] tab_width` spaces in the
    /// whole buffer. One ReplaceRange so undo reverts in a single step.
    /// `:m N` / `:co N` — move (`copy=false`) or copy (`copy=true`) the
    /// cursor's current line to right after line N (1-based; `0` ⇒ top of
    /// buffer). `+K` / `-K` (relative form) ⇒ N = current_row + K. The
    /// cursor lands on the line in its new home. Single edit op so undo
    /// restores the original ordering.
    pub fn run_move_or_copy_line(&mut self, dest: &str, copy: bool) {
        let dest = dest.trim();
        let label = if copy { ":copy" } else { ":move" };
        let Some(b) = self.active_editor_mut() else {
            self.toast(format!("{label} — no active editor"));
            return;
        };
        let text = b.editor.text();
        let line_count = b.editor.line_count();
        let cur_row = b.editor.row_col().0;
        // Parse destination — `+N`, `-N`, or absolute `N` (1-based; 0 = top).
        let dest_idx_signed: i64 = if let Some(rest) = dest.strip_prefix('+') {
            let n: i64 = rest.parse().unwrap_or(0);
            cur_row as i64 + n
        } else if let Some(rest) = dest.strip_prefix('-') {
            let n: i64 = rest.parse().unwrap_or(0);
            cur_row as i64 - n
        } else if dest == "$" {
            // `$` ⇒ end of buffer.
            line_count as i64
        } else if dest.is_empty() {
            self.toast(format!("{label} — destination required"));
            return;
        } else {
            match dest.parse::<i64>() {
                Ok(n) => n, // absolute (vim 1-based; 0 = top)
                Err(_) => {
                    self.toast(format!("{label} — bad destination: {dest:?}"));
                    return;
                }
            }
        };
        // Convert vim's 1-based line ref to "insert after this 0-based line"
        // semantics. `:m 0` ⇒ insert at the very top (before line 0).
        let dest_after: i64 = dest_idx_signed.clamp(0, line_count as i64);
        // Find byte ranges of the source line + the destination boundary.
        let line_start =
            |row: usize| -> usize { text.split('\n').take(row).map(|s| s.len() + 1).sum() };
        let src_start = line_start(cur_row);
        let src_end_excl_nl = src_start
            + text[src_start..]
                .find('\n')
                .unwrap_or(text.len() - src_start);
        // Destination insertion point: the start of (dest_after)th line.
        let insert_at: usize = if dest_after == 0 {
            0
        } else if (dest_after as usize) >= line_count {
            text.len()
        } else {
            line_start(dest_after as usize)
        };
        // The source line text *with* its trailing newline (so we re-insert
        // it as a complete line).
        let src_with_nl = if src_end_excl_nl < text.len() {
            text[src_start..src_end_excl_nl + 1].to_string()
        } else {
            // Last line — synthesize a trailing newline so the splice
            // preserves the line shape.
            let mut s = text[src_start..].to_string();
            if !s.ends_with('\n') {
                s.push('\n');
            }
            s
        };
        // No-op cases that vim treats as harmless.
        if !copy && (dest_after as usize == cur_row || dest_after as usize == cur_row + 1) {
            return;
        }
        // Build a single-string buffer rewrite. Cheap (one alloc).
        let new_text = if copy {
            // Copy: leave source in place, splice a duplicate at insert_at.
            let mut s = String::with_capacity(text.len() + src_with_nl.len());
            s.push_str(&text[..insert_at]);
            s.push_str(&src_with_nl);
            s.push_str(&text[insert_at..]);
            s
        } else {
            // Move: cut source first, then splice at the dest boundary
            // (translating insert_at if it sits past the cut).
            let cut_end = if src_end_excl_nl < text.len() {
                src_end_excl_nl + 1
            } else {
                text.len()
            };
            let translated_insert = if insert_at >= cut_end {
                insert_at - (cut_end - src_start)
            } else {
                insert_at
            };
            let mut s = String::with_capacity(text.len());
            s.push_str(&text[..src_start]);
            s.push_str(&text[cut_end..]);
            // Now splice src into the translated position.
            let mut out = String::with_capacity(s.len() + src_with_nl.len());
            out.push_str(&s[..translated_insert]);
            out.push_str(&src_with_nl);
            out.push_str(&s[translated_insert..]);
            out
        };
        let end = text.len();
        let ops = vec![crate::edit_op::EditOp::ReplaceRange {
            start: 0,
            end,
            text: new_text,
        }];
        let mut clip = crate::clipboard::Clipboard::new();
        b.apply_edit_ops(ops, &mut clip, 0);
        // Land cursor on the moved/copied line in its new home.
        let new_row = if copy {
            // Inserted right at insert_at — that line's row index.
            // Cursor was at cur_row; insertion shifts it if before cur_row.
            if dest_after as usize <= cur_row {
                cur_row + 1 // duplicate is above us; original shifts down
            } else {
                dest_after as usize // duplicate sits at dest_after
            }
        } else if dest_after as usize > cur_row {
            (dest_after as usize).saturating_sub(1)
        } else {
            dest_after as usize
        };
        if let Some(b) = self.active_editor_mut() {
            b.editor.place_cursor(new_row, 0);
        }
        let verb = if copy { "copied" } else { "moved" };
        self.toast(format!(
            "{label} — line {} {verb}{}",
            cur_row + 1,
            new_row + 1
        ));
    }

    /// Interpret a vim `:`-line (without the leading `:`). Anything we don't
    /// recognise is bridged to a registered command if one matches, else toasted.
    /// Apply a parsed `:%s/old/new/[flags]` (or `:s/...` for current line) to
    /// the active editor. Literal substring replace (no regex);
    /// case-insensitive when the `i` flag is set. Staged as one undo step.
    pub(super) fn run_substitute(&mut self, mut sub: Substitute) {
        let Some(idx) = self.active else {
            self.toast(":s — no active editor");
            return;
        };
        let Some(Pane::Editor(b)) = self.panes.get(idx) else {
            self.toast(":s — only works in editor panes");
            return;
        };
        // Empty find ⇒ reuse last :s find (vim canonical `:s//new/g`).
        if sub.find.is_empty() {
            if let Some(last) = self.last_substitute.as_ref() {
                sub.find = last.find.clone();
                // Inherit case-insensitivity flag from last sub if not set.
                if !sub.case_insensitive {
                    sub.case_insensitive = last.case_insensitive;
                }
            } else {
                self.toast(":s — no previous find to reuse");
                return;
            }
        }
        // Remember for vim `&` (re-run on the cursor's current line).
        self.last_substitute = Some(sub.clone());
        let text = b.editor.text().to_string();
        // Compute the byte range to operate on:
        //   - explicit `line_range` (`:5,10s/…/…/`) wins
        //   - `:%s` ⇒ whole buffer
        //   - bare `:s` ⇒ cursor's current line (vim canonical)
        let (lo, hi) = if let Some((sr, er)) = sub.line_range {
            let lines: Vec<&str> = text.split('\n').collect();
            let sr = sr.min(lines.len().saturating_sub(1));
            let er = er.min(lines.len().saturating_sub(1));
            let mut byte_off = 0usize;
            let mut start = 0usize;
            let mut end = text.len();
            for (i, line) in lines.iter().enumerate() {
                if i == sr {
                    start = byte_off;
                }
                byte_off += line.len();
                if i == er {
                    end = byte_off;
                    break;
                }
                byte_off += 1; // trailing '\n'
            }
            (start, end)
        } else if sub.whole_buffer {
            (0usize, text.len())
        } else {
            let cur = b.editor.cursor();
            let bol = text[..cur].rfind('\n').map(|i| i + 1).unwrap_or(0);
            let eol = text[bol..]
                .find('\n')
                .map(|i| bol + i)
                .unwrap_or(text.len());
            (bol, eol)
        };
        let scope = &text[lo..hi];
        // nvchad-user SEV-2 2026-07-10: `:%s/…/…/g` used to be pure
        // literal — `.`, `\d`, `\w`, `(…)`, `|` were all treated as
        // ordinary chars. Vim's `:s` is regex-first (any of those
        // meta-chars are meaningful unless escaped). Try regex first;
        // fall back to the old literal path only when regex compile
        // fails (so a stray unbalanced `[` still doesn't panic — it
        // just falls to literal, matching prior behavior).
        // Translate vim regex grammar → regex-crate grammar on the
        // find side too: `\(…\)` → `(…)`, `\|` → `|`, `\<`/`\>` → `\b`.
        // Nvchad users type these routinely and the old code treated
        // them as literal. nvchad-round-7 SEV-2.
        let translated_find = vim_pattern_to_regex(&sub.find);
        let regex_matches = crate::buffer::find_all_regex(scope, &translated_find);
        let regex_used = !regex_matches.is_empty();
        let matches: Vec<(usize, usize)> = if regex_used {
            regex_matches
        } else if sub.case_insensitive {
            crate::buffer::find_all_ci_ascii(scope, &sub.find)
        } else {
            find_all_case_sensitive(scope, &sub.find)
        }
        .into_iter()
        .map(|(s, e)| (s + lo, e + lo))
        .collect();
        // nvchad-round-12 SEV-2 2026-07-14 — vim default (no `/g`) is
        // one replacement PER LINE. When !sub.global, keep only the
        // first match on each line's start-byte. Was: mnml always
        // replaced every match, so `:s/foo/bar/` on `foo foo foo`
        // became `bar bar bar` instead of `bar foo foo`.
        let matches: Vec<(usize, usize)> = if sub.global {
            matches
        } else {
            let text_bytes = text.as_bytes();
            let line_of = |byte: usize| -> usize {
                text_bytes[..byte.min(text_bytes.len())]
                    .iter()
                    .filter(|&&b| b == b'\n')
                    .count()
            };
            let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
            let mut out = Vec::with_capacity(matches.len());
            for m in matches {
                let ln = line_of(m.0);
                if seen.insert(ln) {
                    out.push(m);
                }
            }
            out
        };
        let label = if sub.whole_buffer { ":%s" } else { ":s" };
        if matches.is_empty() {
            self.toast(format!("{label} — no match for {:?}", sub.find));
            return;
        }
        let n = matches.len();
        // `:%s/.../.../n` ⇒ count-only mode (vim canonical). Don't touch
        // the buffer; just toast the count.
        if sub.count_only {
            self.toast(format!("{label}{n} match(es) of {:?}", sub.find));
            return;
        }
        // `:%s/.../.../c` ⇒ interactive: pop the confirm overlay and walk
        // through matches one at a time. The overlay's keys do the work.
        if sub.confirm {
            // Descending order so each apply keeps earlier offsets valid;
            // we pop from the end (last match first) is *un*-vim-like, so
            // reverse to keep walk-from-top order. As replacements happen,
            // the upcoming offsets are shifted by `apply_replace_confirm`
            // since they're all strictly later in the buffer.
            let mut remaining: Vec<(usize, usize)> = matches.clone();
            remaining.reverse(); // now last match is at index 0; pop = first
            self.replace_confirm = Some(ReplaceConfirm {
                pane_id: idx,
                find: sub.find.clone(),
                replace: sub.replace.clone(),
                remaining,
                applied: 0,
                total: n,
            });
            // Place the cursor on the first match so the user sees what's
            // about to change.
            self.replace_confirm_jump_to_current();
            return;
        }
        // Choose the replacement strategy. If the regex matcher won,
        // rebuild the scope via `Regex::replace_all` so `\1`, `\2`,
        // `&`, `\0` in the replacement text expand against the capture
        // groups. nvchad-round-7 SEV-1 2026-07-11 — before this
        // fix, `\1` etc. were literal text on the wire, silently
        // destroying the match (e.g. `%s/\(foo\) \(bar\)/\2 \1/g`
        // wrote `\2 \1` on every line — actual data loss).
        //
        // Non-regex (literal / ci-ascii) matchers keep the old
        // per-match ReplaceRange fan-out — they have no capture
        // groups to expand, so the raw `sub.replace` is the right
        // text.
        let ops: Vec<crate::edit_op::EditOp> = if !regex_used {
            matches
                .into_iter()
                .rev()
                .map(|(s, e)| crate::edit_op::EditOp::ReplaceRange {
                    start: s,
                    end: e,
                    text: sub.replace.clone(),
                })
                .collect()
        } else {
            // Translate vim replacement grammar → regex-crate grammar,
            // then run one `replace_all` over the scope. Splice into
            // the buffer as a single ReplaceRange covering [lo..hi].
            let prefixed = if sub.case_insensitive {
                format!("(?i){translated_find}")
            } else {
                translated_find.clone()
            };
            match regex::Regex::new(&prefixed) {
                Ok(re) => {
                    let replacement = vim_replacement_to_regex(&sub.replace);
                    // nvchad-round-12 SEV-2 2026-07-14 — vim's `/g`
                    // extends replacement from FIRST-per-line to
                    // ALL-per-line. Was: `re.replace_all` on the whole
                    // scope ran every match regardless of the flag.
                    // Now: split by line and use `replace` (first) or
                    // `replace_all` (global) per line, then rejoin.
                    let replaced: String = scope
                        .split_inclusive('\n')
                        .map(|line| {
                            if sub.global {
                                re.replace_all(line, replacement.as_str()).into_owned()
                            } else {
                                re.replace(line, replacement.as_str()).into_owned()
                            }
                        })
                        .collect();
                    vec![crate::edit_op::EditOp::ReplaceRange {
                        start: lo,
                        end: hi,
                        text: replaced,
                    }]
                }
                Err(_) => matches
                    .into_iter()
                    .rev()
                    .map(|(s, e)| crate::edit_op::EditOp::ReplaceRange {
                        start: s,
                        end: e,
                        text: sub.replace.clone(),
                    })
                    .collect(),
            }
        };
        // Wrap the whole run in a single undo group so `u` reverts
        // all replacements in one step. nvchad-user SEV-2 S2-02
        // ("`:%s/.../.../g` is not a single undo step — needs one
        // `u` per replaced line").
        if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
            let clip = &mut self.clipboard;
            b.editor.atomic_undo(|editor| {
                for op in ops {
                    editor.apply(op, 0, clip);
                }
            });
            // Notify the LSP / persistent undo path by marking the
            // buffer dirty (the per-op apply_edit_ops path used to do
            // this; we replicate the high-level effect here).
            b.dirty = true;
        }
        // Push the new text to the LSP so diagnostics stay current.
        if let Some(Pane::Editor(b)) = self.panes.get(idx)
            && let Some(p) = b.path.clone()
        {
            let t = b.editor.text().to_string();
            self.lsp.did_change(&p, &t);
        }
        self.toast(format!("{label}{n} replacement(s)"));
    }

    pub fn run_ex_command(&mut self, line: &str) {
        // Callers land here from two paths:
        //   1. The cmdline overlay (`:term foo` typed by the user) — the
        //      leading `:` is stripped by the overlay before we see it.
        //   2. Manifest-registered integration commands whose `run`
        //      field is stored *with* the leading `:` (2026-07-03 SDK
        //      bug: `run = ":term mnml-aws-amplify"` reached here as
        //      literal `":term mnml-aws-amplify"` and got dispatched as
        //      the unknown command `":term"`).
        // Normalize both by stripping any single leading colon.
        let line = line.trim().trim_start_matches(':').trim_start();
        if line.is_empty() {
            return;
        }
        // 2026-08-01 (P3) — launcher template expansion. Any
        // `{{workspace}}`, `{{current_file}}`, etc. tokens in the
        // command get resolved to their runtime values before
        // parsing. Unknown tokens stay literal (see
        // launcher_template::expand). Zero cost when the string
        // has no `{{` — the engine early-outs on the search.
        let expanded_string;
        let line = if line.contains("{{") {
            expanded_string = crate::launcher_template::expand(line, &self.launcher_template_ctx());
            expanded_string.as_str()
        } else {
            line
        };
        // nvchad-round-10 SEV-2 2026-07-11 — `:w | e other.txt` and
        // friends. Split on ` | ` (space-pipe-space) only so we don't
        // break `:s/foo|bar/z/` or path/URL-style pipes. Recurse on
        // each part.
        if let Some(parts) = split_ex_command_chain(line) {
            for part in parts {
                self.run_ex_command(&part);
            }
            return;
        }
        // Bare number ⇒ jump to that line.
        if let Ok(n) = line.parse::<usize>() {
            if let Some(b) = self.active_editor_mut() {
                b.editor.place_cursor(n.saturating_sub(1), 0);
            }
            return;
        }
        // Leading line-range form (`:1,5d`, `:5,$y`, `:.,+3d`, `:.+1d`,
        // `:'a,'bd`, `:'<,'>d`). Mark refs (`'<letter>` / `'<` / `'>`) are
        // resolved to row numbers first; then the existing parser handles
        // numeric / `.` / `$` / `+N` / `-N` forms.
        let active_row = self
            .active_editor()
            .map(|b| b.editor.row_col().0)
            .unwrap_or(0);
        let active_line_count = self
            .active_editor()
            .map(|b| b.editor.line_count())
            .unwrap_or(1);
        let resolve_mark = |c: char| -> Option<usize> {
            let b = self.active_editor()?;
            if c == '<' || c == '>' {
                let (lo, hi) = b.editor.last_selection_rows()?;
                return Some(if c == '<' { lo } else { hi });
            }
            if c.is_ascii_uppercase() {
                self.global_marks.get(&c).map(|(_, row, _)| *row)
            } else {
                b.marks.get(&c).map(|(row, _)| *row)
            }
        };
        let expanded = expand_mark_refs(line, &resolve_mark);
        if let Some((start, end, remainder)) =
            parse_line_range(&expanded, active_row, active_line_count)
        {
            let cmd = remainder.trim();
            // Split into head + arg (`:5,10y a` → "y" + "a"). Vim
            // allows an optional register letter as the argument for
            // y / d. nvchad-user SEV-2 2026-07-11.
            let (head, arg) = match cmd.split_once(char::is_whitespace) {
                Some((h, a)) => (h, a.trim()),
                None => (cmd, ""),
            };
            // Substitute-shortcut: `s/foo/bar/g` has no whitespace,
            // so the whole thing becomes `head`. Detect the
            // `s`-followed-by-delim pattern and route to the
            // substitute arm without the whitespace-split path.
            // nvchad round 6 SEV-2 2026-07-11 regression fix.
            let is_subst_shortcut = (head.starts_with("s/")
                || head.starts_with("s#")
                || head.starts_with("s!")
                || head.starts_with("s|"))
                && arg.is_empty();
            if is_subst_shortcut {
                let synthesized = head.to_string();
                if let Some(mut sub) = parse_substitute(&synthesized) {
                    sub.whole_buffer = false;
                    sub.line_range = Some((start, end));
                    self.run_substitute(sub);
                    return;
                }
            }
            match head {
                "d" | "delete" | "del" | "de" => {
                    if !arg.is_empty()
                        && arg.len() == 1
                        && let Some(reg) = arg.chars().next()
                        && reg.is_ascii_alphabetic()
                    {
                        self.clipboard.set_pending_register(Some(reg));
                    }
                    self.delete_lines(start, end);
                    return;
                }
                "y" | "yank" | "ya" => {
                    if !arg.is_empty()
                        && arg.len() == 1
                        && let Some(reg) = arg.chars().next()
                        && reg.is_ascii_alphabetic()
                    {
                        self.clipboard.set_pending_register(Some(reg));
                    }
                    self.yank_lines(start, end);
                    return;
                }
                "j" | "join" => {
                    self.join_lines_range(start, end);
                    return;
                }
                ">" | ">>" => {
                    self.indent_lines_range(start, end, true);
                    return;
                }
                "<" | "<<" => {
                    self.indent_lines_range(start, end, false);
                    return;
                }
                // `:{range}s/…/…/[flags]` — substitute within a range.
                // Vim's canonical form. Previously only `:%s` worked.
                // nvchad-user SEV-2 2026-07-11.
                "s" | "sub" | "substitute" => {
                    // Reconstruct as `:%s<rest>` where <rest> is the
                    // /old/new/flags payload, then walk it through
                    // parse_substitute and clamp the byte range to
                    // [start_line..=end_line] inside run_substitute.
                    if let Some(sub_body) = remainder.trim().strip_prefix(head) {
                        // parse_substitute expects the leading `s`.
                        let synthesized = format!("s{sub_body}");
                        if let Some(mut sub) = parse_substitute(&synthesized) {
                            sub.whole_buffer = false;
                            sub.line_range = Some((start, end));
                            self.run_substitute(sub);
                            return;
                        }
                    }
                    self.toast(format!(":{start}..{end}s — unrecognized substitute"));
                    return;
                }
                // `:{range}sort [flags]` — sort the line range.
                // nvchad-round-9 SEV-2 2026-07-11.
                "sort" | "sor" => {
                    let flags = arg;
                    self.run_sort_lines_range(
                        start,
                        end,
                        flags.contains('u'),
                        flags.contains('r'),
                        flags.contains('i'),
                        flags.contains('n'),
                    );
                    return;
                }
                // `:{range}norm <keys>` — feed keys through the vim
                // handler once per line in the range.
                "norm" | "normal" => {
                    if arg.is_empty() {
                        self.toast(":norm — keys required");
                        return;
                    }
                    self.run_norm_range(arg, start, end);
                    return;
                }
                _ => { /* fall through to normal dispatcher */ }
            }
        }
        // `:%s/old/new/[flags]` — vim-style global substitute. (No regex; flags
        // supported: `g` replace all on each line [default — we always do all
        // matches in the whole buffer]; `i` case-insensitive; `c` confirm
        // ignored for now — applies all without prompting.)
        if let Some(sub) = parse_substitute(line) {
            self.run_substitute(sub);
            return;
        }
        // User-defined ex command resolution. `:command MyCmd <body>`
        // adds it; `:MyCmd <args>` runs `<body> <args>` as a fresh ex
        // command. Lookup is by the leading word (case-sensitive — vim
        // requires user commands to start with a capital letter, but we
        // don't enforce that).
        if let Some(first_word) = line.split_whitespace().next()
            && let Some(cmd) = self.user_ex_commands.get(first_word).cloned()
        {
            let args = line[first_word.len()..].trim();
            if let Err(reason) = cmd.nargs.check(args) {
                self.toast(format!(":{first_word}{reason}"));
                return;
            }
            let merged = if args.is_empty() {
                cmd.expansion
            } else {
                format!("{} {args}", cmd.expansion)
            };
            self.run_ex_command(&merged);
            return;
        }
        // `:g/pattern/cmd` — vim's "global" command. Runs `<cmd>` on
        // every line whose text contains `<pattern>` (literal substring,
        // case-sensitive). Reverse form `:v/pattern/cmd` runs on lines
        // that *don't* match. Lines are visited top-to-bottom; the cmd
        // runs after `place_cursor(row, 0)` so things like `:d` apply
        // to the matched line.
        if let Some(rest) = line
            .strip_prefix("g/")
            .or_else(|| line.strip_prefix("global/"))
        {
            self.run_global_cmd(rest, false);
            return;
        }
        if let Some(rest) = line
            .strip_prefix("v/")
            .or_else(|| line.strip_prefix("vglobal/"))
        {
            self.run_global_cmd(rest, true);
            return;
        }
        // `:silent <cmd>` / `:sil <cmd>` — run `<cmd>` with toasts
        // suppressed (still recorded in `:messages`). Useful for
        // chained ex commands you don't want narrating themselves.
        if let Some(rest) = line
            .strip_prefix("silent! ")
            .or_else(|| line.strip_prefix("sil! "))
            .or_else(|| line.strip_prefix("silent "))
            .or_else(|| line.strip_prefix("sil "))
        {
            // Mnml doesn't distinguish error toasts from normal toasts,
            // so `:silent` and `:silent!` behave identically.
            self.silent_depth = self.silent_depth.saturating_add(1);
            self.run_ex_command(rest);
            self.silent_depth = self.silent_depth.saturating_sub(1);
            return;
        }
        // Vim adverbs `:keepjumps <cmd>` / `:keepalt <cmd>` / `:noautocmd <cmd>`.
        // Vim uses them to suppress jumplist / alt-buffer / autocmd side effects.
        // mnml's jumplist + alt-buffer machinery aren't sophisticated enough
        // to honor these strictly — strip the adverb and run the inner cmd
        // (vim users get the chained behavior; the suppression is best-effort).
        for adverb in [
            "keepjumps ",
            "keepj ",
            "keepalt ",
            "keepa ",
            "noautocmd ",
            "noa ",
            "keepmarks ",
            "kee ",
        ] {
            if let Some(rest) = line.strip_prefix(adverb) {
                self.run_ex_command(rest);
                return;
            }
        }
        // `:%!cmd` — pipe the whole buffer through `cmd`, replace it
        // with stdout. With an active selection (no `%` prefix), filters
        // the selection only. Useful for `jq .`, `sort`, `prettier`, etc.
        if let Some(rest) = line.strip_prefix("%!") {
            self.run_filter_through_shell(rest.trim(), false);
            return;
        }
        if let Some(rest) = line.strip_prefix("'<,'>!") {
            // Vim canonical visual-range form (``:'<,'>!``) — selection-only.
            self.run_filter_through_shell(rest.trim(), true);
            return;
        }
        // `:!cmd` — fire `cmd` through the shell synchronously, toast a snippet
        // of stdout/stderr (capped) + exit status. Bounded by the harness — not
        // a substitute for opening a `:term <cmd>` pty for long-running things.
        if let Some(rest) = line.strip_prefix("!") {
            let rest = rest.trim();
            // `:!!` ⇒ repeat last `:!` command (vim canonical).
            let actual_cmd = if rest == "!" {
                let Some(last) = self.last_shell_cmd.clone() else {
                    self.toast(":!! — no previous :! command");
                    return;
                };
                last
            } else if rest.is_empty() {
                self.toast(":! — command required");
                return;
            } else {
                rest.to_string()
            };
            self.last_shell_cmd = Some(actual_cmd.clone());
            let cwd = self.active_workspace_path().to_path_buf();
            let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
            let out = std::process::Command::new(&shell)
                .arg("-c")
                .arg(&actual_cmd)
                .current_dir(&cwd)
                .output();
            match out {
                Ok(out) => {
                    let mut text = String::from_utf8_lossy(&out.stdout).to_string();
                    if text.is_empty() {
                        text = String::from_utf8_lossy(&out.stderr).to_string();
                    }
                    let text = text.trim_end().to_string();
                    let preview: String = text.chars().take(200).collect();
                    let suffix = if text.chars().count() > 200 {
                        ""
                    } else {
                        ""
                    };
                    let status = match out.status.code() {
                        Some(0) => String::new(),
                        Some(c) => format!(" [exit {c}]"),
                        None => " [killed]".to_string(),
                    };
                    if preview.is_empty() {
                        self.toast(format!(":! ok{status}"));
                    } else {
                        self.toast(format!(":! {preview}{suffix}{status}"));
                    }
                }
                Err(e) => self.toast(format!(":! — {e}")),
            }
            return;
        }
        let (cmd, rest) = match line.split_once(char::is_whitespace) {
            Some((c, r)) => (c, r.trim()),
            None => (line, ""),
        };
        match cmd {
            "w" | "write" => {
                if rest.is_empty() {
                    self.save_active();
                } else if let Some(shell_cmd) = rest.strip_prefix('!') {
                    // `:w !cmd` — pipe the buffer contents to `cmd` on
                    // stdin, toast the output. Vim canonical.
                    // nvchad-round-7 SEV-2 2026-07-11 — was
                    // "save-as filename `!cmd`" which literally
                    // created a file named `!cmd`.
                    self.write_buffer_to_shell(shell_cmd.trim());
                } else {
                    self.save_active_as(rest);
                }
            }
            // nvchad-round-12 SEV-2 2026-07-14 — `:w!` / `:write!` used
            // to be silent no-ops. Vim's `!` on write forces past a
            // read-only filesystem; mnml has no r/o concept at this
            // layer, so `!` is semantically identical to plain save
            // — but it MUST save, not silently drop the write.
            // Especially dangerous when combined with quit (a user
            // typing `:wa!` before `:qa!` under a "force everything"
            // reflex was losing writes).
            "w!" | "write!" => {
                if rest.is_empty() {
                    self.save_active();
                } else if let Some(shell_cmd) = rest.strip_prefix('!') {
                    self.write_buffer_to_shell(shell_cmd.trim());
                } else {
                    self.save_active_as(rest);
                }
            }
            "saveas" => {
                if rest.is_empty() {
                    self.toast(":saveas <path> — path required");
                } else {
                    self.save_active_as(rest);
                }
            }
            // `:q` / `:x` / `:wq` close the active PANE only. Vim
            // quits when the last pane closes; mnml shows the welcome
            // screen instead so unsaved work in OTHER mnml UI state
            // (recents, settings, the tree, AI threads) isn't blown
            // away by reflexive `ZZ` / `:q`. The explicit quit chord
            // is `:qa` / `:qall` / `Cmd+Q` for app-quit.
            //
            // 2026-06-13 nvchad-user SEV-1 / SEV-2 follow-up: closing
            // the last buffer with `ZZ` was firing `should_quit = true`
            // and exiting the app, masking any other in-flight UI.
            "q" | "quit" => {
                if self.active.is_some() && self.active_pane().is_some_and(Pane::is_dirty) {
                    // R9 nvchad SEV-3 — was "unsaved changes — use :q!
                    // to discard", the same toast for every dirty
                    // buffer with no hint about WHICH one. Add the
                    // filename so the user can jump to it and save
                    // instead of guessing which of N split panes has
                    // the modification.
                    let name = self
                        .active_pane()
                        .and_then(|p| p.as_editor())
                        .and_then(|b| b.path.as_ref())
                        .and_then(|p| p.file_name())
                        .and_then(|s| s.to_str())
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| "scratch buffer".to_string());
                    self.toast(format!("unsaved changes in {name} — use :q! to discard"));
                } else {
                    self.close_active_pane();
                    if self.panes.is_empty() {
                        self.show_welcome = true;
                    }
                }
            }
            "q!" | "quit!" => {
                self.force_close_active_pane();
                if self.panes.is_empty() {
                    self.show_welcome = true;
                }
            }
            "wq" | "x" | "xit" => {
                self.save_active();
                // After a successful save the buffer's clean, so this won't prompt.
                self.close_active_pane();
                if self.panes.is_empty() {
                    self.show_welcome = true;
                }
            }
            "wa" | "wall" => self.save_all(),
            // nvchad-round-12 SEV-2 2026-07-14 — bang variants must
            // save. Same rationale as `:w!` above.
            "wa!" | "wall!" | "w!a" => self.save_all(),
            "wqa" | "wqall" | "xa" | "xall" => {
                self.save_all();
                self.should_quit = true;
            }
            // nvchad-round-12 SEV-2 2026-07-14 — was silently
            // matching `qa!` via the fuzzy fallback (quit-only), so
            // `:wqa!` did the q!-half but silently DROPPED the write.
            // Explicit arm to save + quit.
            "wqa!" | "wqall!" | "xa!" | "xall!" => {
                self.save_all();
                self.should_quit = true;
            }
            // R6 nvchad-user SEV-1 2026-08-09 — `:qa` used to set
            // should_quit unconditionally, silently discarding unsaved
            // work. Vim's `:qa` refuses with E37 when any buffer's
            // dirty; require `:qa!` to force. Same dirty-guard shape
            // as `:q` above but walks every pane, not just the active.
            "qa" | "qall" | "quitall" => {
                if self.panes.iter().any(Pane::is_dirty) {
                    self.toast("unsaved changes — use :qa! to discard");
                } else {
                    self.should_quit = true;
                }
            }
            "qa!" | "qall!" => self.should_quit = true,
            "bd" | "bdelete" => self.close_active_pane(),
            // `:bd!` / `:bdelete!` — force-close (bypass dirty prompt).
            "bd!" | "bdelete!" => {
                if let Some(idx) = self.active {
                    self.force_close_pane(idx);
                }
            }
            // `:close` / `:clo` / `:hide` — close the active pane (vim canonical
            // "close window"). Same dirty-prompt path as `:bd` so unsaved
            // editors prompt.
            "close" | "clo" | "hide" => self.close_active_pane(),
            // `:settings` — open the settings overlay. Same as
            // `view.settings` in the palette.
            "settings" => {
                self.open_settings_overlay();
            }
            // `:commands` / `:reference` — open a scratch buffer
            // listing every registered command grouped by category.
            // Same as `view.commands_reference` in the palette.
            "commands" | "reference" => {
                let text =
                    crate::command::build_commands_reference_text_public(&self.dynamic_commands);
                self.open_scratch_with_text("[commands]".into(), text);
            }
            // `:debug.rects` — toggle the visual click-rect overlay.
            // Paints borders around every registered hit-rect so you
            // can SEE where clicks are caught vs where glyphs are
            // rendered. Bug-hunt tool added 2026-06-19 after a wide-
            // glyph cell-width mismatch off-by-one hid for hours.
            "debug.rects" => {
                self.debug_rects = !self.debug_rects;
                self.toast(if self.debug_rects {
                    "debug.rects on (toggle with `:debug.rects`)"
                } else {
                    "debug.rects off"
                });
            }
            // `:help` / `:h` — open the keymap-reference overlay.
            "help" | "h" => {
                self.toggle_help_overlay();
            }
            // `:Explore` / `:E` / `:Sex[plore]` / `:Vex[plore]` / `:Lex[plore]`
            // — vim's netrw file-explorer aliases. mnml routes them to the
            // file tree (`view.toggle_tree`) since that's the closest thing.
            "Explore" | "Ex" | "Sexplore" | "Sex" | "Vexplore" | "Vex" | "Lexplore" | "Lex" => {
                self.toggle_tree_visibility();
            }
            // `:browse edit` / `:browse e` / `:browse` — vim canonical "open a
            // file picker". Route to mnml's `Ctrl+P` file picker.
            "browse" | "bro" => {
                // `:browse edit <whatever>` → ignore the inner cmd; just open
                // the picker (vim's behavior is similar — the GUI dialog comes
                // up regardless).
                self.open_file_picker();
            }
            "bn" | "bnext" => self.next_buffer(),
            "bp" | "bprev" | "bprevious" => self.prev_buffer(),
            // Vim tab pages — each is an independent split tree.
            // `:tabn` / `:tabnext` bare cycles forward; with a count
            // jumps to absolute tab N (1-based). `:tabp` is the mirror.
            "tabn" | "tabnext" => {
                if rest.is_empty() {
                    self.tab_next();
                } else if let Ok(n) = rest.parse::<usize>() {
                    let target = if n == 0 {
                        0
                    } else {
                        (n - 1).min(self.layouts.len().saturating_sub(1))
                    };
                    self.switch_tab(target);
                } else {
                    self.toast(":tabnext — bad arg");
                }
            }
            "tabp" | "tabprev" | "tabprevious" | "tabN" | "tabNext" => {
                if rest.is_empty() {
                    self.tab_prev();
                } else if let Ok(n) = rest.parse::<usize>() {
                    // Vim: `:tabp N` goes N tabs back (wrapping).
                    let len = self.layouts.len();
                    if len > 0 {
                        let cur = self.active_layout;
                        let target = (cur + len - (n % len)) % len;
                        self.switch_tab(target);
                    }
                } else {
                    self.toast(":tabprev — bad arg");
                }
            }
            "tabfirst" | "tabfir" | "tabrewind" | "tabr" => self.tab_first(),
            "tablast" | "tabl" => self.tab_last(),
            "tabclose" | "tabc" => self.tab_close(),
            "tabonly" | "tabo" => self.tab_only(),
            "tabs" => self.tab_list(),
            "tabmove" | "tabm" => self.tab_move(rest),
            "tabreopen" | "tabundo" => self.tab_reopen(),
            // `:badd <path>` — load `<path>` as a buffer but keep focus on the
            // active pane (vim canonical "buffer-add"). Implemented as a
            // background open that reveals the prior active afterwards.
            "badd" | "ba" => {
                if rest.is_empty() {
                    self.toast(":badd <path> — path required");
                } else {
                    let prior = self.active;
                    let p = self.workspace.join(rest);
                    self.open_path(&p);
                    if let Some(idx) = prior
                        && idx < self.panes.len()
                    {
                        self.reveal_pane(idx);
                    }
                }
            }
            // `:resize +N` / `:resize -N` — adjust the active split's height
            // by N percent (10..90 clamp inside `adjust_split`). Bare
            // `:resize` toasts a hint. Vim's exact-rows form (`:resize 20`)
            // would need a screen-row→ratio conversion that we don't track
            // — skip for now.
            "resize" | "res" => {
                let s = rest.trim();
                let delta: i32 = if let Some(rest) = s.strip_prefix('+') {
                    rest.parse().unwrap_or(5)
                } else if let Some(rest) = s.strip_prefix('-') {
                    -rest.parse::<i32>().unwrap_or(5)
                } else {
                    self.toast(":resize +N or :resize -N (mnml uses ratios)");
                    return;
                };
                self.adjust_split(crate::layout::SplitDir::Vertical, delta);
            }
            "vresize" | "vert" => {
                // `:vert resize +N` / `:vert resize -N` — width adjust.
                // `vert` may be followed by `resize`; strip it.
                let s = rest
                    .strip_prefix("resize ")
                    .or_else(|| rest.strip_prefix("res "))
                    .unwrap_or(rest)
                    .trim();
                let delta: i32 = if let Some(rest) = s.strip_prefix('+') {
                    rest.parse().unwrap_or(5)
                } else if let Some(rest) = s.strip_prefix('-') {
                    -rest.parse::<i32>().unwrap_or(5)
                } else {
                    self.toast(":vert resize +N or :vert resize -N");
                    return;
                };
                self.adjust_split(crate::layout::SplitDir::Horizontal, delta);
            }
            // `:bfirst` / `:bf` / `:brewind` / `:br` — jump to the first
            // editor pane. `:blast` / `:bl` — jump to the last. Vim canonical.
            "bfirst" | "bf" | "brewind" | "br" => {
                if let Some(idx) = self.panes.iter().position(|p| matches!(p, Pane::Editor(_))) {
                    self.reveal_pane(idx);
                }
            }
            "blast" | "bl" => {
                if let Some(idx) = self
                    .panes
                    .iter()
                    .rposition(|p| matches!(p, Pane::Editor(_)))
                {
                    self.reveal_pane(idx);
                }
            }
            // `:#` / `:b#` / `:e#` / `:bu#` — switch to the alternate (most
            // recently active) buffer. Vim canonical for the `Ctrl+^` chord.
            "#" | "b#" | "e#" | "bu#" | "buffer#" => self.switch_to_last_buffer(),
            // `:undo` / `:u` and `:redo` / `:red` — vim canonical aliases for
            // a single undo / redo step (count form lives at `:earlier N` /
            // `:later N`).
            "u" | "undo" => {
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.editor
                        .apply(crate::edit_op::EditOp::Undo, 20, &mut self.clipboard);
                    b.recompute_dirty();
                    b.refresh_highlights();
                }
            }
            "red" | "redo" => {
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.editor
                        .apply(crate::edit_op::EditOp::Redo, 20, &mut self.clipboard);
                    b.recompute_dirty();
                    b.refresh_highlights();
                }
            }
            // `:redraw` / `:redr` / `:redraw!` — force a screen redraw (vim
            // canonical, useful after a sub-process scrambles the terminal).
            "redraw" | "redr" | "redraw!" => {
                self.redraw_requested = true;
            }
            // `:b <substr>` / `:buffer <substr>` — switch to the editor pane
            // whose path contains <substr> (case-insensitive). Vim convention:
            // ambiguous matches toast a hint; bare `:b` toasts a list.
            "b" | "buffer" => self.ex_buffer(rest),
            // Split commands. `:sp [path]` opens (or splits) below; `:vsp` /
            // `:vs` opens to the right. Bare form just splits the current
            // pane; with a path, splits and opens that file in the new leaf.
            "sp" | "split" => {
                self.split_active(crate::layout::SplitDir::Vertical);
                if !rest.is_empty() {
                    let p = self.workspace.join(rest);
                    self.open_path(&p);
                }
            }
            "vs" | "vsp" | "vsplit" => {
                self.split_active(crate::layout::SplitDir::Horizontal);
                if !rest.is_empty() {
                    let p = self.workspace.join(rest);
                    self.open_path(&p);
                }
            }
            // Vim `:new [file]` / `:vnew [file]` — open a new scratch
            // buffer in a horizontal / vertical split. Without this
            // arm, `:new` fuzzy-fell into `agents.new_from_pr`
            // because "new" is a substring of both the id and the
            // title of that command. nvchad-round-10 SEV-2 2026-07-12.
            // nvchad-round-11 SEV-2 2026-07-12 — was calling
            // `view.split_down` AND `view.split_new_scratch`, which
            // both split, producing 4 panes (3 duplicates + 1
            // scratch). `split_new_scratch` already splits (Vertical
            // = horizontal split visually) so drop the outer split.
            // With `[file]`, use `view.split_down` + `open_path`
            // since the split shouldn't produce a scratch first.
            "new" => {
                let path = rest.trim();
                if path.is_empty() {
                    crate::command::run("view.split_new_scratch", self);
                } else {
                    crate::command::run("view.split_down", self);
                    let p = self.workspace.join(path);
                    self.open_path(&p);
                }
            }
            "vnew" => {
                let path = rest.trim();
                if path.is_empty() {
                    // split_new_scratch defaults to a Vertical
                    // split (horizontal visually — top/bottom); for
                    // `:vnew` the vim canonical is a vertical
                    // (side-by-side) split, so split_right first
                    // then swap the scratch into that leaf.
                    crate::command::run("view.split_right", self);
                    let buf = crate::buffer::Buffer::scratch(&self.config);
                    self.panes.push(Pane::Editor(buf));
                    let new_id = self.panes.len() - 1;
                    self.reveal_pane(new_id);
                } else {
                    crate::command::run("view.split_right", self);
                    let p = self.workspace.join(path);
                    self.open_path(&p);
                }
            }
            // Vim tab pages — open a fresh tab; optional path opens it in the
            // new tab's first leaf.
            "tabnew" | "tabe" | "tabedit" => {
                if rest.is_empty() {
                    self.tab_new(None);
                } else {
                    let p = self.workspace.join(rest);
                    self.tab_new(Some(&p));
                }
            }
            // `:only` / `:on` — close every pane except the active one.
            "on" | "only" => self.close_other_panes(),
            // `:pwd` — show the workspace path (vim convention).
            "pwd" => {
                let p = self.workspace.display().to_string();
                self.toast(p);
            }
            // `:sort [u]` — sort lines (whole buffer if no selection;
            // active selection otherwise). `u` = unique (de-dupe).
            // `:m N` / `:move N` — move the cursor's current line to right
            // after line N (1-based). `N=0` moves to the top of the buffer.
            // `:m -1` moves up by one line; `:m +1` moves down by one (vim
            // canonical relative form). No selection support yet — operates
            // on the cursor's line only.
            "m" | "move" => self.run_move_or_copy_line(rest, false),
            // `:co N` / `:copy N` / `:t N` — duplicate the cursor's line and
            // place the copy after line N. Same destination semantics as `:m`.
            "co" | "copy" | "t" => self.run_move_or_copy_line(rest, true),
            // nvchad-round-9 SEV-2 2026-07-11 — `n` and `r` flags
            // were previously unparsed. `n` = numeric sort, `r` =
            // reverse. `sort!` (bang) still means reverse for the
            // vim-canonical shape.
            "sort" | "sor" => self.run_sort_lines_full(
                rest.contains('u'),
                rest.contains('r'),
                rest.contains('i'),
                rest.contains('n'),
                None,
            ),
            "sort!" => self.run_sort_lines_full(
                rest.contains('u'),
                true,
                rest.contains('i'),
                rest.contains('n'),
                None,
            ),
            // `:retab` — replace tabs with `[editor] tab_width` spaces in
            // the whole buffer.
            "retab" => {
                let prior_tab_w = self.config.editor.tab_width;
                if let Ok(n) = rest.trim().parse::<usize>()
                    && n >= 1
                {
                    self.config.editor.tab_width = n;
                }
                self.run_retab(false);
                self.config.editor.tab_width = prior_tab_w;
            }
            "retab!" => {
                let prior_tab_w = self.config.editor.tab_width;
                if let Ok(n) = rest.trim().parse::<usize>()
                    && n >= 1
                {
                    self.config.editor.tab_width = n;
                }
                self.run_retab(true);
                self.config.editor.tab_width = prior_tab_w;
            }
            // `:term` / `:terminal` — open a shell in a new split (alias for
            // `term.shell` / `Ctrl+T`).
            "term" | "terminal" => {
                if rest.trim().is_empty() {
                    self.open_shell();
                } else {
                    // `:term <cmd>` — open a one-shot pty pane running the
                    // given shell command in the active workspace.
                    //
                    // Tab-label derivation (2026-07-03):
                    //   - `:term mnml-aws-amplify` → `amplify` (strip
                    //     the `mnml-<category>-` prefix so integration
                    //     integrations show their family name, not
                    //     the noisy `mnml-aws-amplify` binary path).
                    //   - `:term npm run dev` → `npm` (first word).
                    // The manifest's own `name` field would be
                    // richer but doesn't reach `:term` — this handler
                    // is oblivious to which command line dispatched
                    // to it. Prefix-stripping gets us 90% there
                    // without threading manifest context.
                    let cmdline = rest.trim();
                    let first = cmdline.split_whitespace().next().unwrap_or("term");
                    // #1099 f/u v3 (2026-08-21) — take() the integration
                    // hint at the TOP of the handler, before the dedup
                    // early return. Was: hint was `.take()`en further
                    // down after chip lookup, but the "already open,
                    // just focus" path returned before that ran. Result:
                    // a second chip click for the same integration left
                    // the hint stashed on App, and the next unrelated
                    // hand-typed `:term <cmd>` inherited it and got
                    // mis-iconed with the stale integration's identity.
                    let hinted = self.pending_term_integration_hint.take();
                    // 2026-07-03 — if a Pty pane is already running
                    // this exact cmdline (e.g. the user clicked the
                    // Amplify chip a second time), focus it instead
                    // of splitting with a duplicate. The chip click
                    // dispatches `:term <binary>` directly to this
                    // handler, so the dedup needs to live here as
                    // well as in run_dynamic_command.
                    let existing = self.panes.iter().enumerate().find_map(|(pid, p)| {
                        let crate::pane::Pane::Pty(s) = p else {
                            return None;
                        };
                        let args_joined = s.profile.args.join(" ");
                        if args_joined.trim() == cmdline || args_joined.trim().ends_with(cmdline) {
                            Some(pid)
                        } else {
                            None
                        }
                    });
                    if let Some(pid) = existing {
                        self.active = Some(pid);
                        return;
                    }
                    // Derive a base label from the binary name:
                    //   `mnml-forge-bitbucket` → `bitbucket`
                    //   `mnml-aws-amplify`     → `amplify`
                    //   `npm run dev`          → `npm`
                    // Then title-case the last segment so the tab
                    // reads "Bitbucket" not "bitbucket" (user report
                    // 2026-07-19: "tab name needs fixed to match the
                    // app name, right now its just lowercase").
                    let raw = if let Some(rest) = first.strip_prefix("mnml-") {
                        rest.rsplit_once('-')
                            .map_or(rest, |(_, tail)| tail)
                            .to_string()
                    } else {
                        first.to_string()
                    };
                    let mut chars = raw.chars();
                    let mut label = match chars.next() {
                        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                        None => String::new(),
                    };
                    let ws = self.active_workspace_path().to_path_buf();
                    // 2026-07-19 — deterministic tab-icon: stamp
                    // the integration id (if any chip's `command`
                    // matches the ex-command we're about to run)
                    // onto the profile so pty_icon looks it up by
                    // exact id, not by substring guessing on args.
                    // The chip's `command` field is stored as
                    // ":term <binary> [args…]"; `cmdline` here is
                    // JUST the "<binary> [args…]" portion (the
                    // "term " prefix was already consumed by the
                    // outer match), so we reconstruct both forms.
                    let ex_term_form = format!(":term {}", cmdline);
                    let term_form = format!("term {}", cmdline);
                    // #1099 f/u v2 (2026-08-20) — RIGID chip binding
                    // via `pending_term_integration_hint`. When a
                    // dynamic command dispatch (chip click, palette
                    // fire, statusline segment click, keybind) set
                    // the hint on App just before invoking us, use
                    // THAT integration's chip verbatim — no
                    // guessing at exact-cmdline or binary. The hint
                    // is `.take()`en above (before the dedup early
                    // return) — see #1099 f/u v3.
                    let hinted_chip = hinted.as_deref().and_then(|id| {
                        self.config
                            .ui
                            .integration_icons
                            .iter()
                            .find(|ic| ic.id == id)
                    });
                    // Exact-string match on the chip's command is
                    // the second-tier source-of-truth (e.g. a chip
                    // clicked directly from the palette bar / rail
                    // that didn't go through run_dynamic_command).
                    let exact = self.config.ui.integration_icons.iter().find(|ic| {
                        ic.command == ex_term_form
                            || ic.command == term_form
                            || ic.command == cmdline
                    });
                    let is_exact_match = hinted_chip.is_some() || exact.is_some();
                    let integration_match = hinted_chip
                        .or(exact)
                        .map(|ic| (ic.id.clone(), ic.label.clone()));
                    // If the ex-command matches an integration chip
                    // AND that chip carries a `label`, use it as the
                    // tab label — that's the chip's human-facing name
                    // (e.g. "Bitbucket PRs"). Beats the binary-name
                    // derivation which produced "Bitbucket".
                    if let Some((_, Some(tt))) = &integration_match {
                        label = tt.clone();
                    }
                    // If the caller passed `--only <family>` and we
                    // fell back to a BINARY match (not exact), the
                    // label came from a peer chip — append a variant
                    // suffix so tabs stay visually distinct
                    // ("Bitbucket PRs" vs "Bitbucket PRs · Mine").
                    // Skipped on exact-match because the chip's own
                    // label already reflects its variant.
                    if !is_exact_match && let Some(pos) = cmdline.find("--only ") {
                        let after = &cmdline[pos + "--only ".len()..];
                        let family = after.split_whitespace().next().unwrap_or("");
                        let suffix = match family {
                            "prs-mine" | "pull_requests_mine" => Some("Mine"),
                            "prs" | "pull_requests" => Some("Pull Requests"),
                            "pipelines" => Some("Pipelines"),
                            "branches" => Some("Branches"),
                            "work" | "jira_work" => Some("Work"),
                            "fix-versions" | "fix_versions" | "fix_version" => Some("Fix Versions"),
                            "boards" | "jira_boards" => Some("Boards"),
                            _ => None,
                        };
                        if let Some(s) = suffix {
                            label = format!("{label} · {s}");
                        }
                    }
                    let mut prof = crate::pty_pane::BinaryProfile::task(&label, cmdline, ws);
                    if let Some((id, _)) = integration_match {
                        prof = prof.with_integration(id);
                    }
                    self.open_pty(prof);
                }
            }
            // `:version` — toast the build sha (formerly the bottom-right
            // statusline chip).
            "version" | "ver" => {
                self.toast(format!(
                    "mnml {} · {}",
                    env!("CARGO_PKG_VERSION"),
                    env!("MNML_GIT_SHA")
                ));
            }
            // `:welcome` — re-open the first-launch overlay. Useful as a
            // discoverability gesture after the marker has been written.
            "welcome" | "Welcome" => self.toggle_welcome(),
            "about" | "About" => self.toggle_about(),
            "Settings" => self.open_settings_overlay(),
            "ClaudeChat" | "Claude" | "claudechat" => self.open_ai_chat_prompt(),
            // `:rename` (lowercase) renames the pty session — `:Rename`
            // (capital) is the LSP-rename alias handled below.
            "rename" => self.open_rename_session_prompt(),
            // `:reg` / `:registers` — toast clipboard contents (we have a
            // single anonymous register for now). Newlines render as `↵`,
            // truncated to keep the toast short.
            // `:marks` — toast all set marks. Buffer-local (lowercase) for
            // the active editor; global (uppercase) across the workspace.
            // `:ls` / `:files` / `:buffers` — vim canonical "list buffers".
            // Opens the buffer-switcher picker (same as Ctrl+P's buffer
            // mode).
            // `:messages` / `:mes` — show the most-recent N toasts
            // (vim canonical). Joined with `↵` for the toast preview.
            "messages" | "mes" => {
                if self.message_log.is_empty() {
                    self.toast(":messages — none yet");
                } else {
                    let recent: Vec<String> =
                        self.message_log.iter().rev().take(8).cloned().collect();
                    let joined = recent.join("");
                    self.toast(format!(":mes · {joined}"));
                }
            }
            "ls" | "files" | "buffers" | "buf" => self.open_buffer_picker(),
            // fzf.vim-style aliases — wide adoption among vim users.
            "Files" => self.open_file_picker(),
            "Buffers" => self.open_buffer_picker(),
            "Rg" | "Ag" | "Lines" => {
                if rest.trim().is_empty() {
                    self.open_grep_prompt();
                } else {
                    // `:Rg foo` — run grep with the query directly.
                    self.run_workspace_grep(rest.trim().to_string());
                }
            }
            "BLines" => self.open_find_prompt(),
            "History" => {
                crate::command::run("picker.recent", self);
            }
            "Commands" => {
                crate::command::run("palette", self);
            }
            "Marks" => {
                crate::command::run("picker.marks", self);
            }
            "Snippets" => self.snippet_pick(),
            "SnippetsAll" => self.snippet_pick_all(),
            "LinkCheck" | "linkcheck" => self.run_markdown_link_check(),
            // `:Trim` — one-shot remove trailing whitespace from every line
            // in the active buffer (single edit op; one Undo restores).
            "Trim" | "trimws" => {
                if let Some(b) = self.active_editor_mut() {
                    b.apply_trim_trailing_ws();
                }
            }
            // LSP ex aliases — title-case "verbs" for vim users coming from
            // ALE / coc / nvim-lspconfig conventions.
            "Format" => {
                crate::command::run("lsp.format", self);
            }
            // `:Format!` / `:FormatExternal` — pipe through the configured
            // external formatter (prettier / rustfmt / gofmt / ruff / …)
            // instead of the LSP. Useful when the LSP doesn't support
            // formatting or has stale config.
            "Format!" | "FormatExternal" => {
                crate::command::run("editor.format_external", self);
            }
            // `:Lint` — fire the configured external linter on the
            // active buffer (background; results land on
            // `linter_diagnostics` and merge into the diagnostics pane /
            // statusline counts).
            "Lint" | "LintExternal" => {
                crate::command::run("editor.lint_external", self);
            }
            // `:Tools` / `:Mason` — open the Mason-style tools picker.
            // Shows every LSP / formatter / linter mnml looks for, with
            // ✓/✗ "is on PATH" status; Enter copies the install command
            // to the clipboard.
            "Tools" | "Mason" => {
                crate::command::run("tools.installer", self);
            }
            // DAP starter MVP — breakpoint marks only; no real adapter
            // launch yet. `:Bp` is a short alias for the toggle.
            "Breakpoint" | "ToggleBreakpoint" | "Bp" => {
                crate::command::run("dap.toggle_breakpoint", self);
            }
            "Breakpoints" | "Bps" => {
                crate::command::run("dap.list_breakpoints", self);
            }
            "BreakpointsClear" | "BpsClear" | "ClearBreakpoints" => {
                crate::command::run("dap.clear_all_breakpoints", self);
            }
            "Debug" | "Dap" | "DapRun" => {
                crate::command::run("dap.run", self);
            }
            // `:DapShow` / `:DebugPane` — open the live call-stack +
            // output pane independent of dap.run.
            "DapShow" | "DebugPane" => {
                crate::command::run("dap.show", self);
            }
            "DapTerminate" | "DapStop" => {
                crate::command::run("dap.terminate", self);
            }
            // `:LspRestart` — kill every running server; subsequent
            // `did_open` calls (e.g. opening a file in that language) spawn
            // fresh ones. "The LSP got stuck" recovery gesture.
            "LspRestart" | "LspReset" => {
                let n_before = self.lsp.server_count();
                self.lsp.restart_all();
                // Re-fire did_open for every open editor pane so the
                // language servers respawn immediately (otherwise the user
                // would have to switch buffers / save to trigger it).
                let opens: Vec<(PathBuf, String, String)> = self
                    .panes
                    .iter()
                    .filter_map(|p| match p {
                        Pane::Editor(b) => {
                            let path = b.path.clone()?;
                            let lang = b.language_ext.clone()?;
                            Some((path, lang, b.editor.text().to_string()))
                        }
                        _ => None,
                    })
                    .collect();
                for (path, _lang, text) in opens {
                    self.lsp.did_open(&path, &text);
                }
                self.toast(format!("LSP restarted ({n_before} server(s) dropped)"));
            }
            // `:LspStatus` / `:LspInfo` — toast each running server.
            "LspStatus" | "LspInfo" => {
                let servers = self.lsp.servers_running();
                if servers.is_empty() {
                    self.toast("LSP: no servers running");
                } else {
                    let lines: Vec<String> = servers
                        .iter()
                        .map(|(name, root)| {
                            let rel = root
                                .strip_prefix(&self.workspace)
                                .unwrap_or(root.as_path())
                                .to_string_lossy();
                            let rel = if rel.is_empty() { ".".into() } else { rel };
                            format!("{name} ({rel})")
                        })
                        .collect();
                    self.toast(format!("LSP: {}", lines.join(" · ")));
                }
            }
            "Hover" => self.lsp_hover(),
            "Definition" => self.lsp_goto_definition(),
            "Declaration" => self.lsp_goto_declaration(),
            "TypeDefinition" => self.lsp_goto_type_definition(),
            "Implementation" => self.lsp_goto_implementation(),
            "IncomingCalls" | "Callers" => self.lsp_incoming_calls(),
            "OutgoingCalls" | "Callees" => self.lsp_outgoing_calls(),
            "Supertypes" | "ParentTypes" => self.lsp_supertypes(),
            "Subtypes" | "ChildTypes" => self.lsp_subtypes(),
            "References" => {
                crate::command::run("lsp.references", self);
            }
            "Symbols" => {
                crate::command::run("lsp.symbols", self);
            }
            "Diagnostics" => {
                crate::command::run("lsp.diagnostics", self);
            }
            // `:lopen` / `:lclose` / `:lwindow` — vim's location list. mnml's
            // closest analog is the LSP diagnostics pane. Open it via
            // :lopen; close via :lclose. Same handler — pane toggles.
            "lopen" | "lwindow" => {
                crate::command::run("lsp.diagnostics", self);
            }
            "lclose" => {
                if let Some(i) = self
                    .panes
                    .iter()
                    .position(|p| matches!(p, Pane::Diagnostics(_)))
                {
                    self.force_close_pane(i);
                }
            }
            // `:lnext` / `:lprev` — walk the location list. Routes to
            // `lsp.next_diagnostic` / `lsp.prev_diagnostic`.
            "lnext" | "lne" => {
                crate::command::run("lsp.next_diagnostic", self);
            }
            "lprev" | "lp" | "lprevious" => {
                crate::command::run("lsp.prev_diagnostic", self);
            }
            // `:colorscheme <name>` / `:colo <name>` — vim canonical theme
            // switcher. mnml's existing `:set theme=…` does the same; this
            // is just the muscle-memory form.
            "colorscheme" | "colo" | "Theme" => {
                let name = rest.trim();
                if name.is_empty() {
                    let cur = crate::ui::theme::cur().name;
                    self.toast(format!(":colorscheme · current: {cur}"));
                } else {
                    self.set_theme(name);
                }
            }
            "Rename" => {
                crate::command::run("lsp.rename", self);
            }
            "CodeAction" | "CA" => {
                crate::command::run("lsp.code_action", self);
            }
            "QuickFix" | "QF" => {
                crate::command::run("lsp.quick_fix", self);
            }
            // Title-case git ex aliases — fugitive.vim conventions. Each
            // routes to the matching `git.*` command.
            "G" | "Git" | "Status" => {
                crate::command::run("git.status_pane", self);
            }
            "Gblame" | "Blame" => {
                crate::command::run("git.blame_toggle", self);
            }
            "Gdiff" => {
                crate::command::run("git.diff_file", self);
            }
            "Glog" | "Log" => {
                crate::command::run("git.graph", self);
            }
            "Gflog" | "FileHistory" => {
                crate::command::run("git.file_history", self);
            }
            "DiffOrig" => {
                crate::command::run("git.diff_orig", self);
            }
            // `:Diffsplit <other>` / `:Diffwith <other>` — open a diff
            // pane comparing the *active editor's buffer* against
            // `<other>` (workspace-relative). Reuses
            // DiffScope::BufferVsDisk by pointing it at `<other>`, but
            // the on-disk read is for `<other>` and the in-memory side
            // is the active buffer's text via active_editor — so the
            // helper sees the right text either way (it matches by
            // path; if the active buffer's path != <other>, we route
            // through a temp comparison).
            "Diffsplit" | "Diffwith" => {
                let other = rest.trim();
                if other.is_empty() {
                    self.toast(":Diffsplit <file> — needs a path");
                    return;
                }
                let other_path = if std::path::Path::new(other).is_absolute() {
                    std::path::PathBuf::from(other)
                } else {
                    self.workspace.join(other)
                };
                if !other_path.exists() {
                    self.toast(format!(":Diffsplit — no such file: {other}"));
                    return;
                }
                self.open_diff_buffer_vs_file(other_path);
            }
            "GBrowse" | "Gbrowse" | "Browse" => {
                if let Some(arg) = rest.split_whitespace().next() {
                    // `:GBrowse <commit>` — open the commit URL on remote.
                    // Resolve `arg` to a full SHA via `git rev-parse`.
                    let workspace = self.workspace.clone();
                    let resolved = std::process::Command::new("git")
                        .args(["rev-parse", arg])
                        .current_dir(&workspace)
                        .output()
                        .ok()
                        .filter(|o| o.status.success())
                        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                        .filter(|s| !s.is_empty());
                    match resolved.and_then(|h| crate::git::browse::commit_url(&workspace, &h)) {
                        Some(url) => {
                            open_url_external(&url);
                            self.toast(format!("{url}"));
                        }
                        None => self.toast(format!("GBrowse: cannot resolve commit {arg:?}")),
                    }
                } else {
                    crate::command::run("git.browse", self);
                }
            }
            "reveal" | "Reveal" | "Finder" => {
                crate::command::run("view.reveal_active", self);
            }
            "Todos" | "TODO" | "FIXME" | "todos" => {
                crate::command::run("project.todos", self);
            }
            // `:Stat` — toast file size on disk, mtime, line/byte counts,
            // language. Combines `:Path` + `g Ctrl+G` + disk facts.
            // `:Echo <text>` — toast the rest of the line verbatim (vim
            // canonical `:echo`). Tiny utility — useful for keymap
            // confirmation, plugin debugging.
            "Echo" | "echo" => {
                self.toast(rest.to_string());
            }
            // `:Mkdir <path>` — create the directory (+ missing parents)
            // under the workspace. Relative paths join onto self.workspace.
            // `:Capture <cmd>` — run `<cmd>` via $SHELL -c, open the
            // `:Scratch [ft]` — open a fresh scratch buffer (split below)
            // optionally tagged with a filetype for syntax highlighting.
            "Scratch" | "scratch" => {
                let ft = rest.trim();
                self.split_active(crate::layout::SplitDir::Vertical);
                let mut buf = crate::buffer::Buffer::scratch(&self.config);
                if !ft.is_empty() {
                    buf.set_language_ext(Some(ft.to_string()));
                    buf.refresh_highlights();
                }
                self.panes.push(Pane::Editor(buf));
                let new_id = self.panes.len() - 1;
                self.reveal_pane(new_id);
            }
            // combined stdout/stderr in a new scratch buffer. Useful for
            // grabbing `cargo test` output for grep/highlight without
            // launching a full pty. Cwd is the workspace.
            "Capture" | "capture" => {
                let cmd = rest.trim();
                if cmd.is_empty() {
                    self.toast(":Capture <cmd> — needs a command");
                    return;
                }
                let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
                let cwd = self.active_workspace_path().to_path_buf();
                let out = std::process::Command::new(&shell)
                    .args(["-c", cmd])
                    .current_dir(&cwd)
                    .output();
                match out {
                    Ok(o) => {
                        let mut text = String::from_utf8_lossy(&o.stdout).into_owned();
                        let err = String::from_utf8_lossy(&o.stderr);
                        if !err.trim().is_empty() {
                            if !text.is_empty() && !text.ends_with('\n') {
                                text.push('\n');
                            }
                            text.push_str("---stderr---\n");
                            text.push_str(&err);
                        }
                        let title = format!("[capture: {cmd}]");
                        self.open_scratch_with_text(title, text);
                    }
                    Err(e) => self.toast(format!("capture failed: {e}")),
                }
            }
            "Mkdir" | "mkdir" => {
                let arg = rest.trim();
                if arg.is_empty() {
                    self.toast(":Mkdir <path> — needs a path");
                } else {
                    let target = std::path::Path::new(arg);
                    let abs = if target.is_absolute() {
                        target.to_path_buf()
                    } else {
                        self.workspace.join(target)
                    };
                    match std::fs::create_dir_all(&abs) {
                        Ok(_) => {
                            self.tree.refresh();
                            self.toast(format!("mkdir: {}", abs.display()));
                        }
                        Err(e) => self.toast(format!("mkdir failed: {e}")),
                    }
                }
            }
            // `:Touch <path>` — create an empty file (creating parents).
            // `:Mv <from> <to>` — rename / move a file. Both paths
            // workspace-relative. Refuses to overwrite an existing
            // destination. Re-points any open editor pane on `<from>`
            // to `<to>` (LSP did_close + did_open are wired through
            // the existing rename flow).
            // `:Cp <from> <to>` — copy a file (workspace-relative).
            // Refuses to overwrite. Creates the parent of `<to>` if needed.
            "Cp" => self.ex_cp(rest),
            "Mv" | "mv" => self.ex_mv(rest),
            "Touch" | "touch" => self.ex_touch(rest),
            // `:Macros` — toast each recorded macro register + key count.
            // `:Macro <reg>` — replay a specific register (alt: `@<reg>` in vim).
            "Macros" => {
                if self.macro_buffer.is_empty() {
                    self.toast("no macros recorded");
                } else {
                    let mut entries: Vec<(char, usize)> = self
                        .macro_buffer
                        .iter()
                        .map(|(k, v)| (*k, v.len()))
                        .collect();
                    entries.sort_by_key(|(k, _)| *k);
                    let line: String = entries
                        .iter()
                        .map(|(k, n)| format!("@{k}={n}"))
                        .collect::<Vec<_>>()
                        .join(" ");
                    self.toast(line);
                }
            }
            "Macro" => {
                let reg = rest.trim().chars().next();
                match reg {
                    Some(c) if self.macro_buffer.contains_key(&c) => {
                        self.pending_macro_register = Some(c);
                        self.macro_replay();
                    }
                    Some(c) => self.toast(format!(":Macro — register @{c} is empty")),
                    None => self.toast(":Macro <reg> — needs a register letter"),
                }
            }
            // `:A` — alternate file. Tries common test ↔ source pairings
            // for the active file: `_test`, `.test.`, `.spec.`, `_spec`,
            // `Tests`. Strips when present, adds when absent.
            // `:Refresh` — manually rescan the file tree + git status.
            // Useful after external file ops (cloning a submodule, etc.).
            "Refresh" => {
                self.tree.refresh();
                self.git.refresh();
                self.toast("refreshed");
            }
            // `:Hidden` / `:ToggleHidden` — flip the file tree's hidden-file
            // visibility (dotfiles, `.gitignored` entries skipped by the
            // initial scan). Re-scans the tree.
            // `:Bonly` — close every editor pane except the active one.
            // Vim has `:%bd <bang>` for similar; this is the friendlier alias.
            // Dirty buffers are kept + counted (matches the tab context-menu's
            // "Close others" semantics).
            // `:Outline` / `:Toc` / `:Symbols` — open the outline pane for
            // the active file (LSP / regex / markdown symbols).
            // `:Outline` / `:Toc` — open the outline pane for the active
            // file (LSP / regex / markdown symbols). `:Symbols` already
            // opens the picker variant earlier in this match arm.
            "Outline" | "Toc" | "TOC" => {
                crate::command::run("outline.show", self);
            }
            // `:NextDirty` / `:PrevDirty` — jump to the next / previous
            // editor pane with unsaved changes. Useful when you have many
            // buffers and want to find what's still dirty before quitting.
            "NextDirty" => self.jump_dirty_pane(true),
            "PrevDirty" => self.jump_dirty_pane(false),
            // `:Wipeout <substr>` — close every editor pane whose
            // workspace-relative path contains `<substr>`. Skips dirty
            // buffers (toasts the count). Useful for "drop everything
            // under `tests/` after a refactor".
            // `:Sum` — extract every integer / decimal from the visual
            // selection (or the whole buffer when no selection) and
            // toast the count + total. Spreadsheet-y "what does this
            // column add up to" gesture.
            // `:CountMatches <pattern>` — toast the count of regex
            // matches for `<pattern>` in the active buffer (or selection).
            // Sibling to `:%s/.../.../n` but doesn't require a replacement.
            "CountMatches" | "CountMatch" => {
                let pattern = rest.trim();
                if pattern.is_empty() {
                    self.toast(":CountMatches <pattern> — needs a pattern");
                    return;
                }
                let text = self.active_editor().map(|b| {
                    if let Some((s, e)) = b.editor.selection() {
                        b.editor.text()[s..e].to_string()
                    } else {
                        b.editor.text().to_string()
                    }
                });
                let Some(text) = text else {
                    self.toast("no active editor");
                    return;
                };
                match regex::Regex::new(&format!("(?i){pattern}")) {
                    Ok(re) => {
                        let n = re.find_iter(&text).count();
                        self.toast(format!(":CountMatches /{pattern}/ — {n}"));
                    }
                    Err(e) => self.toast(format!(":CountMatches — bad regex: {e}")),
                }
            }
            // `:Messages!` — open the full toast/message log in a fresh
            // scratch buffer below. `:messages` (already wired) toasts
            // the recent 8; the bang form is "show me all 200".
            "Messages!" | "MessageLog" | "messageslog" => {
                if self.message_log.is_empty() {
                    self.toast(":Messages! — empty log");
                    return;
                }
                let text = self.message_log.join("\n");
                self.open_scratch_with_text("[messages]".into(), text);
            }
            "Sum" | "sum" => self.ex_sum(rest),
            "Wipeout" | "Wipe" => self.ex_wipeout(rest),
            "Bonly" | "bonly" => {
                if let Some(id) = self.active {
                    self.close_panes_except(Some(id));
                }
            }
            "Hidden" | "ToggleHidden" => {
                self.tree.show_hidden = !self.tree.show_hidden;
                self.tree.refresh();
                self.toast(if self.tree.show_hidden {
                    "tree: show hidden"
                } else {
                    "tree: hide hidden"
                });
            }
            "A" | "Alternate" => {
                let Some(path) = self.active_editor().and_then(|b| b.path.clone()) else {
                    self.toast(":A — no active file");
                    return;
                };
                let candidates = alternate_paths(&path);
                let hit = candidates.into_iter().find(|p| p.exists());
                match hit {
                    Some(p) => self.open_path(&p),
                    None => self.toast(":A — no alternate file found"),
                }
            }
            // `:Notes` — open / create `<workspace>/.mnml/notes.md` as
            // a workspace-local notepad. Markdown so the existing
            // highlight + preview auto-open behavior kicks in.
            // `:OpenAt <path>:<line>[:<col>]` — open the file and jump to
            // the given 1-based position. Useful for pasting in
            // `path:row:col` strings from grep / clippy / etc.
            // `:Filetypes` — toast the tree-sitter grammars / filetypes
            // mnml ships with. Helpful for "is X supported?" without
            // grepping the source.
            "Filetypes" | "filetypes" => {
                let exts = [
                    "rs", "js", "jsx", "ts", "tsx", "py", "json", "go", "toml", "css", "bash",
                    "html", "md", "c", "cpp", "rb", "java", "cs", "lua", "yaml", "scala", "ex",
                    "hs", "php", "swift", "zig", "nix", "ocaml", "dart", "sql", "make", "kt",
                    "regex",
                ];
                self.toast(format!("filetypes ({}): {}", exts.len(), exts.join(" ")));
            }
            "OpenAt" | "openat" => {
                let arg = rest.trim();
                if arg.is_empty() {
                    self.toast(":OpenAt <path>:<line>[:<col>] — needs args");
                    return;
                }
                let mut parts = arg.splitn(3, ':');
                let path_str = parts.next().unwrap_or("");
                let line = parts.next().and_then(|s| s.parse::<usize>().ok());
                let col = parts.next().and_then(|s| s.parse::<usize>().ok());
                if path_str.is_empty() || line.is_none() {
                    self.toast(":OpenAt — bad format (need <path>:<line>)");
                    return;
                }
                let path = if std::path::Path::new(path_str).is_absolute() {
                    std::path::PathBuf::from(path_str)
                } else {
                    self.workspace.join(path_str)
                };
                self.open_path(&path);
                let row = line.unwrap_or(1).saturating_sub(1);
                let c = col.unwrap_or(1).saturating_sub(1);
                if let Some(b) = self.active_editor_mut() {
                    b.editor.place_cursor(row, c);
                }
            }
            // `:Fn` — toast just the active editor's filename (no path).
            // Friendlier than `:Path` for quick "what file is this".
            "Fn" => {
                let name = self
                    .active_editor()
                    .and_then(|b| b.path.as_ref().and_then(|p| p.file_name()))
                    .map(|s| s.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "(unsaved buffer)".into());
                self.toast(name);
            }
            // `:Args` — mnml extension: list every open editor pane's
            // workspace-relative path. Lowercase `:args` is handled
            // further below as the real vim arglist (`:args`/`:next`/
            // `:prev`/`:first`/`:last`).
            "Args" => {
                let mut names: Vec<String> = self
                    .panes
                    .iter()
                    .filter_map(|p| match p {
                        Pane::Editor(b) => b.path.as_ref().map(|p| {
                            p.strip_prefix(&self.workspace)
                                .unwrap_or(p)
                                .to_string_lossy()
                                .into_owned()
                        }),
                        _ => None,
                    })
                    .collect();
                if names.is_empty() {
                    self.toast(":Args — no open files");
                } else {
                    names.sort();
                    self.toast(format!(":Args — {}", names.join(" · ")));
                }
            }
            // `:Mtime` — toast the active file's mtime (when readable).
            "Mtime" => {
                let Some(path) = self.active_editor().and_then(|b| b.path.clone()) else {
                    self.toast(":Mtime — no saved file");
                    return;
                };
                match std::fs::metadata(&path).and_then(|m| m.modified()) {
                    Ok(t) => {
                        let secs = t
                            .duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_secs() as i64)
                            .unwrap_or(0);
                        let now = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_secs() as i64)
                            .unwrap_or(0);
                        let age = crate::ui::git_graph_view::humanize_age(now.saturating_sub(secs));
                        self.toast(format!(
                            ":Mtime — {} (age {age})",
                            path.file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_default()
                        ));
                    }
                    Err(e) => self.toast(format!(":Mtime: {e}")),
                }
            }
            "Notes" | "notes" => {
                let dir = self.workspace.join(".mnml");
                if let Err(e) = std::fs::create_dir_all(&dir) {
                    self.toast(format!(":Notes: cannot create dir: {e}"));
                    return;
                }
                let path = dir.join("notes.md");
                if !path.exists() {
                    let seed = "# Workspace notes\n\n";
                    if let Err(e) = std::fs::write(&path, seed) {
                        self.toast(format!(":Notes: cannot create file: {e}"));
                        return;
                    }
                }
                self.open_path(&path);
            }
            // `:Reflow [N]` — reflow the paragraph at cursor to width N
            // (default `[editor] text_width`). Vim canonical is `gqq`;
            // this is the ex form with an optional width arg.
            "Reflow" => {
                let arg = rest.trim();
                let prev_width = self.config.editor.text_width;
                let mut restore = None;
                if !arg.is_empty()
                    && let Ok(n) = arg.parse::<usize>()
                    && n > 0
                {
                    restore = Some(prev_width);
                    self.config.editor.text_width = n;
                }
                self.reflow_paragraph_at_cursor();
                if let Some(prev) = restore {
                    self.config.editor.text_width = prev;
                }
            }
            // `:Sleep <ms>` — block the event loop for `<ms>` ms.
            // Mostly for scripting / e2e. Clamps at 10 000 ms.
            "Sleep" | "sleep" => {
                let ms = rest.trim().parse::<u64>().unwrap_or(0).min(10_000);
                if ms == 0 {
                    self.toast(":Sleep <ms> — needs a positive number");
                } else {
                    std::thread::sleep(std::time::Duration::from_millis(ms));
                }
            }
            // `:Encoding` / `:enc` — mnml is UTF-8 only. Toast for vim
            // muscle memory.
            "Encoding" | "enc" => {
                self.toast(":Encoding — utf-8 (mnml is UTF-8 only)");
            }
            // `:RootFor [path]` — toast the LSP root for `<path>` (or
            // the active buffer). Walks ancestors for Cargo.toml /
            // package.json / etc.
            "RootFor" | "rootfor" => self.ex_rootfor(rest),
            // `:Newer <N>` / `:Older <N>` — aliases for `:later` /
            // `:earlier`. Walks N undo steps forward / back.
            "Newer" => {
                let alias = format!("later {rest}");
                self.run_ex_command(&alias);
            }
            "Older" => {
                let alias = format!("earlier {rest}");
                self.run_ex_command(&alias);
            }
            // `:WordCount` / `:Wc` — count chars / words / lines in the
            // active buffer (or selection). The classic `wc -lwc` shape.
            "WordCount" | "Wc" | "wc" => {
                let text = self.active_editor().map(|b| {
                    if let Some((s, e)) = b.editor.selection() {
                        b.editor.text()[s..e].to_string()
                    } else {
                        b.editor.text().to_string()
                    }
                });
                let Some(text) = text else {
                    self.toast("no active editor");
                    return;
                };
                let lines = if text.is_empty() {
                    0
                } else {
                    text.matches('\n').count() + 1
                };
                let words = text.split_whitespace().count();
                let chars = text.chars().count();
                let bytes = text.len();
                self.toast(format!(
                    "{lines} lines · {words} words · {chars} chars · {bytes}B"
                ));
            }
            "Stat" | "stat" => {
                let Some(b) = self.active_editor() else {
                    self.toast("no active editor");
                    return;
                };
                let text = b.editor.text();
                let line_count = b.editor.line_count();
                let byte_count = text.len();
                let lang = b.language_ext.as_deref().unwrap_or("?").to_string();
                let mut on_disk = String::from("(unsaved)");
                if let Some(p) = &b.path
                    && let Ok(md) = std::fs::metadata(p)
                {
                    let bytes = md.len();
                    let kb = (bytes as f64) / 1024.0;
                    on_disk = if bytes < 1024 {
                        format!("{bytes}B")
                    } else if kb < 1024.0 {
                        format!("{kb:.1}KB")
                    } else {
                        format!("{:.1}MB", kb / 1024.0)
                    };
                }
                self.toast(format!(
                    "{line_count} lines · {byte_count}B in memory · disk={on_disk} · lang={lang}"
                ));
            }
            // `:Path` / `:pwd` already toasts workspace; `:Path` toasts the
            // active file's full path. Useful for "where is this file".
            "Path" => {
                let path = self
                    .active_editor()
                    .and_then(|b| b.path.clone())
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| "(unsaved buffer)".into());
                self.toast(path);
            }
            "Gcommit" | "Commit" => {
                crate::command::run("git.commit", self);
            }
            "Branch" | "Branches" => {
                crate::command::run("git.checkout", self);
            }
            "Stash" => {
                crate::command::run("git.stash", self);
            }
            "StashPop" => {
                crate::command::run("git.stash_pop", self);
            }
            // Playwright test aliases.
            "Test" => {
                crate::command::run("test.run_at_cursor", self);
            }
            "TestAll" => {
                crate::command::run("test.run_all", self);
            }
            "TestFile" => {
                crate::command::run("test.run_file", self);
            }
            "TestFailed" => {
                crate::command::run("test.rerun_failed", self);
            }
            "Flaky" => {
                crate::command::run("flaky.show", self);
            }
            // Git hunk navigation aliases.
            "NextHunk" | "Hnext" => {
                crate::command::run("git.jump_next_change", self);
            }
            "PrevHunk" | "Hprev" => {
                crate::command::run("git.jump_prev_change", self);
            }
            "PeekHunk" | "Hpeek" => {
                crate::command::run("git.peek_change", self);
            }
            // `:Toast <text>` — show a toast (useful for scripting / plugin
            // development / quick debugging from the cmdline).
            "Toast" => {
                if rest.trim().is_empty() {
                    self.toast(":Toast <text>");
                } else {
                    self.toast(rest.trim().to_string());
                }
            }
            // `:Maps [filter]` — toast the resolved keymap (chord → command).
            // With a filter, narrows to specs / command ids containing the
            // substring. Vim users reach for `:map`; mnml's keymap is
            // config-driven so this is read-only discovery.
            // `:wincmd <c>` — run the `Ctrl+W <c>` chord as an ex command
            // (vim canonical for "do window-cmd from cmdline"). Mirrors the
            // Prefix::Window arms in the vim handler.
            "wincmd" | "winc" => self.ex_wincmd(cmd, rest),
            "Maps" | "Keys" => self.ex_maps(rest),
            // `:diff` / `:diffs` / `:diffsplit` — open the diff pane for
            // the active file (alias for the existing `git.diff_file`
            // command). Vim users reach for `:diff` reflexively.
            "diff" | "diffs" | "diffsplit" => {
                crate::command::run("git.diff_file", self);
            }
            // `:tag <name>` — annotated tag on HEAD (or the selected graph
            // commit). Bare `:tag` opens the prompt. `:tags` lists local
            // tags. `:Tag` is a friendlier alias.
            "tag" | "Tag" => {
                let name = rest.trim();
                if name.is_empty() {
                    self.open_git_tag_prompt();
                } else {
                    let target = self.selected_graph_commit_hash();
                    match crate::git::tag::create_annotated(
                        self.active_repo_path(),
                        name,
                        name,
                        target.as_deref(),
                    ) {
                        Ok(summary) => {
                            self.after_git_change();
                            self.refresh_active_git_graph();
                            self.toast(summary);
                        }
                        Err(e) => self.toast(format!("git tag: {e}")),
                    }
                }
            }
            "tags" | "Tags" => {
                let tags = crate::git::tag::list(self.active_repo_path());
                if tags.is_empty() {
                    self.toast(":tags — none");
                } else {
                    let preview = tags
                        .iter()
                        .take(10)
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(" · ");
                    let more = if tags.len() > 10 {
                        format!(" (+{} more)", tags.len() - 10)
                    } else {
                        String::new()
                    };
                    self.toast(format!(":tags ({}) {}{}", tags.len(), preview, more));
                }
            }
            "PushTags" | "pushtags" => {
                self.run_git_push_tags();
            }
            // `:Stashes` / `:StashList` — open the stash list (pick to
            // apply, vim canon). `:StashDrop` opens the drop variant.
            "Stashes" | "StashList" | "stashlist" => {
                self.open_git_stash_list();
            }
            "StashDrop" | "stashdrop" => {
                self.open_git_stash_drop();
            }
            // `:Reflog` — open the reflog picker. Accept ⇒ open the
            // commit's diff. The dim detail column shows HEAD@{N} so
            // the user can copy it for a manual reset from a pty.
            "Reflog" | "reflog" => {
                self.open_git_reflog();
            }
            // `:execute "<str>"` / `:exe "<str>"` — strip outer quotes,
            // unescape `\\` and `\"`, run the result as a fresh ex cmd.
            // No expression eval (vim's `:execute` does string concat
            // with `.`); strict literal MVP.
            "execute" | "exe" => self.ex_execute(rest),
            // `:syntax on|off` — toggle tree-sitter highlights (master
            // switch). Off paints all editor text in the theme's
            // foreground color.
            // `:setf <name>` / `:set filetype=<name>` — override the
            // buffer's `language_ext` so the highlighter targets a
            // different grammar (`:setf rust` for a `.txt` snippet that's
            // actually code, etc.). Re-runs the highlighter immediately.
            "setf" | "setfiletype" => {
                let name = rest.trim();
                if name.is_empty() {
                    self.toast(":setf <ext>");
                } else if let Some(b) = self.active_editor_mut() {
                    b.set_language_ext(Some(name.to_string()));
                    b.refresh_highlights();
                    self.toast(format!(":setf {name}"));
                }
            }
            // `:j` / `:join` — bare form joins the current line with the
            // next (vim's `J`).
            "j" | "join" => {
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.editor.apply(
                        crate::edit_op::EditOp::JoinLines { keep_space: true },
                        20,
                        &mut self.clipboard,
                    );
                    self.toast(":j");
                }
            }
            "syntax" | "syn" => {
                let opt = rest.trim();
                match opt {
                    "on" | "" => {
                        self.config.ui.syntax = true;
                        self.toast(":syntax on");
                    }
                    "off" => {
                        self.config.ui.syntax = false;
                        self.toast(":syntax off");
                    }
                    _ => self.toast(":syntax on|off"),
                }
            }
            // `:ascii` ⇒ char info under cursor (vim canonical alias for `ga`).
            "ascii" | "asc" => self.show_char_info(),
            // `:goto N` ⇒ jump to byte N (rough — places cursor at line where
            // the byte falls). Vim canonical for byte-position navigation.
            "goto" | "go" => {
                if let Ok(target) = rest.trim().parse::<usize>()
                    && let Some(b) = self.active_editor_mut()
                {
                    let text = b.editor.text();
                    let target = target.min(text.len());
                    let row = text[..target].bytes().filter(|&c| c == b'\n').count();
                    b.editor.place_cursor(row, 0);
                    self.toast(format!(":goto {target}B → line {}", row + 1));
                }
            }
            // `:enew` / `:ene` — fresh scratch buffer in current pane.
            "enew" | "ene" => {
                let buf = crate::buffer::Buffer::scratch(&self.config);
                self.panes.push(Pane::Editor(buf));
                let new_id = self.panes.len() - 1;
                self.reveal_pane(new_id);
                self.toast(":enew");
            }
            // `:make [task]` — kick off the configured `[tasks.make]`
            // task (or the named task) in a pty pane. Vim canonical for
            // "build / test from inside the editor".
            "make" | "mak" => {
                // Vim canonical: `:make [args]` shells out to the
                // `makeprg` (default `make`) and populates quickfix.
                // mnml preserves the [tasks.<name>] override for
                // richer flows (custom cwd/env). Fallback: run
                // `make <args>` via $SHELL so vim users get the
                // expected behavior even without a config entry.
                // nvchad-round-10 SEV-2 2026-07-12.
                let args = rest.trim();
                let task_key = if args.is_empty() { "make" } else { args };
                if self.config.tasks.contains_key(task_key) {
                    self.run_task(task_key);
                } else {
                    let cmdline = if args.is_empty() {
                        "make".to_string()
                    } else {
                        format!("make {args}")
                    };
                    let cwd = self.workspace.clone();
                    let label = if args.is_empty() {
                        "make".to_string()
                    } else {
                        format!("make {args}")
                    };
                    self.open_pty(crate::pty_pane::BinaryProfile::task(&label, &cmdline, cwd));
                }
            }
            "marks" => {
                let mut parts: Vec<String> = Vec::new();
                if let Some(b) = self.active_editor() {
                    let mut local: Vec<(char, (usize, usize))> =
                        b.marks.iter().map(|(&c, &v)| (c, v)).collect();
                    local.sort_by_key(|(c, _)| *c);
                    for (c, (row, col)) in local {
                        parts.push(format!("'{c}@{}:{}", row + 1, col + 1));
                    }
                }
                let mut global: Vec<(char, &(PathBuf, usize, usize))> =
                    self.global_marks.iter().map(|(&c, v)| (c, v)).collect();
                global.sort_by_key(|(c, _)| *c);
                for (c, (path, row, _col)) in global {
                    let rel = rel_path(&self.workspace, path);
                    parts.push(format!("'{c}@{rel}:{}", row + 1));
                }
                if parts.is_empty() {
                    self.toast(":marks — none set");
                } else {
                    self.toast(format!(":marks · {}", parts.join("  ")));
                }
            }
            // `:jumps` — toast the jumplist (nav_back + nav_forward), newest
            // first. Capped to 10 entries each side so the toast stays
            // readable.
            "jumps" => self.ex_jumps(rest),
            // `:wn` / `:wnext` — write the current buffer + jump to next.
            // `:wp` / `:wprev` — write + jump to prev.
            "wn" | "wnext" => {
                self.save_active();
                self.next_buffer();
            }
            "wp" | "wprev" | "wprevious" => {
                self.save_active();
                self.prev_buffer();
            }
            // `:wa` already exists below — short alias.
            // `:d[elete]` — delete current line (vim canonical ex form
            // of `dd`). Goes through `DeleteLine` so the unnamed register
            // gets the line.
            "d" | "delete" | "de" | "del" => {
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.editor
                        .apply(crate::edit_op::EditOp::DeleteLine, 20, &mut self.clipboard);
                    // SEV-1 fix 2026-07-07 — was: `:g/pattern/d`
                    // deleted lines but never flipped `dirty`, so
                    // `:q` silently discarded the changes (data loss).
                    // The `:d` handler drives every `:g/…/d` iteration
                    // via run_ex_command, and each apply() call needs
                    // its own dirty recompute for the buffer to know
                    // the mutation happened.
                    b.recompute_dirty();
                    self.toast(":delete");
                }
            }
            // `:y[ank]` — yank current line.
            "y" | "yank" | "ya" => {
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.editor
                        .apply(crate::edit_op::EditOp::YankLine, 20, &mut self.clipboard);
                    // YankLine doesn't mutate the buffer, but recompute
                    // for consistency with the surrounding `:d`/`:put`
                    // handlers.
                    b.recompute_dirty();
                    self.toast(":yank");
                }
            }
            // `:put` / `:put!` — paste the unnamed register on the next /
            // previous line (vim canonical ex-cmd form of `p`/`P`).
            // Linewise — always inserts a new line (even if the register
            // is charwise).
            "put" | "pu" => {
                let Some(idx) = self.active else {
                    self.toast(":put — no active editor");
                    return;
                };
                // Optional register letter — `:put a` reads from
                // `"a`. nvchad round 5 SEV-2 2026-07-11.
                if !rest.is_empty()
                    && rest.len() == 1
                    && let Some(reg) = rest.chars().next()
                    && reg.is_ascii_alphabetic()
                {
                    self.clipboard.set_pending_register(Some(reg));
                }
                let s = self.clipboard.text();
                if s.is_empty() {
                    self.toast(":put — clipboard empty");
                    return;
                };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    let row = b.editor.row_col().0;
                    let line_end = b.editor.line_byte_range(row).1;
                    let insert_at = line_end;
                    let payload = format!("\n{}", s.trim_end_matches('\n'));
                    b.apply_edit_ops(
                        vec![crate::edit_op::EditOp::ReplaceRange {
                            start: insert_at,
                            end: insert_at,
                            text: payload,
                        }],
                        &mut self.clipboard,
                        0,
                    );
                    self.toast(format!(":put — inserted {}B below", s.len()));
                }
            }
            "put!" => {
                let Some(idx) = self.active else {
                    self.toast(":put! — no active editor");
                    return;
                };
                let s = self.clipboard.text();
                if s.is_empty() {
                    self.toast(":put! — clipboard empty");
                    return;
                }
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    let row = b.editor.row_col().0;
                    let line_start = b.editor.line_byte_range(row).0;
                    let payload = format!("{}\n", s.trim_end_matches('\n'));
                    b.apply_edit_ops(
                        vec![crate::edit_op::EditOp::ReplaceRange {
                            start: line_start,
                            end: line_start,
                            text: payload,
                        }],
                        &mut self.clipboard,
                        0,
                    );
                    self.toast(format!(":put! — inserted {}B above", s.len()));
                }
            }
            // `:%y` / `:%d` — yank / delete the whole buffer. Single edit
            // op so undo restores. The clipboard receives the buffer text
            // (linewise) so a subsequent `p` pastes it back as lines.
            "%y" | "%yank" => {
                let Some(b) = self.active_editor() else {
                    self.toast(":%y — no active editor");
                    return;
                };
                let text = b.editor.text().to_string();
                self.clipboard.set(text.clone(), true);
                self.toast(format!(":%y — yanked {}B", text.len()));
            }
            "%d" | "%delete" => {
                let Some(idx) = self.active else {
                    self.toast(":%d — no active editor");
                    return;
                };
                let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
                    self.toast(":%d — no active editor");
                    return;
                };
                let text = b.editor.text().to_string();
                let len = text.len();
                self.clipboard.set(text, true);
                b.apply_edit_ops(
                    vec![crate::edit_op::EditOp::ReplaceRange {
                        start: 0,
                        end: len,
                        text: String::new(),
                    }],
                    &mut self.clipboard,
                    0,
                );
                self.toast(format!(":%d — cut {len}B"));
            }
            // `:bufdo <ex>` / `:tabdo <ex>` / `:argdo <ex>` — run `<ex>`
            // for every editor pane in turn. mnml has buffers, not tabs;
            // `:tabdo` is just an alias. `:argdo` would iterate the
            // command-line argument list in vim — we treat it as bufdo
            // since mnml doesn't track an arglist.
            // `:cnext` / `:cprev` / `:cfirst` / `:clast` — quickfix
            // navigation through the most-recent grep results.
            // `:%norm <keys>` / `:norm <keys>` — for each line in the
            // range (whole buffer with `%`, selection if active, else
            // current line), place the cursor at line start and dispatch
            // each key in `<keys>` through the active vim handler. Vim's
            // killer power tool for "do this on every line".
            "norm" | "normal" => self.run_norm(rest, false),
            "%norm" | "%normal" => self.run_norm(rest, true),
            // `:earlier N` — walk N undo steps. `:earlier 5s` / `5m` / `2h` /
            // `1d` — walk back to the most recent snapshot at least that
            // wall-clock old (vim canonical; relies on the per-snapshot
            // timestamp added in this round). Bare N (no unit) is steps.
            "earlier" | "ea" => {
                let Some(idx) = self.active else { return };
                let arg = rest.trim();
                let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
                    return;
                };
                let steps = match parse_undo_age_spec(arg) {
                    Some(secs) => b.editor.undo_steps_for_age(secs),
                    None => arg.parse::<usize>().unwrap_or(1),
                };
                for _ in 0..steps {
                    b.editor
                        .apply(crate::edit_op::EditOp::Undo, 20, &mut self.clipboard);
                }
                b.recompute_dirty();
                b.refresh_highlights();
                self.toast(format!(":earlier · {steps} step(s)"));
            }
            "later" | "lat" => {
                let Some(idx) = self.active else { return };
                let arg = rest.trim();
                let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
                    return;
                };
                let steps = match parse_undo_age_spec(arg) {
                    Some(secs) => b.editor.redo_steps_for_age(secs),
                    None => arg.parse::<usize>().unwrap_or(1),
                };
                for _ in 0..steps {
                    b.editor
                        .apply(crate::edit_op::EditOp::Redo, 20, &mut self.clipboard);
                }
                b.recompute_dirty();
                b.refresh_highlights();
                self.toast(format!(":later · {steps} step(s)"));
            }
            // `:copen` / `:cclose` / `:cwin[dow]` — focus / close the
            // grep ("quickfix") pane. mnml has one such pane per session.
            // `:vimgrep <pat>` / `:grep <pat>` / `:gr` — workspace grep
            // (vim's vimgrep + Quickfix one-shot). Result lands in the
            // grep pane.
            "vimgrep" | "vim" | "grep" | "gr" => {
                let q = rest.trim();
                if q.is_empty() {
                    self.toast(":grep <pattern>");
                } else {
                    self.run_workspace_grep(q.to_string());
                }
            }
            "copen" | "cope" | "cwindow" | "cwin" => {
                // Prefer an existing Quickfix pane; fall back to Grep
                // (mnml's `:grep` populates Grep).
                if let Some(idx) = self
                    .panes
                    .iter()
                    .position(|p| matches!(p, Pane::Quickfix(_)))
                {
                    self.reveal_pane(idx);
                } else if let Some(idx) = self.panes.iter().position(|p| matches!(p, Pane::Grep(_)))
                {
                    self.reveal_pane(idx);
                } else {
                    self.toast(":copen — no quickfix / grep results yet");
                }
            }
            "cclose" | "ccl" => {
                if let Some(idx) = self
                    .panes
                    .iter()
                    .position(|p| matches!(p, Pane::Quickfix(_)))
                {
                    self.force_close_pane(idx);
                } else if let Some(idx) = self.panes.iter().position(|p| matches!(p, Pane::Grep(_)))
                {
                    self.force_close_pane(idx);
                } else {
                    self.toast(":cclose — no quickfix / grep pane");
                }
            }
            // `:cexpr <text>` — populate the quickfix list from a
            // `file:line:col:message` string (vim canonical). Each newline-
            // separated line that parses becomes one entry.
            "cexpr" | "cex" => self.ex_cexpr(rest),
            "cnext" | "cn" => self.quickfix_navigate(1),
            "cprev" | "cp" | "cN" => self.quickfix_navigate(-1),
            "cfirst" | "cfir" => self.quickfix_navigate(i32::MIN),
            "clast" | "cla" => self.quickfix_navigate(i32::MAX),
            "ccurrent" | "cc" => self.quickfix_navigate(0),
            // `:cdo <cmd>` — run `<cmd>` on every quickfix entry (jump,
            // execute, save). `:cfdo <cmd>` — same but once per unique file.
            // Vim canonical.
            "cdo" | "cfdo" => self.ex_cdo(cmd, rest),
            "bufdo" | "argdo" => self.ex_bufdo(rest),
            "tabdo" => {
                // Vim canonical: switch to each tab in turn, run the
                // command in that tab's active window, leave the
                // cursor on the last tab.
                let inner = rest.trim();
                if inner.is_empty() {
                    self.toast(":tabdo <ex-command>");
                    return;
                }
                let count = self.layouts.len();
                let inner = inner.to_string();
                for i in 0..count {
                    if i != self.active_layout {
                        self.switch_tab(i);
                    }
                    self.run_ex_command(&inner);
                }
                self.toast(format!(":tabdo · ran on {count} tab(s)"));
            }
            // `:cd <path>` — vim's "change current directory". mnml's
            // workspace is fixed for the session, so we treat this as
            // a toast-only acknowledgement (vim users get `:pwd` anyway).
            "cd" | "chdir" => {
                let path = rest.trim();
                if path.is_empty() {
                    self.toast(format!(":cd — workspace is {}", self.workspace.display()));
                } else {
                    self.toast(":cd — workspace is per-session; not changed");
                }
            }
            // `:lcd` — window-local :cd in vim. mnml has one workspace
            // per session, so both scopes collapse to the same
            // read-only acknowledgement. Aliased so vim users don't
            // hit "unknown command" every other line. nvchad-round-10
            // SEV-3 2026-07-12.
            "lcd" | "lchdir" | "tcd" | "tchdir" => {
                let path = rest.trim();
                if path.is_empty() {
                    self.toast(format!(
                        ":{cmd} — workspace is {}",
                        self.workspace.display()
                    ));
                } else {
                    self.toast(format!(
                        ":{cmd} — mnml uses one workspace per session; not changed"
                    ));
                }
            }
            // `:command <Name> <expansion>` — register a user-defined ex
            // command. `:Name <args>` runs `<expansion> <args>`. Bare
            // `:command` lists. `:delcommand <Name>` (alias `:delc`)
            // removes one. Vim canonical aliases.
            "command" | "com" => self.ex_command_def(cmd, rest),
            "delcommand" | "delc" => {
                let key = rest.trim();
                if key.is_empty() {
                    self.toast(":delcommand <Name>");
                } else if self.user_ex_commands.remove(key).is_some() {
                    self.toast(format!(":delcommand {key}"));
                } else {
                    self.toast(format!(":delcommand — no such command: {key}"));
                }
            }
            // `:ab[breviate] <key> <expansion>` — set a vim abbreviation
            // (Insert-mode word that auto-expands when followed by a
            // trigger char). Bare `:ab` lists current abbreviations.
            // `:una[bbreviate] <key>` removes one.
            "ab" | "abbreviate" => {
                let rest = rest.trim();
                if rest.is_empty() {
                    if self.config.abbreviations.is_empty() {
                        self.toast(":ab — none defined");
                    } else {
                        let mut entries: Vec<String> = self
                            .config
                            .abbreviations
                            .iter()
                            .map(|(k, v)| {
                                let preview: String = v.chars().take(20).collect();
                                let suffix = if v.chars().count() > 20 { "" } else { "" };
                                format!("{k}={preview}{suffix}")
                            })
                            .collect();
                        entries.sort();
                        self.toast(format!(":ab · {}", entries.join("  ")));
                    }
                } else if let Some((k, v)) = rest.split_once(char::is_whitespace) {
                    self.config
                        .abbreviations
                        .insert(k.trim().to_string(), v.trim().to_string());
                    self.toast(format!(":ab {} = {}", k.trim(), v.trim()));
                } else {
                    self.toast(":ab <key> <expansion>");
                }
            }
            "una" | "unab" | "unabbreviate" => {
                let key = rest.trim();
                if key.is_empty() {
                    self.toast(":una <key>");
                } else if self.config.abbreviations.remove(key).is_some() {
                    self.toast(format!(":una {key}"));
                } else {
                    self.toast(format!(":una — no abbreviation for {key}"));
                }
            }
            // `:abclear` / `:abc` — drop every abbreviation. Vim canonical.
            "abc" | "abclear" => {
                let n = self.config.abbreviations.len();
                self.config.abbreviations.clear();
                self.toast(format!(":abclear — {n} abbreviation(s) cleared"));
            }
            // `:history` / `:his` / `:hist` — toast the ex-command history
            // (oldest at the start; capped preview). Vim canonical.
            "his" | "hist" | "history" => {
                if self.ex_history.is_empty() {
                    self.toast(":history — empty");
                } else {
                    // Take the most recent N (capped) — vim's `:history` shows
                    // them indexed from oldest to newest, but the toast is
                    // bounded so newest-first reads better here.
                    let preview: Vec<String> = self
                        .ex_history
                        .iter()
                        .rev()
                        .take(20)
                        .enumerate()
                        .map(|(i, s)| format!("{}:{s}", i + 1))
                        .collect();
                    let more = if self.ex_history.len() > 20 {
                        format!(" (…{} more)", self.ex_history.len() - 20)
                    } else {
                        String::new()
                    };
                    self.toast(format!(":history · {}{more}", preview.join("  ")));
                }
            }
            "reg" | "registers" | "di" | "display" => self.ex_registers(rest),
            // `:source <path>` (alias `:so`) — re-apply a config file at
            // runtime. Layers on top of the current config (missing keys
            // keep their existing value). Rebuilds the keymap (input-style
            // / [keys.*] changes take effect) and bounces the active
            // editor's input handler if `[editor] input_style` changed.
            "source" | "so" => {
                if rest.trim().is_empty() {
                    self.toast(":source <path> — path required");
                } else {
                    let path = self.workspace.join(rest.trim());
                    if !path.exists() {
                        self.toast(format!(":source — not found: {}", path.display()));
                    } else {
                        let prior_style = self.config.editor.input_style.clone();
                        self.config.apply_file_pub(&path);
                        if self.config.editor.input_style != prior_style {
                            // Re-apply input style (rebuilds keymap +
                            // swaps every editor's handler).
                            let new_style = self.config.editor.input_style.clone();
                            self.set_input_style(&new_style);
                        } else {
                            // Keymap might have changed without an input
                            // style switch — rebuild it explicitly.
                            self.keymap = crate::input::keymap::Keymap::build(&self.config);
                        }
                        self.toast(format!(":source {}", rel_path(&self.workspace, &path)));
                    }
                }
            }
            "e" | "edit" => self.ex_edit(rest),
            // `:e!` with no arg reloads the current buffer; `:e! path`
            // force-opens `path`, discarding any unsaved edits in the
            // current buffer. nvchad-round-7 SEV-3 2026-07-11.
            //
            // nvchad-round-9 SEV-1 2026-07-11 — earlier fix just
            // cleared `dirty` before switching, which left the
            // buffer's in-memory text still modified. When the user
            // later `:b <name>` back to it, they saw modifications
            // with `dirty:false`, and `:w` wrote phantom content to
            // disk. Reload from disk BEFORE switching so the alt
            // buffer's state matches disk.
            "e!" | "edit!" => {
                if rest.is_empty() {
                    self.reload_active(true);
                } else {
                    self.reload_active(true);
                    self.ex_edit(rest);
                }
            }
            // `:r !cmd` / `:read !cmd` — fire `cmd` through the shell, splice
            // its stdout into the active editor below the cursor's line.
            // Vim convention: line is added below the *current* line, not at
            // the cursor's column. Without `!` (`:r path`) reads a file.
            "r" | "read" => self.ex_read(cmd, rest),
            // `:setlocal` — like `:set`, but only mutates the active
            // buffer's per-buffer settings (tab_width / ensure_trailing
            // _newline / trim_trailing_ws_on_save). Buffers without the
            // setting fall through silently. Vim canonical for
            // file-specific overrides without touching the global config.
            "setlocal" | "setl" => self.ex_setlocal(rest),
            "set" => self.ex_set(rest),
            // `:let @<reg> = "text"` — set a named register's contents.
            // Vim canonical. nvchad round 5 SEV-2 2026-07-11 fix.
            // Only the `@<reg>` form is implemented; general vim `let`
            // (variable assignment) isn't wired.
            "let" | "l" => {
                let r = rest.trim();
                if let Some(rest) = r.strip_prefix('@')
                    && let Some((reg_str, val_str)) = rest.split_once('=')
                {
                    let reg_str = reg_str.trim();
                    let val_str = val_str.trim();
                    // Strip surrounding matched quotes.
                    let value = val_str
                        .strip_prefix('"')
                        .and_then(|s| s.strip_suffix('"'))
                        .or_else(|| {
                            val_str
                                .strip_prefix('\'')
                                .and_then(|s| s.strip_suffix('\''))
                        })
                        .unwrap_or(val_str)
                        .to_string();
                    if reg_str.len() == 1
                        && let Some(reg) = reg_str.chars().next()
                        && reg.is_ascii_alphabetic()
                    {
                        self.clipboard.set_pending_register(Some(reg));
                        self.clipboard.set(value, false);
                        self.toast(format!(":let @{reg} — set ({} bytes)", val_str.len()));
                    } else {
                        self.toast(format!(":let @{reg_str} — only single-letter registers"));
                    }
                } else {
                    self.toast(":let — expected `:let @<reg> = \"text\"`");
                }
            }
            // `:noh` / `:nohlsearch` — clear the active buffer's find state
            // (drops the highlights). Vim convention.
            "noh" | "nohl" | "nohlsearch" => {
                if let Some(b) = self.active_editor_mut() {
                    b.find = None;
                }
            }
            // vim arglist family (`:args` / `:next` / `:prev` / `:first` /
            // `:last`). Prior to the round-7 fix `:next` fell through to
            // registered-command lookup and hit `find.next` — a footgun
            // for muscle-memory nvchad users. Implementation lives on
            // App::{arglist,arglist_index}. `:args {glob}` sets the
            // arglist; `:args` prints it; `:next`/`:prev` step; `:first`/
            // `:last` jump to endpoints.
            "args" | "ar" => {
                if rest.is_empty() {
                    self.arglist_show();
                } else {
                    self.arglist_set(rest);
                }
            }
            "delmarks" | "delm" => self.delete_marks(rest),
            "delmarks!" | "delm!" => self.delete_marks("!"),
            "next" | "ne" => self.arglist_step(1),
            "prev" | "previous" | "Ne" => self.arglist_step(-1),
            "first" | "fir" | "rew" | "rewind" => self.arglist_goto(0),
            "last" | "la" => self.arglist_step(isize::MAX),
            other => {
                // Last resort: maybe it names a registered command.
                if crate::command::registry().get(other).is_some() {
                    crate::command::run(other, self);
                    return;
                }
                // nvchad-round-12 SEV-2 2026-07-14 — reserved vim ex
                // command names that mnml doesn't yet implement. Was:
                // the fuzzy fallback below matched `:map` against
                // `editor.toggle_keyMAP` and silently flipped the
                // user out of vim mode; `:changes` matched
                // `git.commit_staged_changes`; etc. Fuzzy-resolving
                // *any* vim canonical name is a footgun — a user
                // typing a reflexive vim command should get "unknown"
                // (recoverable) rather than an integration action firing
                // by name-collision. If mnml grows a real implementation
                // for one of these, add it as an explicit arm above
                // (which shadows this list).
                const VIM_RESERVED: &[&str] = &[
                    "map",
                    "nmap",
                    "imap",
                    "vmap",
                    "xmap",
                    "cmap",
                    "smap",
                    "omap",
                    "tmap",
                    "unmap",
                    "nunmap",
                    "iunmap",
                    "vunmap",
                    "xunmap",
                    "cunmap",
                    "noremap",
                    "nnoremap",
                    "inoremap",
                    "vnoremap",
                    "xnoremap",
                    "cnoremap",
                    "changes",
                    "jumps",
                    "marks",
                    "reg",
                    "registers",
                    "buffers",
                    "ls",
                    "files",
                    "let",
                    "call",
                    "sign",
                    "signs",
                    "syntax",
                    "syn",
                    "highlight",
                    "hi",
                    "colorscheme",
                    "color",
                    "colo",
                    "cd",
                    "chdir",
                    "lcd",
                    "tcd",
                    "put",
                    "put!",
                    "verbose",
                    "silent",
                    "debug",
                    "profile",
                    "profdel",
                    "hist",
                    "history",
                ];
                if VIM_RESERVED.contains(&other) {
                    // nvchad-round-16 SEV-3 F16 2026-07-17 — `:map`
                    // (and the map/unmap/noremap family) is what
                    // vim users hit to INSPECT their bindings. Route
                    // to the cheatsheet, which shows every registered
                    // chord + command grouped by prefix — the closest
                    // mnml analog to vim's `:map` output. Other
                    // reserved names still toast "unknown".
                    if matches!(
                        other,
                        "map"
                            | "nmap"
                            | "imap"
                            | "vmap"
                            | "xmap"
                            | "cmap"
                            | "smap"
                            | "omap"
                            | "tmap"
                            | "noremap"
                            | "nnoremap"
                            | "inoremap"
                            | "vnoremap"
                            | "xnoremap"
                            | "cnoremap"
                    ) {
                        crate::command::run("view.cheatsheet", self);
                        return;
                    }
                    self.toast(format!(":{line} — unknown command"));
                    return;
                }
                // 2026-06-26 — typed text isn't a known command.
                // Fall back to the popup's highlighted match.
                // vscode-style palette behaviour: if there's an
                // obvious "what you probably meant", use it instead
                // of erroring. Fixes the "type partial → ↓ to
                // highlight → Enter fires partial" UX bug at its
                // root — callers no longer need to substitute before
                // calling run_ex_command. Recursion capped at 1 by
                // checking resolved != line.
                //
                // We use the popup's CURRENT highlighted index when
                // popup state exists (caller navigated with ↓/Tab);
                // otherwise we compute completions on-the-fly and
                // pick idx 0 (the top match). This means a fresh
                // `:ag<Enter>` (no navigation) also works.
                let resolved_opt: Option<String> = {
                    let idx_from_state = self
                        .cmdline_complete_state
                        .as_ref()
                        .and_then(|s| s.matches.get(self.cmdline_popup_selected).cloned())
                        .map(|suffix| {
                            let head = self
                                .cmdline_complete_state
                                .as_ref()
                                .map(|s| s.head.clone())
                                .unwrap_or_default();
                            format!("{head}{suffix}")
                        });
                    idx_from_state.or_else(|| {
                        crate::app::compute_cmdline_completions_for_app(self, line).and_then(
                            |state| {
                                state
                                    .matches
                                    .first()
                                    .map(|m| format!("{}{}", state.head, m))
                            },
                        )
                    })
                };
                if let Some(resolved) = resolved_opt
                    && resolved != line
                    && !resolved.trim().is_empty()
                {
                    // Clear popup state so the recursion can't loop.
                    self.cmdline_complete_state = None;
                    self.cmdline_popup_selected = 0;
                    self.run_ex_command(&resolved);
                    return;
                }
                self.toast(format!(":{line} — unknown command"));
            }
        }
    }

    fn ex_buffer(&mut self, rest: &str) {
        let q = rest.trim();
        if q.is_empty() {
            let names: Vec<String> = self
                .panes
                .iter()
                .filter_map(|p| match p {
                    Pane::Editor(b) => Some(
                        b.path
                            .as_ref()
                            .map(|pp| rel_path(&self.workspace, pp))
                            .unwrap_or_else(|| b.display_name().to_string()),
                    ),
                    _ => None,
                })
                .collect();
            if names.is_empty() {
                self.toast(":b — no buffers");
            } else {
                self.toast(format!(":b · {}", names.join("  ")));
            }
        } else {
            // nvchad-user SEV-2 2026-07-10: try numeric arg first
            // (`:b 1` is the vim-canonical form; `:ls` shows numbers,
            // NvChad's tab-line also uses 1-based indices). Only fall
            // through to name matching when it's not a number. Index
            // counts EDITOR panes only, in registration order — same
            // order the ":b" listing above prints.
            if let Ok(n) = q.parse::<usize>() {
                if n == 0 {
                    self.toast(":b — buffer numbers are 1-based");
                    return;
                }
                let editor_panes: Vec<usize> = self
                    .panes
                    .iter()
                    .enumerate()
                    .filter_map(|(idx, p)| matches!(p, Pane::Editor(_)).then_some(idx))
                    .collect();
                match editor_panes.get(n - 1) {
                    Some(&pid) => self.reveal_pane(pid),
                    None => self.toast(format!(
                        ":b — {n} out of range (1..={})",
                        editor_panes.len()
                    )),
                }
                return;
            }
            let qlc = q.to_lowercase();
            let mut hits: Vec<(usize, String)> = Vec::new();
            for (idx, p) in self.panes.iter().enumerate() {
                if let Pane::Editor(b) = p {
                    let label = b
                        .path
                        .as_ref()
                        .map(|pp| rel_path(&self.workspace, pp))
                        .unwrap_or_else(|| b.display_name().to_string());
                    if label.to_lowercase().contains(&qlc) {
                        hits.push((idx, label));
                    }
                }
            }
            match hits.len() {
                0 => self.toast(format!(":b — no match for {q:?}")),
                1 => self.reveal_pane(hits[0].0),
                _ => {
                    // Pick the one whose filename matches, else toast hint.
                    let exact = hits.iter().find(|(_, l)| {
                        std::path::Path::new(l)
                            .file_name()
                            .and_then(|s| s.to_str())
                            .map(|s| s.to_lowercase() == qlc)
                            .unwrap_or(false)
                    });
                    if let Some((idx, _)) = exact {
                        self.reveal_pane(*idx);
                    } else {
                        let labels: Vec<String> = hits.iter().map(|(_, l)| l.clone()).collect();
                        self.toast(format!(":b — ambiguous: {}", labels.join(", ")));
                    }
                }
            }
        }
    }

    fn ex_cp(&mut self, rest: &str) {
        let mut parts = rest.split_whitespace();
        let (Some(from), Some(to)) = (parts.next(), parts.next()) else {
            self.toast(":Cp <from> <to> — needs two paths");
            return;
        };
        let resolve = |p: &str| -> std::path::PathBuf {
            let path = std::path::Path::new(p);
            if path.is_absolute() {
                path.to_path_buf()
            } else {
                self.workspace.join(path)
            }
        };
        let src = resolve(from);
        let dst = resolve(to);
        if dst.exists() {
            self.toast(format!("cp refused: {} exists", dst.display()));
        } else if let Some(parent) = dst.parent()
            && !parent.exists()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            self.toast(format!("cp: cannot create parent: {e}"));
        } else if let Err(e) = std::fs::copy(&src, &dst) {
            self.toast(format!("cp failed: {e}"));
        } else {
            self.tree.refresh();
            self.toast(format!("cp: {}{}", src.display(), dst.display()));
        }
    }

    fn ex_mv(&mut self, rest: &str) {
        let mut parts = rest.split_whitespace();
        let (Some(from), Some(to)) = (parts.next(), parts.next()) else {
            self.toast(":Mv <from> <to> — needs two paths");
            return;
        };
        let resolve = |p: &str| -> std::path::PathBuf {
            let path = std::path::Path::new(p);
            if path.is_absolute() {
                path.to_path_buf()
            } else {
                self.workspace.join(path)
            }
        };
        let src = resolve(from);
        let dst = resolve(to);
        if dst.exists() {
            self.toast(format!("mv refused: {} exists", dst.display()));
        } else if let Some(parent) = dst.parent()
            && !parent.exists()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            self.toast(format!("mv: cannot create parent: {e}"));
        } else if let Err(e) = std::fs::rename(&src, &dst) {
            self.toast(format!("mv failed: {e}"));
        } else {
            // Re-point any open editor pane + notify LSP +
            // update recent_files. Same bookkeeping shape as
            // `rename_fs_entry`.
            for pane in &mut self.panes {
                if let Pane::Editor(b) = pane
                    && b.path.as_deref() == Some(src.as_path())
                {
                    b.path = Some(dst.clone());
                }
            }
            self.lsp.did_close(&src);
            let new_text = self.panes.iter().find_map(|p| match p {
                Pane::Editor(b) if b.is_at(&dst) => Some(b.editor.text().to_string()),
                _ => None,
            });
            if let Some(t) = new_text {
                self.lsp.did_open(&dst, &t);
            }
            for p in &mut self.recent_files {
                if p == &src {
                    *p = dst.clone();
                }
            }
            self.tree.refresh();
            self.toast(format!("mv: {}{}", src.display(), dst.display()));
        }
    }

    fn ex_touch(&mut self, rest: &str) {
        let arg = rest.trim();
        if arg.is_empty() {
            self.toast(":Touch <path> — needs a path");
        } else {
            let target = std::path::Path::new(arg);
            let abs = if target.is_absolute() {
                target.to_path_buf()
            } else {
                self.workspace.join(target)
            };
            let parent_ok = abs
                .parent()
                .is_none_or(|p| p.exists() || std::fs::create_dir_all(p).is_ok());
            if !parent_ok {
                self.toast("touch: parent dir create failed");
            } else {
                match std::fs::OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(false)
                    .open(&abs)
                {
                    Ok(_) => {
                        self.tree.refresh();
                        self.toast(format!("touch: {}", abs.display()));
                    }
                    Err(e) => self.toast(format!("touch failed: {e}")),
                }
            }
        }
    }

    fn ex_sum(&mut self, _rest: &str) {
        let text = self.active_editor().map(|b| {
            if let Some((s, e)) = b.editor.selection() {
                b.editor.text()[s..e].to_string()
            } else {
                b.editor.text().to_string()
            }
        });
        let Some(text) = text else {
            self.toast("no active editor");
            return;
        };
        let mut total: f64 = 0.0;
        let mut count: usize = 0;
        let mut buf = String::new();
        for c in text.chars() {
            if c.is_ascii_digit() || c == '-' || c == '.' {
                buf.push(c);
            } else {
                if !buf.is_empty()
                    && let Ok(n) = buf.parse::<f64>()
                {
                    total += n;
                    count += 1;
                }
                buf.clear();
            }
        }
        if !buf.is_empty()
            && let Ok(n) = buf.parse::<f64>()
        {
            total += n;
            count += 1;
        }
        let total_disp = if total.fract().abs() < 1e-9 {
            format!("{}", total as i64)
        } else {
            format!("{total:.4}")
        };
        self.toast(format!(":Sum — {count} number(s), total {total_disp}"));
    }

    fn ex_wipeout(&mut self, rest: &str) {
        let sub = rest.trim();
        if sub.is_empty() {
            self.toast(":Wipeout <substr> — needs a substring");
            return;
        }
        let sub_lower = sub.to_lowercase();
        let workspace = self.workspace.clone();
        let to_close: Vec<usize> = self
            .panes
            .iter()
            .enumerate()
            .filter_map(|(i, p)| match p {
                Pane::Editor(b) => {
                    let path = b.path.as_ref()?;
                    let rel = path
                        .strip_prefix(&workspace)
                        .unwrap_or(path)
                        .to_string_lossy()
                        .to_lowercase();
                    if rel.contains(&sub_lower) && !b.dirty {
                        Some(i)
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .collect();
        if to_close.is_empty() {
            self.toast(format!(":Wipeout — no clean buffers match {sub:?}"));
            return;
        }
        // Close in reverse index order so earlier indices stay
        // valid as we work backward.
        let n = to_close.len();
        for i in to_close.into_iter().rev() {
            self.close_pane(i);
        }
        self.toast(format!(":Wipeout — closed {n} buffer(s)"));
    }

    fn ex_rootfor(&mut self, rest: &str) {
        let arg = rest.trim();
        let path = if arg.is_empty() {
            self.active_editor().and_then(|b| b.path.clone())
        } else {
            let p = std::path::PathBuf::from(arg);
            if p.is_absolute() {
                Some(p)
            } else {
                Some(self.workspace.join(p))
            }
        };
        let Some(path) = path else {
            self.toast(":RootFor <path> — needs a path");
            return;
        };
        let markers = [
            "Cargo.toml",
            "package.json",
            "go.mod",
            "pyproject.toml",
            ".git",
        ];
        let mut cur = path.parent();
        let mut found: Option<std::path::PathBuf> = None;
        while let Some(dir) = cur {
            if markers.iter().any(|m| dir.join(m).exists()) {
                found = Some(dir.to_path_buf());
                break;
            }
            cur = dir.parent();
        }
        match found {
            Some(p) => self.toast(format!(":RootFor → {}", p.display())),
            None => self.toast(":RootFor — no recognized root marker"),
        }
    }

    fn ex_wincmd(&mut self, _cmd: &str, rest: &str) {
        let arg = rest.trim().chars().next();
        let cmd = match arg {
            Some('h') => Some("view.focus_left"),
            Some('l') => Some("view.focus_right"),
            Some('k') => Some("view.focus_up"),
            Some('j') => Some("view.focus_down"),
            Some('w') => Some("view.focus_next_split"),
            Some('q') | Some('c') => Some("view.close_split"),
            Some('s') => Some("view.split_down"),
            Some('v') => Some("view.split_right"),
            Some('=') => Some("view.equalize_splits"),
            Some('o') => Some("view.close_others"),
            Some('r') | Some('x') | Some('R') => Some("view.rotate_splits"),
            Some('+') => Some("view.split_grow_height"),
            Some('-') => Some("view.split_shrink_height"),
            Some('>') => Some("view.split_grow_width"),
            Some('<') => Some("view.split_shrink_width"),
            Some('H') => Some("view.move_split_left"),
            Some('L') => Some("view.move_split_right"),
            Some('K') => Some("view.move_split_up"),
            Some('J') => Some("view.move_split_down"),
            Some('p') => Some("buffer.last"),
            Some('_') => Some("view.maximize_height"),
            Some('|') => Some("view.maximize_width"),
            Some('f') => Some("view.split_open_file_under_cursor"),
            Some('d') => Some("view.split_goto_definition"),
            Some('n') => Some("view.split_new_scratch"),
            _ => None,
        };
        if let Some(id) = cmd {
            crate::command::run(id, self);
        } else {
            self.toast(":wincmd <c> — unknown chord");
        }
    }

    fn ex_maps(&mut self, rest: &str) {
        let filter = rest.trim().to_lowercase();
        let mut rows: Vec<(String, String)> = self
            .keymap
            .iter()
            .map(|(seq, id)| (crate::input::keymap::chord_seq_to_spec(seq), id.to_string()))
            .filter(|(spec, id)| {
                filter.is_empty()
                    || spec.to_lowercase().contains(&filter)
                    || id.to_lowercase().contains(&filter)
            })
            .collect();
        rows.sort();
        if rows.is_empty() {
            self.toast(format!(":Maps — no matches for {filter:?}"));
        } else {
            let preview = rows
                .iter()
                .take(20)
                .map(|(spec, id)| format!("{spec}{id}"))
                .collect::<Vec<_>>()
                .join(" · ");
            let more = if rows.len() > 20 {
                format!(" (…{} more)", rows.len() - 20)
            } else {
                String::new()
            };
            self.toast(format!(":Maps · {preview}{more}"));
        }
    }

    fn ex_execute(&mut self, rest: &str) {
        let s = rest.trim();
        let inner = if s.len() >= 2
            && ((s.starts_with('"') && s.ends_with('"'))
                || (s.starts_with('\'') && s.ends_with('\'')))
        {
            &s[1..s.len() - 1]
        } else {
            s
        };
        // Unescape `\"` → `"` and `\\` → `\`.
        let unescaped: String = {
            let mut out = String::with_capacity(inner.len());
            let mut chars = inner.chars().peekable();
            while let Some(c) = chars.next() {
                if c == '\\'
                    && let Some(&n) = chars.peek()
                {
                    match n {
                        '"' | '\\' | '\'' => {
                            chars.next();
                            out.push(n);
                            continue;
                        }
                        _ => {}
                    }
                }
                out.push(c);
            }
            out
        };
        if unescaped.is_empty() {
            self.toast(":execute — empty string");
        } else {
            self.run_ex_command(&unescaped);
        }
    }

    fn ex_jumps(&mut self, _rest: &str) {
        let back: Vec<String> = self
            .nav_back
            .iter()
            .rev()
            .take(10)
            .map(|np| {
                let rel = rel_path(&self.workspace, &np.path);
                format!("{rel}:{}", np.row + 1)
            })
            .collect();
        let fwd: Vec<String> = self
            .nav_forward
            .iter()
            .rev()
            .take(10)
            .map(|np| {
                let rel = rel_path(&self.workspace, &np.path);
                format!("{rel}:{}", np.row + 1)
            })
            .collect();
        if back.is_empty() && fwd.is_empty() {
            self.toast(":jumps — empty");
        } else {
            let b_part = if back.is_empty() {
                String::new()
            } else {
                format!("{}", back.join("  "))
            };
            let f_part = if fwd.is_empty() {
                String::new()
            } else {
                format!("{}", fwd.join("  "))
            };
            self.toast(format!(":jumps {}{}", b_part, f_part));
        }
    }

    fn ex_cexpr(&mut self, rest: &str) {
        let mut hits: Vec<crate::grep_pane::GrepHit> = Vec::new();
        for ln in rest.lines() {
            let parts: Vec<&str> = ln.splitn(4, ':').collect();
            if parts.len() < 3 {
                continue;
            }
            let Ok(line) = parts[1].parse::<u32>() else {
                continue;
            };
            let col = parts[2].parse::<u32>().ok();
            let (col, text_idx) = match col {
                Some(c) => (c, 3),
                None => (1, 2),
            };
            let path = self.workspace.join(parts[0]);
            let rel = parts[0].to_string();
            let text = parts.get(text_idx).copied().unwrap_or("").to_string();
            hits.push(crate::grep_pane::GrepHit {
                path,
                rel,
                line: line.saturating_sub(1),
                col: col.saturating_sub(1),
                text,
            });
        }
        if hits.is_empty() {
            self.toast(":cexpr — no parseable entries");
        } else {
            self.open_quickfix("cexpr", hits);
        }
    }

    fn ex_cdo(&mut self, cmd: &str, rest: &str) {
        let inner = rest.trim();
        if inner.is_empty() {
            self.toast(":cdo <ex-command>");
            return;
        }
        let per_file = cmd == "cfdo";
        let hits = self
            .panes
            .iter()
            .find_map(|p| match p {
                Pane::Quickfix(g) | Pane::Grep(g) => Some(g.hits.clone()),
                _ => None,
            })
            .unwrap_or_default();
        if hits.is_empty() {
            self.toast(":cdo — no quickfix entries");
            return;
        }
        let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
        let mut ran = 0usize;
        for hit in hits {
            if per_file && !seen.insert(hit.path.clone()) {
                continue;
            }
            self.open_path(&hit.path);
            if let Some(b) = self.active_editor_mut() {
                b.editor.place_cursor(hit.line as usize, hit.col as usize);
            }
            self.run_ex_command(inner);
            self.save_active_now();
            ran += 1;
        }
        let scope = if per_file { "unique file " } else { "" };
        self.toast(format!(":{cmd} {inner:?} — ran on {ran} {scope}entry/ies"));
    }

    fn ex_bufdo(&mut self, rest: &str) {
        let inner = rest.trim();
        if inner.is_empty() {
            self.toast(":bufdo <ex-command>");
            return;
        }
        let editor_indices: Vec<usize> = self
            .panes
            .iter()
            .enumerate()
            .filter_map(|(i, p)| {
                if matches!(p, Pane::Editor(_)) {
                    Some(i)
                } else {
                    None
                }
            })
            .collect();
        if editor_indices.is_empty() {
            self.toast(":bufdo — no editor buffers open");
            return;
        }
        let count = editor_indices.len();
        let inner = inner.to_string();
        for idx in editor_indices {
            self.reveal_pane(idx);
            self.run_ex_command(&inner);
        }
        self.toast(format!(":bufdo · ran on {count} buffer(s)"));
    }

    fn ex_command_def(&mut self, _cmd: &str, rest: &str) {
        let rest = rest.trim();
        if rest.is_empty() {
            if self.user_ex_commands.is_empty() {
                self.toast(":command — none defined");
            } else {
                let mut entries: Vec<String> = self
                    .user_ex_commands
                    .iter()
                    .map(|(k, v)| {
                        let preview: String = v.expansion.chars().take(30).collect();
                        let suffix = if v.expansion.chars().count() > 30 {
                            ""
                        } else {
                            ""
                        };
                        format!("{k}={preview}{suffix}")
                    })
                    .collect();
                entries.sort();
                self.toast(format!(":command · {}", entries.join("  ")));
            }
        } else {
            // Optional leading `-nargs=...` flag (vim canonical).
            let (nargs, rest) = if let Some(after) = rest.strip_prefix("-nargs=") {
                let (val, tail) = match after.find(char::is_whitespace) {
                    Some(i) => (&after[..i], after[i..].trim_start()),
                    None => (after, ""),
                };
                (ExCommandNargs::parse(val), tail)
            } else {
                (ExCommandNargs::Any, rest)
            };
            if let Some((name, body)) = rest.split_once(char::is_whitespace) {
                let cmd = UserExCommand {
                    expansion: body.trim().to_string(),
                    nargs,
                };
                self.user_ex_commands.insert(name.trim().to_string(), cmd);
                self.toast(format!(":command {} = {}", name.trim(), body.trim()));
            } else {
                self.toast(":command [-nargs=…] <Name> <expansion>");
            }
        }
    }

    fn ex_registers(&mut self, rest: &str) {
        let mut parts: Vec<String> = Vec::new();
        let preview = |s: &str, cap: usize| -> String {
            let mut out: String = s
                .chars()
                .take(cap)
                .map(|c| if c == '\n' { '' } else { c })
                .collect();
            if s.chars().count() > cap {
                out.push('');
            }
            out
        };
        // `:reg abc` ⇒ filter to only show the named registers in
        // the arg. Bare `:reg` shows them all. Vim canonical.
        let filter: Option<std::collections::HashSet<char>> = if rest.trim().is_empty() {
            None
        } else {
            Some(rest.chars().filter(|c| !c.is_whitespace()).collect())
        };
        let show_unnamed = filter.as_ref().map(|s| s.contains(&'"')).unwrap_or(true);
        let unnamed = self.clipboard.text();
        if show_unnamed && !unnamed.is_empty() {
            parts.push(format!("\"\"  {}", preview(&unnamed, 40)));
        }
        let mut named: Vec<(char, (String, bool))> = self
            .clipboard
            .named_registers()
            .iter()
            .map(|(c, v)| (*c, v.clone()))
            .collect();
        named.sort_by_key(|(c, _)| *c);
        for (c, (text, _linewise)) in named {
            if let Some(f) = &filter
                && !f.contains(&c)
            {
                continue;
            }
            if !text.is_empty() {
                parts.push(format!("\"{c}  {}", preview(&text, 40)));
            }
        }
        if parts.is_empty() {
            self.toast(":reg — empty");
        } else {
            self.toast(format!(":reg · {}", parts.join("  ")));
        }
    }

    fn ex_edit(&mut self, rest: &str) {
        // `:e` (bare) and `:e %` both reload the active buffer
        // (vim's `%` substitutes to the current file's path; we
        // short-circuit it). Non-empty other paths open the file.
        // `:e +N <path>` opens the file and jumps to line N (vim
        // canonical). `:e +<path>` (no N) opens at last line.
        if rest.is_empty() || rest.trim() == "%" {
            self.reload_active(false);
        } else if let Some(after_plus) = rest.strip_prefix('+') {
            let (count_part, path_part) = match after_plus.find(char::is_whitespace) {
                Some(i) => (&after_plus[..i], after_plus[i..].trim()),
                None => ("", after_plus),
            };
            let p = self.workspace.join(path_part);
            // R7 vscode-mouse SEV-2 F5 2026-08-09 — vim `:e` opens
            // the RAW editor regardless of extension. `open_path`'s
            // MdPreview / Request / image-viewer auto-routing is for
            // tree-clicks and picker-opens; a user typing `:e foo.md`
            // means "edit the text", not "render the markdown".
            self.open_path_force_editor(&p);
            let line = if count_part.is_empty() {
                self.active_editor()
                    .map(|b| b.editor.line_count())
                    .unwrap_or(1)
            } else {
                count_part.parse::<usize>().unwrap_or(1).max(1)
            };
            if let Some(b) = self.active_editor_mut() {
                b.editor.place_cursor(line.saturating_sub(1), 0);
            }
        } else {
            let p = self.workspace.join(rest);
            self.open_path_force_editor(&p);
        }
    }

    fn ex_read(&mut self, _cmd: &str, rest: &str) {
        if let Some(rest) = rest.strip_prefix('!') {
            let rest = rest.trim();
            if rest.is_empty() {
                self.toast(":read ! — command required");
            } else {
                let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
                let cwd = self.active_workspace_path().to_path_buf();
                let out = std::process::Command::new(&shell)
                    .arg("-c")
                    .arg(rest)
                    .current_dir(&cwd)
                    .output();
                match out {
                    Ok(out) => {
                        let body = String::from_utf8_lossy(&out.stdout).to_string();
                        let body = body.trim_end_matches('\n').to_string();
                        let Some(idx) = self.active else {
                            self.toast(":r ! — no active editor");
                            return;
                        };
                        let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
                            self.toast(":r ! — no active editor");
                            return;
                        };
                        let line_no = b.editor.row_col().0;
                        let eol = b.editor.line_byte_range(line_no).1;
                        let payload = format!("\n{body}");
                        let payload_len = payload.len();
                        b.apply_edit_ops(
                            vec![crate::edit_op::EditOp::ReplaceRange {
                                start: eol,
                                end: eol,
                                text: payload,
                            }],
                            &mut self.clipboard,
                            0,
                        );
                        self.toast(format!(":r ! — inserted {payload_len}B"));
                    }
                    Err(e) => self.toast(format!(":r ! — {e}")),
                }
            }
        } else if rest.is_empty() {
            self.toast(":r — path or `!cmd` required");
        } else {
            // `:r <path>` — splice file contents below the cursor.
            let path = if std::path::Path::new(rest).is_absolute() {
                std::path::PathBuf::from(rest)
            } else {
                self.workspace.join(rest)
            };
            match std::fs::read_to_string(&path) {
                Ok(body) => {
                    let body = body.trim_end_matches('\n').to_string();
                    let Some(idx) = self.active else {
                        self.toast(":r — no active editor");
                        return;
                    };
                    let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
                        self.toast(":r — no active editor");
                        return;
                    };
                    let line_no = b.editor.row_col().0;
                    let eol = b.editor.line_byte_range(line_no).1;
                    let payload = format!("\n{body}");
                    let payload_len = payload.len();
                    b.apply_edit_ops(
                        vec![crate::edit_op::EditOp::ReplaceRange {
                            start: eol,
                            end: eol,
                            text: payload,
                        }],
                        &mut self.clipboard,
                        0,
                    );
                    self.toast(format!(":r — inserted {payload_len}B"));
                }
                Err(e) => self.toast(format!(":r — {e}")),
            }
        }
    }

    fn ex_setlocal(&mut self, rest: &str) {
        let opt = rest.trim();
        let Some(idx) = self.active else {
            self.toast(":setlocal — no active editor");
            return;
        };
        let Some(Pane::Editor(b)) = self.panes.get_mut(idx) else {
            self.toast(":setlocal — no active editor");
            return;
        };
        if let Some(v) = opt
            .strip_prefix("tab_width=")
            .or_else(|| opt.strip_prefix("tabstop="))
            .or_else(|| opt.strip_prefix("ts="))
            .or_else(|| opt.strip_prefix("shiftwidth="))
            .or_else(|| opt.strip_prefix("sw="))
            .or_else(|| opt.strip_prefix("softtabstop="))
            .or_else(|| opt.strip_prefix("sts="))
        {
            if let Ok(n) = v.trim().parse::<usize>() {
                b.editor.set_tab_width(n);
                self.toast(format!(":setlocal tab_width={n}"));
            } else {
                self.toast(format!(":setlocal tab_width={v} — not a number"));
            }
        } else if matches!(opt, "eol" | "endofline") {
            b.ensure_trailing_newline = true;
            self.toast(":setlocal eol");
        } else if matches!(opt, "noeol" | "noendofline") {
            b.ensure_trailing_newline = false;
            self.toast(":setlocal noeol");
        } else if matches!(opt, "trim" | "trim_trailing_whitespace") {
            b.trim_trailing_ws_on_save = true;
            self.toast(":setlocal trim");
        } else if matches!(opt, "notrim" | "notrim_trailing_whitespace") {
            b.trim_trailing_ws_on_save = false;
            self.toast(":setlocal notrim");
        } else if matches!(opt, "readonly" | "ro") {
            b.read_only = true;
            self.toast(":setlocal readonly");
        } else if matches!(opt, "noreadonly" | "noro" | "modifiable") {
            b.read_only = false;
            self.toast(":setlocal modifiable");
        } else if matches!(opt, "readonly!" | "invreadonly") {
            b.read_only = !b.read_only;
            let label = if b.read_only {
                "readonly"
            } else {
                "modifiable"
            };
            self.toast(format!(":setlocal {label}"));
        } else {
            self.toast(format!(":setlocal — unknown option: {opt}"));
        }
    }

    fn ex_set(&mut self, rest: &str) {
        // `:set` (bare) → list every option's current value as a toast.
        // `:set input=vim|standard` · `:set theme=…` · `:set tab_width=N`
        // · `:set [no]relativenumber` / `[no]list` (toggle suffix `!`).
        let opt = rest.trim();
        if opt.is_empty() {
            let cfg = &self.config;
            let theme = crate::ui::theme::cur().name;
            self.toast(format!(
                "input={} · theme={theme} · tab_width={} · {} · {} · {}",
                cfg.editor.input_style,
                cfg.editor.tab_width,
                if cfg.ui.relative_line_numbers {
                    "relativenumber"
                } else {
                    "norelativenumber"
                },
                if cfg.ui.show_whitespace {
                    "list"
                } else {
                    "nolist"
                },
                if cfg.ui.bracket_rainbow {
                    "rainbow"
                } else {
                    "norainbow"
                },
            ));
        } else if let Some(v) = rest.strip_prefix("input=") {
            self.set_input_style(v.trim());
        } else if let Some(v) = rest
            .strip_prefix("bufferline_diag_style=")
            .or_else(|| rest.strip_prefix("buf_diag="))
        {
            let normalized = v.trim().to_ascii_lowercase();
            if matches!(normalized.as_str(), "count" | "dot" | "off") {
                self.config.ui.bufferline_diag_style = normalized.clone();
                let _ =
                    crate::app::discovery::persist_ui_string("bufferline_diag_style", &normalized);
                self.toast(format!("bufferline_diag_style: {normalized}"));
            } else {
                self.toast(format!(
                    "bufferline_diag_style: unknown value \"{v}\" — try count/dot/off"
                ));
            }
        } else if let Some(v) = rest.strip_prefix("theme=") {
            self.set_theme(v.trim());
        } else if let Some(v) = rest
            .strip_prefix("filetype=")
            .or_else(|| rest.strip_prefix("ft="))
        {
            let name = v.trim().to_string();
            if let Some(b) = self.active_editor_mut() {
                b.set_language_ext(Some(name.clone()));
                b.refresh_highlights();
                self.toast(format!(":set filetype={name}"));
            }
        } else if let Some(v) = rest
            .strip_prefix("tab_width=")
            .or_else(|| rest.strip_prefix("tabstop="))
            .or_else(|| rest.strip_prefix("ts="))
            .or_else(|| rest.strip_prefix("shiftwidth="))
            .or_else(|| rest.strip_prefix("sw="))
            .or_else(|| rest.strip_prefix("softtabstop="))
            .or_else(|| rest.strip_prefix("sts="))
        {
            // Vim has separate tabstop / shiftwidth / softtabstop knobs;
            // mnml has one (`tab_width`). All aliases route to the same
            // setter — close enough for the vim users who set them all
            // to the same value anyway.
            if let Ok(n) = v.trim().parse::<usize>() {
                self.set_tab_width(n);
            } else {
                self.toast(format!(":set tab_width={v} — not a number"));
            }
        } else if let Some(v) = rest
            .strip_prefix("colorcolumn=")
            .or_else(|| rest.strip_prefix("cc="))
        {
            let s = v.trim();
            if s.is_empty() {
                self.set_color_column(0);
            } else if let Ok(n) = s.parse::<usize>() {
                self.set_color_column(n);
            } else {
                self.toast(format!(":set colorcolumn={v} — not a number"));
            }
        } else if let Some(v) = rest
            .strip_prefix("scrolloff=")
            .or_else(|| rest.strip_prefix("so="))
        {
            if let Ok(n) = v.trim().parse::<usize>() {
                self.config.ui.scrolloff = n;
                self.toast(format!("scrolloff: {n}"));
            } else {
                self.toast(format!(":set scrolloff={v} — not a number"));
            }
        } else if let Some(v) = rest
            .strip_prefix("sidescrolloff=")
            .or_else(|| rest.strip_prefix("siso="))
        {
            if let Ok(n) = v.trim().parse::<usize>() {
                self.config.ui.sidescrolloff = n;
                self.toast(format!("sidescrolloff: {n}"));
            } else {
                self.toast(format!(":set sidescrolloff={v} — not a number"));
            }
        } else if let Some(v) = rest.strip_prefix("text_width=") {
            if let Ok(n) = v.trim().parse::<usize>() {
                self.config.editor.text_width = n.max(8);
                self.toast(format!("text_width: {}", self.config.editor.text_width));
            } else {
                self.toast(format!(":set text_width={v} — not a number"));
            }
        } else if matches!(opt, "endofline" | "eol") {
            self.config.editor.ensure_trailing_newline = true;
            self.toast("ensure_trailing_newline: on");
        } else if matches!(opt, "noendofline" | "noeol") {
            self.config.editor.ensure_trailing_newline = false;
            self.toast("ensure_trailing_newline: off");
        } else if matches!(opt, "breadcrumb") {
            self.set_breadcrumb(true);
        } else if matches!(opt, "nobreadcrumb") {
            self.set_breadcrumb(false);
        } else if matches!(opt, "breadcrumb!" | "invbreadcrumb") {
            self.toggle_breadcrumb();
        } else if matches!(opt, "autopair" | "ap") {
            self.set_auto_pair(true);
        } else if matches!(opt, "noautopair" | "noap") {
            self.set_auto_pair(false);
        } else if matches!(opt, "autopair!" | "invautopair") {
            self.toggle_auto_pair();
        } else if matches!(opt, "rightpanel" | "right_panel" | "rp") {
            // vim convention: `:set foo` enables idempotently;
            // `:set foo!` toggles. vscode-user-keyboard SEV-3.
            self.right_panel_visible = true;
            self.toast("right_panel: on");
        } else if matches!(
            opt,
            "rightpanel!" | "right_panel!" | "rp!" | "invrightpanel"
        ) {
            self.right_panel_visible = !self.right_panel_visible;
            // code-reviewer 2026-06-28 W-1: parity with
            // view.toggle_right_panel — drain hosted panes when
            // hiding so they don't ghost in the bufferline.
            if !self.right_panel_visible {
                self.close_right_panel_hosted_panes();
            }
            self.toast(format!(
                "right_panel: {}",
                if self.right_panel_visible {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "norightpanel" | "noright_panel" | "norp") {
            self.right_panel_visible = false;
            self.close_right_panel_hosted_panes();
            self.toast("right_panel: off");
        } else if matches!(opt, "hoverhelp" | "hover_help" | "hh") {
            self.config.ui.hover_help = true;
            let _ = crate::app::discovery::persist_ui_bool("hover_help", true);
            self.toast("hover_help: on");
        } else if matches!(opt, "nohoverhelp" | "nohover_help" | "nohh") {
            self.config.ui.hover_help = false;
            let _ = crate::app::discovery::persist_ui_bool("hover_help", false);
            self.toast("hover_help: off");
        } else if matches!(opt, "hovertooltip" | "hover_tooltip" | "ht") {
            self.config.ui.hover_tooltip = true;
            let _ = crate::app::discovery::persist_ui_bool("hover_tooltip", true);
            self.toast("hover_tooltip: on");
        } else if matches!(opt, "nohovertooltip" | "nohover_tooltip" | "noht") {
            self.config.ui.hover_tooltip = false;
            let _ = crate::app::discovery::persist_ui_bool("hover_tooltip", false);
            self.toast("hover_tooltip: off");
        } else if matches!(opt, "wsdots" | "workspacedots" | "workspace_dots") {
            self.set_workspace_dots(true);
        } else if matches!(opt, "nowsdots" | "noworkspacedots" | "noworkspace_dots") {
            self.set_workspace_dots(false);
        } else if matches!(
            opt,
            "wsdots!" | "workspacedots!" | "workspace_dots!" | "invwsdots"
        ) {
            self.toggle_workspace_dots();
        } else if matches!(opt, "syncnormalize" | "sync_normalize" | "sn") {
            self.config.http.sync_normalize = true;
            self.toast("sync_normalize: on");
        } else if matches!(opt, "nosyncnormalize" | "nosync_normalize" | "nosn") {
            self.config.http.sync_normalize = false;
            self.toast("sync_normalize: off");
        } else if matches!(opt, "syncnormalize!" | "sync_normalize!" | "sn!") {
            self.config.http.sync_normalize = !self.config.http.sync_normalize;
            self.toast(format!(
                "sync_normalize: {}",
                if self.config.http.sync_normalize {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "autoformat" | "auto_format_body" | "af") {
            self.config.http.auto_format_body = true;
            self.toast("auto_format_body: on");
            self.maybe_auto_format_active_body();
        } else if matches!(opt, "noautoformat" | "noauto_format_body" | "noaf") {
            self.config.http.auto_format_body = false;
            self.toast("auto_format_body: off");
        } else if matches!(opt, "autoformat!" | "auto_format_body!" | "af!") {
            self.config.http.auto_format_body = !self.config.http.auto_format_body;
            let state = if self.config.http.auto_format_body {
                "on"
            } else {
                "off"
            };
            self.toast(format!("auto_format_body: {state}"));
            if self.config.http.auto_format_body {
                self.maybe_auto_format_active_body();
            }
        } else if let Some(val) = opt
            .strip_prefix("mdengine=")
            .or_else(|| opt.strip_prefix("md_preview_engine="))
        {
            let val = val.trim();
            if val.is_empty() {
                self.toast(":set mdengine=<builtin|glow|custom:...> — value required");
                return;
            }
            self.config.ui.md_preview_engine = val.to_string();
            // Invalidate every open md preview so the new engine
            // kicks in on the next paint.
            for pane in self.panes.iter_mut() {
                if let crate::pane::Pane::MdPreview(p) = pane {
                    p.external_cache = Default::default();
                    p.external_error_toasted = false;
                }
            }
            self.toast(format!("md_preview_engine: {val}"));
        } else if matches!(opt, "hoverhelp!" | "hover_help!" | "hh!" | "invhoverhelp") {
            self.config.ui.hover_help = !self.config.ui.hover_help;
            self.toast(format!(
                "hover_help: {}",
                if self.config.ui.hover_help {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "relativenumber" | "rnu") {
            self.set_relative_line_numbers(true);
        } else if matches!(opt, "norelativenumber" | "nornu") {
            self.set_relative_line_numbers(false);
        } else if matches!(opt, "relativenumber!" | "rnu!" | "invrelativenumber") {
            self.set_relative_line_numbers(!self.config.ui.relative_line_numbers);
        } else if matches!(opt, "cursorline" | "cul") {
            self.config.ui.cursor_line = true;
            self.toast("cursorline: on");
        } else if matches!(opt, "nocursorline" | "nocul") {
            self.config.ui.cursor_line = false;
            self.toast("cursorline: off");
        } else if matches!(opt, "cursorline!" | "cul!" | "invcursorline") {
            self.config.ui.cursor_line = !self.config.ui.cursor_line;
            self.toast(format!(
                "cursorline: {}",
                if self.config.ui.cursor_line {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "number" | "nu") {
            self.config.ui.line_numbers = true;
            self.toast("number: on");
        } else if matches!(opt, "nonumber" | "nonu") {
            self.config.ui.line_numbers = false;
            self.toast("number: off");
        } else if matches!(opt, "number!" | "nu!" | "invnumber") {
            self.config.ui.line_numbers = !self.config.ui.line_numbers;
            self.toast(format!(
                "number: {}",
                if self.config.ui.line_numbers {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "list") {
            self.set_show_whitespace(true);
        } else if matches!(opt, "nolist") {
            self.set_show_whitespace(false);
        } else if matches!(opt, "list!" | "invlist") {
            self.set_show_whitespace(!self.config.ui.show_whitespace);
        } else if matches!(opt, "rainbow") {
            self.set_bracket_rainbow(true);
        } else if matches!(opt, "norainbow") {
            self.set_bracket_rainbow(false);
        } else if matches!(opt, "rainbow!" | "invrainbow") {
            self.toggle_bracket_rainbow();
        } else if matches!(opt, "scrollbar") {
            self.set_scrollbar(true);
        } else if matches!(opt, "noscrollbar") {
            self.set_scrollbar(false);
        } else if matches!(opt, "scrollbar!" | "invscrollbar") {
            self.toggle_scrollbar();
        } else if matches!(opt, "headless") {
            self.set_browser_headless(true);
        } else if matches!(opt, "noheadless") {
            self.set_browser_headless(false);
        } else if matches!(opt, "headless!" | "invheadless") {
            self.toggle_browser_headless();
        } else if matches!(opt, "trailing") {
            self.set_highlight_trailing_ws(true);
        } else if matches!(opt, "notrailing") {
            self.set_highlight_trailing_ws(false);
        } else if matches!(opt, "trailing!" | "invtrailing") {
            self.toggle_highlight_trailing_ws();
        } else if matches!(opt, "hlword") {
            self.set_highlight_word_under_cursor(true);
        } else if matches!(opt, "nohlword") {
            self.set_highlight_word_under_cursor(false);
        } else if matches!(opt, "hlword!" | "invhlword") {
            self.toggle_highlight_word_under_cursor();
        } else if matches!(opt, "inlayhints") {
            self.config.editor.inlay_hints = true;
            self.toast("inlay hints: on");
        } else if matches!(opt, "noinlayhints") {
            self.config.editor.inlay_hints = false;
            self.toast("inlay hints: off");
        } else if matches!(opt, "inlayhints!" | "invinlayhints") {
            self.config.editor.inlay_hints = !self.config.editor.inlay_hints;
            self.toast(format!(
                "inlay hints: {}",
                if self.config.editor.inlay_hints {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "clock") {
            self.config.ui.clock = true;
            self.toast("clock: on");
        } else if matches!(opt, "noclock") {
            self.config.ui.clock = false;
            self.toast("clock: off");
        } else if matches!(opt, "clock!" | "invclock") {
            self.config.ui.clock = !self.config.ui.clock;
            self.toast(format!(
                "clock: {}",
                if self.config.ui.clock { "on" } else { "off" }
            ));
        } else if matches!(opt, "codelens") {
            self.config.editor.code_lens = true;
            self.toast("code lens: on");
        } else if matches!(opt, "nocodelens") {
            self.config.editor.code_lens = false;
            self.toast("code lens: off");
        } else if matches!(opt, "codelens!" | "invcodelens") {
            self.config.editor.code_lens = !self.config.editor.code_lens;
            self.toast(format!(
                "code lens: {}",
                if self.config.editor.code_lens {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "automdpreview") {
            self.config.ui.auto_md_preview = true;
            self.toast("auto-preview md: on");
        } else if matches!(opt, "noautomdpreview") {
            self.config.ui.auto_md_preview = false;
            self.toast("auto-preview md: off");
        } else if matches!(opt, "automdpreview!" | "invautomdpreview") {
            self.config.ui.auto_md_preview = !self.config.ui.auto_md_preview;
            self.toast(format!(
                "auto-preview md: {}",
                if self.config.ui.auto_md_preview {
                    "on"
                } else {
                    "off"
                }
            ));
        } else if matches!(opt, "nocolorcolumn" | "nocc") {
            self.set_color_column(0);
        } else if matches!(opt, "colorcolumn!" | "cc!" | "invcolorcolumn") {
            self.toggle_color_column();
        } else if matches!(opt, "autoindent" | "ai") {
            self.config.editor.auto_indent = true;
            self.toast("auto-indent: on");
        } else if matches!(opt, "noautoindent" | "noai") {
            self.config.editor.auto_indent = false;
            self.toast("auto-indent: off");
        } else if matches!(opt, "autoindent!" | "invautoindent" | "ai!" | "invai") {
            self.config.editor.auto_indent = !self.config.editor.auto_indent;
            self.toast(format!(
                "auto-indent: {}",
                if self.config.editor.auto_indent {
                    "on"
                } else {
                    "off"
                }
            ));
        // Vim-compat toasts — settings vim users reach for that mnml
        // either always-honors or doesn't implement yet. Toast the
        // current state instead of "unknown option" so muscle memory
        // doesn't get punished.
        } else if matches!(opt, "ignorecase" | "ic") {
            // Force case-INSENSITIVE. nvchad-user SEV-2 2026-07-11
            // fix — used to just toast "already on"; now actually
            // sets the search_case_mode override so search paths
            // ignore case regardless of query capitalization.
            self.search_case_mode = Some(false);
            self.toast(":set ignorecase — on");
        } else if matches!(opt, "noignorecase" | "noic") {
            // Force case-SENSITIVE. Was toasting "not supported".
            self.search_case_mode = Some(true);
            self.toast(":set noignorecase — on (case-sensitive)");
        } else if matches!(opt, "smartcase" | "scs") {
            // Smart-case = mnml's historical default (None → detect
            // from query capitalization). Same reset if user
            // previously typed `:set ic` / `:set noic`.
            self.search_case_mode = None;
            self.toast(":set smartcase — on (case-sensitive iff query has uppercase)");
        } else if matches!(opt, "nosmartcase" | "noscs") {
            // Vim: disabling smartcase falls back to global `ignorecase`.
            // mnml maps to case-INSENSITIVE (matches nvchad default).
            self.search_case_mode = Some(false);
            self.toast(":set nosmartcase — on (always case-insensitive)");
        } else if matches!(
            opt,
            "expandtab" | "et" | "hlsearch" | "hls" | "incsearch" | "is"
        ) {
            self.toast(format!(":set {opt} — already on (mnml default)"));
        } else if matches!(
            opt,
            "noexpandtab" | "noet" | "nohlsearch" | "nohls" | "noincsearch" | "nois"
        ) {
            self.toast(format!(":set {opt} — not supported in mnml"));
        } else if opt == "wrap" {
            self.set_wrap(true);
        } else if opt == "nowrap" {
            self.set_wrap(false);
        } else if matches!(opt, "wrap!" | "invwrap") {
            self.toggle_wrap();
        } else if matches!(opt, "todohl" | "todohighlight") {
            self.set_todo_highlight(true);
        } else if matches!(opt, "notodohl" | "notodohighlight") {
            self.set_todo_highlight(false);
        } else if matches!(opt, "todohl!" | "invtodohl") {
            self.toggle_todo_highlight();
        } else if matches!(opt, "rendermarkdown" | "rendermd") {
            self.set_render_markdown(true);
        } else if matches!(opt, "norendermarkdown" | "norendermd") {
            self.set_render_markdown(false);
        } else if matches!(opt, "rendermarkdown!" | "invrendermarkdown") {
            self.toggle_render_markdown();
        } else if matches!(opt, "stickycontext" | "sticky") {
            self.set_sticky_context(true);
        } else if matches!(opt, "nostickycontext" | "nosticky") {
            self.set_sticky_context(false);
        } else if matches!(opt, "stickycontext!" | "invstickycontext") {
            self.toggle_sticky_context();
        } else if matches!(opt, "foldarrows" | "showfoldarrows") {
            // mouse-round-8 SEV-2 2026-07-12 — persistent fold-arrow
            // gutter marker so foldability is discoverable without
            // hover. Matches VS Code's "Show Folding Controls: always".
            self.config.ui.always_show_fold_arrows = true;
            self.toast("fold arrows: always");
        } else if matches!(opt, "nofoldarrows" | "noshowfoldarrows") {
            self.config.ui.always_show_fold_arrows = false;
            self.toast("fold arrows: on hover only");
        } else if matches!(opt, "foldarrows!" | "invfoldarrows") {
            self.config.ui.always_show_fold_arrows = !self.config.ui.always_show_fold_arrows;
            self.toast(format!(
                "fold arrows: {}",
                if self.config.ui.always_show_fold_arrows {
                    "always"
                } else {
                    "on hover only"
                }
            ));
        } else if matches!(opt, "formatontype" | "fot") {
            self.config.editor.format_on_type = true;
            self.toast(":set formatontype");
        } else if matches!(opt, "noformatontype" | "nofot") {
            self.config.editor.format_on_type = false;
            self.toast(":set noformatontype");
        } else if matches!(opt, "formatonsave" | "fos") {
            self.config.editor.format_on_save = true;
            self.toast(":set formatonsave");
        } else if matches!(opt, "noformatonsave" | "nofos") {
            self.config.editor.format_on_save = false;
            self.toast(":set noformatonsave");
        } else if matches!(opt, "willsavewaituntil" | "wswu") {
            self.config.editor.will_save_wait_until = true;
            self.toast(":set willsavewaituntil");
        } else if matches!(opt, "nowillsavewaituntil" | "nowswu") {
            self.config.editor.will_save_wait_until = false;
            self.toast(":set nowillsavewaituntil");
        } else if matches!(opt, "semantictokensviewport" | "stviewport") {
            self.config.editor.semantic_tokens_viewport = true;
            self.toast(":set semantictokensviewport");
        } else if matches!(opt, "nosemantictokensviewport" | "nostviewport") {
            self.config.editor.semantic_tokens_viewport = false;
            // Drop the cached viewports so the next refresh
            // (now driven by the full/delta path) doesn't think
            // it already requested.
            for p in self.panes.iter_mut() {
                if let Pane::Editor(b) = p {
                    b.last_semantic_viewport = None;
                }
            }
            self.toast(":set nosemantictokensviewport");
        } else if matches!(opt, "autoread" | "ar") {
            // mnml auto-reloads on external file changes by default.
            // Vim users expect `:set autoread` to enable it; we
            // acknowledge instead of refusing. nvchad-round-10 SEV-3
            // 2026-07-12.
            self.toast(":set autoread — already on (mnml default)");
        } else if matches!(opt, "noautoread" | "noar") {
            self.toast(":set noautoread — mnml always auto-reloads");
        } else if matches!(opt, "laststatus" | "ls") {
            self.toast(":set laststatus=2 — statusline always on in mnml");
        } else if matches!(opt, "foldenable" | "fen") {
            self.toast(":set foldenable — already on (mnml has folds)");
        } else if matches!(opt, "nofoldenable" | "nofen") {
            self.toast(":set nofoldenable — mnml folds are not toggleable per-file");
        } else if opt == "tabstop" || opt == "ts" {
            self.toast(format!(
                ":set tabstop — read from config ({} · use `:set tab_width=N`)",
                self.config.editor.tab_width
            ));
        } else if opt == "shiftwidth" || opt == "sw" {
            self.toast(format!(
                ":set shiftwidth — mirrors tab_width ({} · use `:set tab_width=N`)",
                self.config.editor.tab_width
            ));
        } else if opt == "textwidth" || opt == "tw" {
            self.toast(":set textwidth — use `:set text_width=N` (mnml naming)");
        } else if let Some(v) = rest
            .strip_prefix("tabstop=")
            .or_else(|| rest.strip_prefix("ts="))
        {
            let vs = v.trim();
            if let Ok(n) = vs.parse::<usize>() {
                self.set_tab_width(n);
                self.toast(format!(":set tabstop={n} (mnml: tab_width)"));
            } else {
                self.toast(format!(":set tabstop={vs} — not a number"));
            }
        } else if let Some(v) = rest
            .strip_prefix("shiftwidth=")
            .or_else(|| rest.strip_prefix("sw="))
        {
            let vs = v.trim();
            if let Ok(n) = vs.parse::<usize>() {
                self.set_tab_width(n);
                self.toast(format!(":set shiftwidth={n} (mnml: mirrors tab_width)"));
            } else {
                self.toast(format!(":set shiftwidth={vs} — not a number"));
            }
        } else if let Some(v) = rest
            .strip_prefix("textwidth=")
            .or_else(|| rest.strip_prefix("tw="))
        {
            let vs = v.trim();
            if let Ok(n) = vs.parse::<usize>() {
                self.config.editor.text_width = n;
                self.toast(format!(":set textwidth={n} (mnml: text_width)"));
            } else {
                self.toast(format!(":set textwidth={vs} — not a number"));
            }
        } else {
            self.toast(format!(":set {rest} — not supported"));
        }
    }

    /// Accept handler for [`PromptKind::QuitConfirm`].
    pub fn accept_quit(&mut self) {
        self.should_quit = true;
    }

    /// Vim `!{motion}` / `!!` — stash the line range and open the
    /// shell-command prompt. Range is `[cursor_row..=cursor_row +
    /// count - 1]`; the prompt's accept path pipes it through the
    /// typed command and replaces with stdout.
    /// nvchad-round-9 SEV-2 2026-07-11.
    pub fn begin_filter_lines_from_cursor(&mut self, count: u32) {
        let Some(b) = self.active_editor() else {
            self.toast(":! — no active editor");
            return;
        };
        let start = b.editor.row_col().0;
        let end = start.saturating_add(count.max(1) as usize - 1);
        let line_count = b.editor.line_count();
        let end = end.min(line_count.saturating_sub(1));
        self.pending_filter_range = Some((start, end));
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::FilterLinesShellCmd,
            format!("Filter lines {}..{} through:", start + 1, end + 1),
        ));
    }

    /// vim `!ip` / `!ap` — filter the inner-/around-paragraph
    /// containing the cursor through a shell command. Reuses the same
    /// prompt pipeline as `!!` after computing the paragraph's line
    /// range. nvchad-round-10 SEV-3 2026-07-12.
    pub fn begin_filter_paragraph_from_cursor(&mut self, around: bool) {
        let Some(b) = self.active_editor() else {
            self.toast(":! — no active editor");
            return;
        };
        let (start_byte, end_byte) = b.editor.paragraph_bounds_public(around);
        // Translate byte offsets → 0-based line indices.
        let text = b.editor.text();
        let start_line = text[..start_byte].bytes().filter(|&c| c == b'\n').count();
        let end_line = text[..end_byte].bytes().filter(|&c| c == b'\n').count();
        self.pending_filter_range = Some((start_line, end_line));
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::FilterLinesShellCmd,
            format!(
                "Filter {} paragraph (lines {}..{}) through:",
                if around { "around" } else { "inner" },
                start_line + 1,
                end_line + 1
            ),
        ));
    }

    /// Accept handler for `PromptKind::FilterLinesShellCmd`. Pipes
    /// the stashed range through the typed command.
    pub fn accept_filter_lines_shell_cmd(&mut self, cmd: String) {
        let Some((start_line, end_line)) = self.pending_filter_range.take() else {
            return;
        };
        let cmd = cmd.trim();
        if cmd.is_empty() {
            self.toast(":! — no command");
            return;
        }
        let Some(b) = self.active_editor() else {
            return;
        };
        let text = b.editor.text().to_string();
        let (start_byte, end_byte) = {
            let mut byte_off = 0usize;
            let mut start_byte = 0usize;
            let mut end_byte = text.len();
            let mut found_start = false;
            for (i, line) in text.split('\n').enumerate() {
                if i == start_line {
                    start_byte = byte_off;
                    found_start = true;
                }
                byte_off += line.len();
                if i == end_line {
                    end_byte = byte_off;
                    break;
                }
                byte_off += 1;
            }
            if !found_start {
                return;
            }
            (start_byte, end_byte)
        };
        let slice = text[start_byte..end_byte].to_string();
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
        use std::io::Write;
        use std::process::{Command, Stdio};
        let mut child = match Command::new(&shell)
            .arg("-c")
            .arg(cmd)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            Err(e) => {
                self.toast(format!(":!{cmd} — spawn failed: {e}"));
                return;
            }
        };
        if let Some(mut sin) = child.stdin.take()
            && let Err(e) = sin.write_all(slice.as_bytes())
        {
            self.toast(format!(":!{cmd} — stdin: {e}"));
            return;
        }
        match child.wait_with_output() {
            Ok(out) => {
                if !out.status.success() {
                    let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
                    self.toast(format!(
                        ":!{cmd} — exit {}: {}",
                        out.status.code().unwrap_or(-1),
                        if err.is_empty() { "no stderr" } else { &err }
                    ));
                    return;
                }
                let mut replacement = String::from_utf8_lossy(&out.stdout).into_owned();
                // Vim canonical: filter output replaces the range
                // exactly. Strip a single trailing `\n` since the
                // range already ends before its `\n`.
                if replacement.ends_with('\n') {
                    replacement.pop();
                }
                let Some(idx) = self.active else { return };
                if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
                    b.apply_edit_ops(
                        vec![crate::edit_op::EditOp::ReplaceRange {
                            start: start_byte,
                            end: end_byte,
                            text: replacement,
                        }],
                        &mut self.clipboard,
                        0,
                    );
                }
                let n = end_line - start_line + 1;
                self.toast(format!(":!{cmd}{n} line(s) filtered"));
            }
            Err(e) => self.toast(format!(":!{cmd} — wait: {e}")),
        }
    }

    /// `:w !cmd` — pipe the active buffer's text to `cmd` on stdin,
    /// toast the trimmed stdout (or an error). No file is written.
    /// Uses `$SHELL -c` so pipes, quoting, redirection work. Timeout
    /// bounded at 30s to prevent a runaway command from hanging the
    /// event loop. nvchad-round-7 SEV-2 2026-07-11.
    pub fn write_buffer_to_shell(&mut self, cmd: &str) {
        if cmd.is_empty() {
            self.toast(":w ! — no command supplied");
            return;
        }
        let Some(text) = self.active_editor().map(|b| b.editor.text().to_string()) else {
            self.toast(":w ! — no active editor");
            return;
        };
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
        use std::io::Write;
        use std::process::{Command, Stdio};
        let mut child = match Command::new(&shell)
            .arg("-c")
            .arg(cmd)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            Err(e) => {
                self.toast(format!(":w !{cmd} — spawn failed: {e}"));
                return;
            }
        };
        if let Some(mut sin) = child.stdin.take()
            && let Err(e) = sin.write_all(text.as_bytes())
        {
            self.toast(format!(":w !{cmd} — stdin write failed: {e}"));
            return;
        }
        match child.wait_with_output() {
            Ok(out) => {
                let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
                let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
                if !out.status.success() {
                    let msg = if !stderr.is_empty() {
                        stderr
                    } else if !stdout.is_empty() {
                        stdout
                    } else {
                        format!("exit {}", out.status.code().unwrap_or(-1))
                    };
                    self.toast(format!(":w !{cmd}{msg}"));
                } else if !stdout.is_empty() {
                    self.toast(format!(":w !{cmd}{stdout}"));
                } else if !stderr.is_empty() {
                    self.toast(format!(":w !{cmd} — (stderr) {stderr}"));
                } else {
                    self.toast(format!(":w !{cmd} — done"));
                }
            }
            Err(e) => self.toast(format!(":w !{cmd} — wait failed: {e}")),
        }
    }

    /// `:args {pattern}` — expand `{pattern}` workspace-relative into a
    /// fresh arglist and open the first entry. Supported forms:
    /// `foo/bar.rs` (literal), `*.rs` (basename glob at workspace root),
    /// `src/**/*.rs` (recursive glob with double-star). If the pattern
    /// matches nothing the arglist is left alone and a toast fires.
    pub fn arglist_set(&mut self, pattern: &str) {
        let ws = self.workspace.clone();
        let paths = arglist_expand(&ws, pattern);
        if paths.is_empty() {
            self.toast(format!(":args {pattern} — no matches"));
            return;
        }
        let count = paths.len();
        self.arglist = paths;
        self.arglist_index = Some(0);
        self.arglist_goto(0);
        self.toast(format!(":args — {count} file(s), showing 1/{count}"));
    }

    /// `:args` (no arg) — print the arglist with `[current]` markers.
    pub fn arglist_show(&mut self) {
        if self.arglist.is_empty() {
            self.toast(":args — arglist is empty (`:args {glob}` to set)");
            return;
        }
        let cur = self.arglist_index.unwrap_or(usize::MAX);
        let ws = self.workspace.clone();
        let items: Vec<String> = self
            .arglist
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let rel = crate::app::rel_path(&ws, p);
                if i == cur { format!("[{rel}]") } else { rel }
            })
            .collect();
        self.toast(format!(":args · {}", items.join("  ")));
    }

    /// `:next` (`delta=1`) / `:prev` (`delta=-1`) / `:last` (`delta=MAX`).
    /// Clamped at both ends; wraps NO — vim canonical.
    pub fn arglist_step(&mut self, delta: isize) {
        if self.arglist.is_empty() {
            self.toast(":next — arglist is empty");
            return;
        }
        let cur = self.arglist_index.unwrap_or(0) as isize;
        let last = (self.arglist.len() - 1) as isize;
        let target = if delta == isize::MAX {
            last
        } else {
            (cur + delta).clamp(0, last)
        };
        self.arglist_goto(target as usize);
    }

    /// `:first` / opens `arglist[i]`, sets `arglist_index = Some(i)`, and
    /// toasts the position. Clamped; caller ensures `i < len()`.
    pub fn arglist_goto(&mut self, i: usize) {
        if self.arglist.is_empty() {
            return;
        }
        let i = i.min(self.arglist.len() - 1);
        let path = self.arglist[i].clone();
        self.arglist_index = Some(i);
        let total = self.arglist.len();
        self.open_path(&path);
        let rel = crate::app::rel_path(&self.workspace, &path);
        self.toast(format!(":args {}/{total} · {rel}", i + 1));
    }
}

#[cfg(test)]
mod ex_commands_tests {
    use super::*;
    use std::fs;

    #[test]
    fn vim_replacement_backrefs_swap() {
        // Vim `\1`, `\2`, `&`, `\\` map to regex-crate grammar.
        assert_eq!(vim_replacement_to_regex("\\2 \\1"), "$2 $1");
        assert_eq!(vim_replacement_to_regex("<&>"), "<$0>");
        assert_eq!(vim_replacement_to_regex("\\&"), "&");
        assert_eq!(vim_replacement_to_regex("cost $5"), "cost $$5");
        assert_eq!(vim_replacement_to_regex("a\\\\b"), "a\\b");
        assert_eq!(vim_replacement_to_regex("line\\none"), "line\none");
    }

    #[test]
    fn vim_pattern_capture_groups_and_alternation() {
        // Vim `\(a\|b\)` → `(a|b)` for the regex crate.
        assert_eq!(vim_pattern_to_regex("\\(foo\\)"), "(foo)");
        assert_eq!(vim_pattern_to_regex("\\(foo\\|bar\\)"), "(foo|bar)");
        assert_eq!(vim_pattern_to_regex("\\<word\\>"), "\\bword\\b");
        // `\d`, `\w`, `\s`, `\b` unchanged.
        assert_eq!(vim_pattern_to_regex("\\d+"), "\\d+");
    }

    #[test]
    fn substitute_backref_swap_actually_swaps() {
        // End-to-end: `\(foo\) \(bar\)` + `\2 \1` swaps every pair.
        let (_d, mut app) = app_with_buffer("foo bar\nfoo bar\n");
        app.run_ex_command("%s/\\(foo\\) \\(bar\\)/\\2 \\1/g");
        let text = app
            .active_editor()
            .map(|b| b.editor.text().to_string())
            .unwrap();
        assert_eq!(text, "bar foo\nbar foo\n", "got: {text:?}");
    }

    fn app_with_buffer(text: &str) -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("a.txt");
        fs::write(&p, text).unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.open_path(&p);
        (d, app)
    }

    #[test]
    fn run_move_or_copy_line_moves_cursor_line_to_after_dest() {
        // Move line 1 ("alpha") to after line 3 ("gamma"). Result:
        // beta / gamma / alpha / delta.
        let (_d, mut app) = app_with_buffer("alpha\nbeta\ngamma\ndelta\n");
        app.run_move_or_copy_line("3", false);
        let text = app
            .active_editor()
            .map(|b| b.editor.text().to_string())
            .unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["beta", "gamma", "alpha", "delta"]);
    }

    #[test]
    fn run_move_or_copy_line_copy_keeps_source() {
        // Copy line 1 ("alpha") to after line 2 ("beta"). Result:
        // alpha / beta / alpha / gamma.
        let (_d, mut app) = app_with_buffer("alpha\nbeta\ngamma\n");
        app.run_move_or_copy_line("2", true);
        let text = app
            .active_editor()
            .map(|b| b.editor.text().to_string())
            .unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alpha", "beta", "alpha", "gamma"]);
    }

    // `sort` / `false` are Unix shell built-ins that don't exist (or
    // behave incompatibly) under Windows cmd/PowerShell. The feature
    // being tested (`:!<cmd>` shell-filter) currently uses `sh -c` on
    // Unix; Windows support would need a `cmd /c` branch which isn't
    // implemented yet. Gate the tests to unix so Windows CI stays green.
    #[cfg(unix)]
    #[test]
    fn run_filter_through_shell_sorts_buffer() {
        let (_d, mut app) = app_with_buffer("charlie\nalpha\nbravo\n");
        app.run_filter_through_shell("sort", false);
        let text = app
            .active_editor()
            .map(|b| b.editor.text().to_string())
            .unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alpha", "bravo", "charlie"]);
    }

    #[cfg(unix)]
    #[test]
    fn run_filter_through_shell_non_zero_exit_leaves_buffer_untouched() {
        // `false` exits non-zero with no stdout. Buffer must be untouched.
        let (_d, mut app) = app_with_buffer("alpha\nbeta\n");
        app.run_filter_through_shell("false", false);
        let text = app
            .active_editor()
            .map(|b| b.editor.text().to_string())
            .unwrap();
        assert_eq!(text, "alpha\nbeta\n");
    }

    /// SDK bug 2026-07-03: manifest-registered commands store `run =
    /// ":term mnml-…"` verbatim, with the leading colon. `run_ex_command`
    /// received the string as-is and split into `cmd=":term"` which
    /// matched nothing → all 37 integrations dispatched as "unknown
    /// command". The normalization strips a single leading `:` before
    /// parsing; this test locks it.
    #[test]
    fn run_ex_command_strips_leading_colon_from_manifest_commands() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("a.txt");
        fs::write(&p, "hi").unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.open_path(&p);

        let before = app.message_log.len();
        // User-typed form (no leading colon) — must reach `:version`.
        app.run_ex_command("version");
        let user_msgs: Vec<_> = app.message_log[before..].to_vec();
        assert!(
            user_msgs.iter().any(|m| m.starts_with("mnml ")),
            "user-typed 'version' should emit a `mnml <sha>` toast; log tail = {user_msgs:?}"
        );

        let before = app.message_log.len();
        // Manifest-registered form (":version" verbatim) — must
        // reach the same arm, not "unknown command".
        app.run_ex_command(":version");
        let manifest_msgs: Vec<_> = app.message_log[before..].to_vec();
        assert!(
            manifest_msgs.iter().any(|m| m.starts_with("mnml ")),
            "manifest ':version' should emit a `mnml <sha>` toast; log tail = {manifest_msgs:?}"
        );
        assert!(
            manifest_msgs.iter().all(|m| !m.contains("unknown")),
            "manifest ':version' should NOT toast 'unknown command'; log tail = {manifest_msgs:?}"
        );
    }
}