hjkl-ex 0.28.0

Ex-command registry and dispatch layer for the hjkl editor stack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
use crate::{
    effect::ExEffect,
    range::LineRange,
    registry::{ArgKind, ExCommand, Registry},
};
use hjkl_engine::Host;

// ---- folds / global / shell are in their own modules -----------------------
use crate::folds::{apply_fold_indent, apply_fold_syntax};
use crate::global::{global_match_handler, vglobal_handler};

// ---- quit ------------------------------------------------------------------

fn quit_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: false,
        save: false,
    })
}

fn quit_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: true,
        save: false,
    })
}

// ---- write -----------------------------------------------------------------

/// `:w` / `:write` — save current buffer, or save to `<path>` when given.
fn write_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let path = args.trim();
    if path.is_empty() {
        Some(ExEffect::Save)
    } else {
        Some(ExEffect::SaveAs(path.to_string()))
    }
}

// ---- edit ------------------------------------------------------------------

/// `:e [path]` / `:edit [path]` — open or reload a file.
/// Returns `None` (defer to legacy) when no path given — legacy handles
/// the reload-current-buffer case via app-side logic.
fn edit_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::EditFile {
        path: args.trim().to_string(),
        force: false,
    })
}

/// `:e! [path]` / `:edit! [path]` — open or force-reload a file.
fn edit_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::EditFile {
        path: args.trim().to_string(),
        force: true,
    })
}

// ---- read ------------------------------------------------------------------

/// `:r <path>` / `:read <path>` / `:r !cmd` — insert file or shell output
/// below the cursor row.
///
/// Replaces the Phase 2b stub that returned `ExEffect::ReadFile`. Now handles
/// the operation fully in hjkl-ex so the app no longer round-trips through
/// the legacy `ex::run("read {path}")` path.
///
/// Returns `None` when no path/cmd is given (vim errors on `:r` alone).
fn read_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    use hjkl_buffer::{Edit, Position};

    let path = args.trim();
    if path.is_empty() {
        return None;
    }

    // `:r !cmd` — run `cmd` through `sh -c` and capture stdout.
    let content = if let Some(cmd) = path.strip_prefix('!') {
        let cmd = cmd.trim();
        if cmd.is_empty() {
            return Some(ExEffect::Error(":r ! needs a shell command".into()));
        }
        match std::process::Command::new("sh").arg("-c").arg(cmd).output() {
            Ok(out) if out.status.success() => match String::from_utf8(out.stdout) {
                Ok(s) => s,
                Err(_) => return Some(ExEffect::Error("command output was not UTF-8".into())),
            },
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);
                let trimmed = stderr.trim();
                let label = if trimmed.is_empty() {
                    "no stderr".to_string()
                } else {
                    trimmed.to_string()
                };
                return Some(ExEffect::Error(format!(
                    "command exited {} ({label})",
                    out.status
                        .code()
                        .map(|c| c.to_string())
                        .unwrap_or_else(|| "?".into())
                )));
            }
            Err(e) => return Some(ExEffect::Error(format!("cannot run `{cmd}`: {e}"))),
        }
    } else {
        match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => return Some(ExEffect::Error(format!("cannot read `{path}`: {e}"))),
        }
    };

    // Vim's `:r` inserts after the current row (or range's last row if
    // specified); trailing newline in file is dropped (vim does the same).
    let trimmed = content.strip_suffix('\n').unwrap_or(&content);
    editor.push_undo();
    // Insert below range end if range given, else below cursor.
    let row = match range {
        Some(r) => r.end_one_based().saturating_sub(1),
        None => editor.cursor().0,
    };
    let line_chars = hjkl_buffer::rope_line_str(&editor.buffer().rope(), row)
        .chars()
        .count();
    let insert_text = format!("\n{trimmed}");
    editor.mutate_edit(Edit::InsertStr {
        at: Position::new(row, line_chars),
        text: insert_text,
    });
    // Cursor lands on the first inserted row at col 0.
    editor.jump_cursor(row + 1, 0);
    editor.mark_content_dirty();
    Some(ExEffect::Ok)
}

// ---- bdelete / bwipeout ----------------------------------------------------

/// `:bd` / `:bdelete` — close current buffer (no force).
fn bdelete_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::BufferDelete {
        force: false,
        wipe: false,
    })
}

/// `:bd!` / `:bdelete!` — close current buffer (force).
fn bdelete_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::BufferDelete {
        force: true,
        wipe: false,
    })
}

/// `:bw` / `:bwipeout` — wipe current buffer (no force).
fn bwipeout_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::BufferDelete {
        force: false,
        wipe: true,
    })
}

/// `:bw!` / `:bwipeout!` — wipe current buffer (force).
fn bwipeout_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::BufferDelete {
        force: true,
        wipe: true,
    })
}

/// `:wa` / `:wall` — write all modified buffers.
/// hjkl owns one buffer per Editor; behaviour parity with legacy: same as `:w`.
fn wall_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Save)
}

// ---- wq / x ----------------------------------------------------------------

fn wq_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: false,
        save: true,
    })
}

fn wq_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: true,
        save: true,
    })
}

// ---- wqall -----------------------------------------------------------------

fn wqall_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: false,
        save: true,
    })
}

// ---- qall ------------------------------------------------------------------

fn qall_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: false,
        save: false,
    })
}

fn qall_force_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Quit {
        force: true,
        save: false,
    })
}

// ---- nohlsearch ------------------------------------------------------------

fn nohlsearch_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    editor.set_search_pattern(None);
    Some(ExEffect::Ok)
}

// ---- undo / redo -----------------------------------------------------------

fn undo_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    editor.undo();
    Some(ExEffect::Ok)
}

fn redo_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    editor.redo();
    Some(ExEffect::Ok)
}

// ---- saveas / file ---------------------------------------------------------

/// `:saveas {path}` / `:sav {path}` — write buffer to `path` AND rename the
/// buffer identity so future `:w` writes there.
fn saveas_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let path = args.trim();
    if path.is_empty() {
        return Some(ExEffect::Error("E471: Argument required".into()));
    }
    Some(ExEffect::SaveAndRename {
        path: path.to_string(),
    })
}

/// `:file [{name}]` — no-arg: print filename + status; with-arg: rename
/// buffer in-memory without writing.
fn file_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let name = args.trim();
    if name.is_empty() {
        // No arg: surface filename + readonly info. Dirty state lives in the
        // app's slot (not the engine) so only readonly is checked here.
        let filename = editor
            .registers()
            .read('%')
            .map(|s| s.text.clone())
            .unwrap_or_else(|| "[No Name]".into());
        let ro_flag = if editor.is_readonly() { " [RO]" } else { "" };
        Some(ExEffect::Info(format!("\"{filename}\"{ro_flag}")))
    } else {
        Some(ExEffect::RenameBuffer {
            name: name.to_string(),
        })
    }
}

// ---- cd / pwd --------------------------------------------------------------

/// `:cd [{path}]` — change working directory. No arg → `$HOME`.
fn cd_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let raw = args.trim();
    let target = if raw.is_empty() {
        std::env::var("HOME").unwrap_or_else(|_| ".".to_string())
    } else {
        raw.to_string()
    };
    match std::env::set_current_dir(&target) {
        Ok(()) => {
            let new_cwd = std::env::current_dir()
                .map(|p| p.display().to_string())
                .unwrap_or(target.clone());
            Some(ExEffect::Cwd(new_cwd))
        }
        Err(e) => Some(ExEffect::Error(format!("{target}: {e}"))),
    }
}

/// `:pwd` — print working directory.
fn pwd_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let cwd = std::env::current_dir()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| "?".to_string());
    Some(ExEffect::Info(cwd))
}

// ---- put -------------------------------------------------------------------

/// `:put [{reg}]` / `:put!` — paste a register's contents as a new line.
///
/// Without `!`: paste below the current line.
/// With `!`: paste above the current line.
/// Default register when no arg: `"` (unnamed).
fn put_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let reg = args.trim().chars().next().unwrap_or('"');
    Some(ExEffect::PutRegister { reg, above: false })
}

fn put_above_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    let reg = args.trim().chars().next().unwrap_or('"');
    Some(ExEffect::PutRegister { reg, above: true })
}

// ---- registers / marks / jumps / changes -----------------------------------

fn registers_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::InfoTitled {
        title: "registers",
        content: crate::listings::format_registers(editor),
    })
}

fn marks_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::InfoTitled {
        title: "marks",
        content: crate::listings::format_marks(editor),
    })
}

fn jumps_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::InfoTitled {
        title: "jumps",
        content: crate::listings::format_jumps(editor),
    })
}

fn changes_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::InfoTitled {
        title: "changes",
        content: crate::listings::format_changes(editor),
    })
}

// ---- delete ----------------------------------------------------------------

/// `:[range]d` / `:[range]delete` — delete lines in range (default: cursor line).
///
/// `LineRange` is 1-based inclusive. Legacy `Range` (in hjkl-editor) is 0-based;
/// we convert here before mutating the buffer.
fn delete_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    use hjkl_buffer::{Edit, MotionKind, Position};

    // No range → current line (1-based cursor row + 1).
    let r = range.unwrap_or_else(|| LineRange::single(editor.cursor().0 + 1));
    // Convert 1-based inclusive to 0-based inclusive row indices.
    let start_row = r.start_one_based().saturating_sub(1);
    let total = editor.buffer().row_count();
    if total == 0 {
        return Some(ExEffect::Ok);
    }
    let end_row = (r.end_one_based().saturating_sub(1)).min(total.saturating_sub(1));
    if start_row > end_row {
        return Some(ExEffect::Ok);
    }

    editor.push_undo();
    // Delete bottom-up so row indices stay valid as rows are removed.
    for row in (start_row..=end_row).rev() {
        if editor.buffer().row_count() == 1 {
            // Last remaining row: clear content rather than deleting the row.
            let line_chars = hjkl_buffer::rope_line_str(&editor.buffer().rope(), 0)
                .chars()
                .count();
            if line_chars > 0 {
                editor.mutate_edit(Edit::DeleteRange {
                    start: Position::new(0, 0),
                    end: Position::new(0, line_chars),
                    kind: MotionKind::Char,
                });
            }
            continue;
        }
        editor.mutate_edit(Edit::DeleteRange {
            start: Position::new(row, 0),
            end: Position::new(row, 0),
            kind: MotionKind::Line,
        });
    }
    editor.mark_content_dirty();
    Some(ExEffect::Ok)
}

// ---- sort ------------------------------------------------------------------

/// `:[range]sort[!iun]` — sort lines in range (default: whole buffer).
///
/// Flags (trailing args): `!` reverse, `i` ignore-case, `u` unique, `n` numeric.
fn sort_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    let trimmed = args.trim();
    let mut reverse = false;
    let mut unique = false;
    let mut numeric = false;
    let mut ignore_case = false;
    for c in trimmed.chars() {
        match c {
            '!' => reverse = true,
            'u' => unique = true,
            'n' => numeric = true,
            'i' => ignore_case = true,
            ' ' | '\t' => {}
            other => return Some(ExEffect::Error(format!("bad :sort flag `{other}`"))),
        }
    }

    let rope = editor.buffer().rope();
    let mut all_lines: Vec<String> = (0..rope.len_lines())
        .map(|i| hjkl_buffer::rope_line_str(&rope, i))
        .collect();
    drop(rope);
    let total = all_lines.len();
    if total == 0 {
        return Some(ExEffect::Ok);
    }

    // Default range: whole buffer (0-based: 0..=total-1).
    let (start_row, end_row) = match range {
        Some(r) => {
            let s = r.start_one_based().saturating_sub(1);
            let e = (r.end_one_based().saturating_sub(1)).min(total - 1);
            (s, e)
        }
        None => (0, total - 1),
    };
    if start_row > end_row {
        return Some(ExEffect::Ok);
    }

    // Sort only the slice in range; keep the rest of the buffer intact.
    let mut slice: Vec<String> = all_lines[start_row..=end_row].to_vec();
    if numeric {
        slice.sort_by_key(|l| extract_leading_number(l));
    } else if ignore_case {
        slice.sort_by_key(|s| s.to_lowercase());
    } else {
        slice.sort();
    }
    if reverse {
        slice.reverse();
    }
    if unique {
        let cmp_key = |s: &str| -> String {
            if ignore_case {
                s.to_lowercase()
            } else {
                s.to_string()
            }
        };
        let mut seen = std::collections::HashSet::new();
        slice.retain(|line| seen.insert(cmp_key(line)));
    }
    // Splice the sorted slice back. `unique` may have shortened it.
    let after: Vec<String> = all_lines.split_off(end_row + 1);
    all_lines.truncate(start_row);
    all_lines.extend(slice);
    all_lines.extend(after);

    editor.push_undo();
    editor.restore(all_lines, (start_row, 0));
    editor.mark_content_dirty();
    Some(ExEffect::Ok)
}

/// Parse the first signed decimal integer from `line` for `:sort n`.
/// Lines with no leading number sort as `i64::MIN` (cluster at top, vim compat).
fn extract_leading_number(line: &str) -> i64 {
    let bytes = line.as_bytes();
    let mut i = 0;
    while i < bytes.len() && !bytes[i].is_ascii_digit() && bytes[i] != b'-' {
        i += 1;
    }
    if i >= bytes.len() {
        return i64::MIN;
    }
    let mut j = i;
    if bytes[j] == b'-' {
        j += 1;
    }
    let start = j;
    while j < bytes.len() && bytes[j].is_ascii_digit() {
        j += 1;
    }
    if j == start {
        return i64::MIN;
    }
    line[i..j].parse().unwrap_or(i64::MIN)
}

// ---- substitute ------------------------------------------------------------

/// `:[range]s/pattern/replacement/[flags]` — substitute text in lines.
///
/// `args` arrives already stripped of the leading `s` command name, so it
/// begins with the delimiter (`/`) that `hjkl_engine::substitute::parse_substitute`
/// expects.  No-range → current cursor line; with range the engine receives a
/// 0-based inclusive `RangeInclusive<u32>`.
///
/// On success the parsed `SubstituteCmd` is stored on the editor so `:&` / `:&&`
/// can repeat it (part of #171).
fn substitute_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    use hjkl_engine::substitute::{apply_substitute, parse_substitute};

    // args already starts with `/` (the delimiter); pass straight to engine.
    let cmd = match parse_substitute(args) {
        Ok(c) => c,
        Err(e) => return Some(ExEffect::Error(e.to_string())),
    };

    // Resolve range to 0-based inclusive u32 bounds.
    // No range → current cursor line (cursor() returns 0-based (row, col)).
    let r = match range {
        Some(lr) => {
            let start = lr.start_one_based().saturating_sub(1) as u32;
            let end = lr.end_one_based().saturating_sub(1) as u32;
            start..=end
        }
        None => {
            let row = editor.cursor().0 as u32;
            row..=row
        }
    };

    match apply_substitute(editor, &cmd, r) {
        Ok(out) => {
            // Store so `:&` / `:&&` can repeat this substitution.
            editor.set_last_substitute(cmd);
            Some(ExEffect::Substituted {
                count: out.replacements,
                lines_changed: out.lines_changed,
            })
        }
        Err(e) => Some(ExEffect::Error(e.to_string())),
    }
}

/// `:&` / `:&&` / `:[range]&` / `:[range]&&` — repeat last substitute.
///
/// `:&`  — repeat with original flags dropped (pattern and replacement kept).
/// `:&&` — repeat with original flags preserved.
///
/// `keep_flags` is `true` for `&&`, `false` for `&`.
pub(crate) fn repeat_substitute_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    keep_flags: bool,
    range: Option<LineRange>,
) -> ExEffect {
    use hjkl_engine::substitute::{SubstFlags, apply_substitute};

    let cmd = match editor.last_substitute().cloned() {
        Some(c) => c,
        None => return ExEffect::Error("no previous substitute".into()),
    };

    // `:&` drops flags; `:&&` keeps them (vim semantics).
    let effective_cmd = if keep_flags {
        cmd
    } else {
        hjkl_engine::substitute::SubstituteCmd {
            flags: SubstFlags::default(),
            ..cmd
        }
    };

    // Resolve range; default to current line.
    let r = match range {
        Some(lr) => {
            let start = lr.start_one_based().saturating_sub(1) as u32;
            let end = lr.end_one_based().saturating_sub(1) as u32;
            start..=end
        }
        None => {
            let row = editor.cursor().0 as u32;
            row..=row
        }
    };

    match apply_substitute(editor, &effective_cmd, r) {
        Ok(out) => {
            // Keep last_substitute updated with what was actually run.
            editor.set_last_substitute(effective_cmd);
            ExEffect::Substituted {
                count: out.replacements,
                lines_changed: out.lines_changed,
            }
        }
        Err(e) => ExEffect::Error(e.to_string()),
    }
}

// ---- set -------------------------------------------------------------------

/// `:set [option ...]` — query / assign vim settings.
fn set_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(crate::setopt::apply_set(editor, args))
}

// ---- registration ----------------------------------------------------------

/// Register all Phase 1 + Phase 2a built-in commands.
pub(crate) fn register_builtins<H: Host>(reg: &mut Registry<H>) {
    // `:quit` / `:q`
    reg.add(ExCommand {
        name: "quit",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 1,
        run: quit_handler::<H>,
    });

    // `:quit!` / `:q!`
    reg.add(ExCommand {
        name: "quit!",
        aliases: &["q!"],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: quit_force_handler::<H>,
    });

    // `:write` / `:w`  (min_prefix=1, but `:wa` resolves to `:wall` not `:write`)
    reg.add(ExCommand {
        name: "write",
        aliases: &[],
        arg_kind: ArgKind::Path,
        min_prefix: 1,
        run: write_handler::<H>,
    });

    // `:wall` / `:wa`
    reg.add(ExCommand {
        name: "wall",
        aliases: &["wa"],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: wall_handler::<H>,
    });

    // `:wq`  (min_prefix=2 so `:w` still resolves to `:write`)
    reg.add(ExCommand {
        name: "wq",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: wq_handler::<H>,
    });

    // `:wq!`
    reg.add(ExCommand {
        name: "wq!",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: wq_force_handler::<H>,
    });

    // `:x`  (exact alias for wq)
    reg.add(ExCommand {
        name: "x",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 1,
        run: wq_handler::<H>,
    });

    // `:x!`
    reg.add(ExCommand {
        name: "x!",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: wq_force_handler::<H>,
    });

    // `:wqall` / `:wqa` — force=false (vim treats force as save errors, save=true)
    reg.add(ExCommand {
        name: "wqall",
        aliases: &["wqa"],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: wqall_handler::<H>,
    });

    // `:wqall!` / `:wqa!`
    reg.add(ExCommand {
        name: "wqall!",
        aliases: &["wqa!"],
        arg_kind: ArgKind::None,
        min_prefix: 4,
        run: wqall_handler::<H>,
    });

    // `:qall` / `:qa`
    reg.add(ExCommand {
        name: "qall",
        aliases: &["qa"],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: qall_handler::<H>,
    });

    // `:qall!` / `:qa!`
    reg.add(ExCommand {
        name: "qall!",
        aliases: &["qa!"],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: qall_force_handler::<H>,
    });

    // `:nohlsearch` / `:noh` / `:nohl` (min_prefix=3)
    reg.add(ExCommand {
        name: "nohlsearch",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: nohlsearch_handler::<H>,
    });

    // `:undo` / `:u`
    reg.add(ExCommand {
        name: "undo",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 1,
        run: undo_handler::<H>,
    });

    // `:redo` (min_prefix=3; `:r` resolves to `:read`, `:re` is ambiguous)
    reg.add(ExCommand {
        name: "redo",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: redo_handler::<H>,
    });

    // `:edit` / `:e` (min_prefix=1; no other registered command starts with `e`)
    reg.add(ExCommand {
        name: "edit",
        aliases: &[],
        arg_kind: ArgKind::Path,
        min_prefix: 1,
        run: edit_handler::<H>,
    });

    // `:edit!` / `:e!` (min_prefix=2)
    reg.add(ExCommand {
        name: "edit!",
        aliases: &["e!"],
        arg_kind: ArgKind::Path,
        min_prefix: 2,
        run: edit_force_handler::<H>,
    });

    // `:read` / `:r` (min_prefix=1; `:re` still ambiguous with `:redo` at min=3)
    reg.add(ExCommand {
        name: "read",
        aliases: &[],
        arg_kind: ArgKind::Path,
        min_prefix: 1,
        run: read_handler::<H>,
    });

    // `:bdelete` / `:bd` (min_prefix=2)
    reg.add(ExCommand {
        name: "bdelete",
        aliases: &["bd"],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: bdelete_handler::<H>,
    });

    // `:bdelete!` / `:bd!` (min_prefix=3)
    reg.add(ExCommand {
        name: "bdelete!",
        aliases: &["bd!"],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: bdelete_force_handler::<H>,
    });

    // `:bwipeout` / `:bw` (min_prefix=2)
    reg.add(ExCommand {
        name: "bwipeout",
        aliases: &["bw"],
        arg_kind: ArgKind::None,
        min_prefix: 2,
        run: bwipeout_handler::<H>,
    });

    // `:bwipeout!` / `:bw!` (min_prefix=3)
    reg.add(ExCommand {
        name: "bwipeout!",
        aliases: &["bw!"],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: bwipeout_force_handler::<H>,
    });

    // `:saveas {path}` / `:sav {path}` — write and rename buffer (min_prefix=3).
    reg.add(ExCommand {
        name: "saveas",
        aliases: &["sav"],
        arg_kind: ArgKind::Path,
        min_prefix: 3,
        run: saveas_handler::<H>,
    });

    // `:file [{name}]` — no-arg: show filename; with-arg: rename buffer (min_prefix=1).
    reg.add(ExCommand {
        name: "file",
        aliases: &[],
        arg_kind: ArgKind::Path,
        min_prefix: 1,
        run: file_handler::<H>,
    });

    // `:cd [{path}]` — change working directory (no-arg → $HOME) (min_prefix=2).
    reg.add(ExCommand {
        name: "cd",
        aliases: &[],
        arg_kind: ArgKind::Path,
        min_prefix: 2,
        run: cd_handler::<H>,
    });

    // `:pwd` — print working directory (min_prefix=3).
    reg.add(ExCommand {
        name: "pwd",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: pwd_handler::<H>,
    });

    // `:put [{reg}]` / `:pu [{reg}]` — paste register as new line below cursor.
    reg.add(ExCommand {
        name: "put",
        aliases: &["pu"],
        arg_kind: ArgKind::Raw,
        min_prefix: 2,
        run: put_handler::<H>,
    });

    // `:put! [{reg}]` / `:pu!` — paste register as new line above cursor.
    reg.add(ExCommand {
        name: "put!",
        aliases: &["pu!"],
        arg_kind: ArgKind::Raw,
        min_prefix: 3,
        run: put_above_handler::<H>,
    });

    // `:registers` / `:reg` (min_prefix=3; `:reg` via alias since "reg" < 3 chars)
    reg.add(ExCommand {
        name: "registers",
        aliases: &["reg"],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: registers_handler::<H>,
    });

    // `:marks` (min_prefix=5)
    reg.add(ExCommand {
        name: "marks",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 5,
        run: marks_handler::<H>,
    });

    // `:jumps` (min_prefix=5)
    reg.add(ExCommand {
        name: "jumps",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 5,
        run: jumps_handler::<H>,
    });

    // `:changes` (min_prefix=7)
    reg.add(ExCommand {
        name: "changes",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 7,
        run: changes_handler::<H>,
    });

    // `:delete` / `:d` (min_prefix=1; range-aware)
    reg.add(ExCommand {
        name: "delete",
        aliases: &["d"],
        arg_kind: ArgKind::None,
        min_prefix: 1,
        run: delete_handler::<H>,
    });

    // `:sort` (min_prefix=3; range-aware)
    reg.add(ExCommand {
        name: "sort",
        aliases: &[],
        arg_kind: ArgKind::Raw,
        min_prefix: 3,
        run: sort_handler::<H>,
    });

    // `:substitute` / `:s` (min_prefix=1; range-aware)
    // `:&` and `:~` (repeat-last-substitute) are NOT registered here — their
    // non-alphabetic names cannot be parsed by `split_name_args`.  Deferred to
    // a future phase that extends the command-name parser.
    reg.add(ExCommand {
        name: "substitute",
        aliases: &[],
        arg_kind: ArgKind::Raw,
        min_prefix: 1,
        run: substitute_handler::<H>,
    });

    // `:set` / `:se` (min_prefix=2 — matches legacy COMMAND_NAMES line 47)
    reg.add(ExCommand {
        name: "set",
        aliases: &[],
        arg_kind: ArgKind::Setting,
        min_prefix: 2,
        run: set_handler::<H>,
    });

    // ---- Phase 8a ----------------------------------------------------------

    // `:foldindent` (min_prefix=5; `:foldi` is the shortest unambiguous form)
    reg.add(ExCommand {
        name: "foldindent",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 5,
        run: |editor, args, range| apply_fold_indent(editor, args, range),
    });

    // `:foldsyntax` (min_prefix=5; `:folds` is shortest — same as foldindent)
    reg.add(ExCommand {
        name: "foldsyntax",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 5,
        run: |editor, args, range| apply_fold_syntax(editor, args, range),
    });

    // `:global` / `:g` (min_prefix=1; range-aware)
    // `:global!/pat/cmd` is handled by global_match_handler (strips leading `!`).
    reg.add(ExCommand {
        name: "global",
        aliases: &["g"],
        arg_kind: ArgKind::Raw,
        min_prefix: 1,
        run: |editor, args, range| global_match_handler(editor, args, range),
    });

    // `:vglobal` / `:v` (min_prefix=1; range-aware)
    reg.add(ExCommand {
        name: "vglobal",
        aliases: &["v"],
        arg_kind: ArgKind::Raw,
        min_prefix: 1,
        run: |editor, args, range| vglobal_handler(editor, args, range),
    });

    // ---- Phase #187 -----------------------------------------------------------

    // `:comment` (min_prefix=3; toggle line comments; range-aware)
    reg.add(ExCommand {
        name: "comment",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 3,
        run: comment_handler::<H>,
    });

    // `:uncomment` (min_prefix=5; force-strip line comments; range-aware)
    reg.add(ExCommand {
        name: "uncomment",
        aliases: &[],
        arg_kind: ArgKind::None,
        min_prefix: 5,
        run: uncomment_handler::<H>,
    });

    // `:syntax [on|off|enable|disable]` — vim-compat syntax-highlight toggle.
    // Engine never touches highlighting; this returns Ok so headless/nvim-api
    // paths see success. The TUI app overrides via the host registry to
    // actually drop/re-attach bonsai layers (see ex_host_cmds::SyntaxCmd).
    reg.add(ExCommand {
        name: "syntax",
        aliases: &[],
        arg_kind: ArgKind::Raw,
        min_prefix: 3,
        run: syntax_handler::<H>,
    });
}

// ---- :syntax ---------------------------------------------------------------

/// `:syntax [on|off|enable|disable|...]` — engine-side no-op for vim parity.
///
/// Recognised subcommands return `ExEffect::Ok`. Unknown args also return
/// `Ok` (vim's `:syntax <bareword>` is permissive — many forms like
/// `:syntax sync`, `:syntax clear`, `:syntax reset` are accepted without
/// error).
fn syntax_handler<H: Host>(
    _editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    _range: Option<LineRange>,
) -> Option<ExEffect> {
    Some(ExEffect::Ok)
}

// ---- comment / uncomment (#187) --------------------------------------------

/// `:[range]comment` — toggle line comments on the range.
///
/// Toggle algorithm (vim-commentary parity):
/// - Scan non-blank lines.  If every non-blank line is commented → uncomment.
/// - Otherwise → comment all non-blank lines.
///
/// No range → current cursor line.
fn comment_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    let (top, bot) = resolve_comment_range(editor, range);
    editor.toggle_comment_range(top, bot);
    Some(ExEffect::Ok)
}

/// `:[range]uncomment` — force-remove comment markers (idempotent no-op when
/// not commented).
///
/// Achieves "force uncomment" by temporarily overriding the all-commented
/// check: scan each non-blank line and strip exactly one occurrence of the
/// comment marker if present. Lines that are not commented are left unchanged.
fn uncomment_handler<H: Host>(
    editor: &mut hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    _args: &str,
    range: Option<LineRange>,
) -> Option<ExEffect> {
    use hjkl_lang::comment::commentstring_for_lang;

    let (top, bot) = resolve_comment_range(editor, range);
    let lang = editor.settings().filetype.clone();

    // Resolve comment markers (same priority as toggle_comment_range).
    let (start, end): (String, Option<String>) = if !editor.settings().commentstring.is_empty() {
        let cs = editor.settings().commentstring.clone();
        if let Some(idx) = cs.find("%s") {
            let s = cs[..idx].trim_end().to_string();
            let e_raw = cs[idx + 2..].trim_start();
            let e = if e_raw.is_empty() {
                None
            } else {
                Some(e_raw.to_string())
            };
            (s, e)
        } else {
            (cs, None)
        }
    } else {
        match commentstring_for_lang(&lang) {
            Some((s, e)) => (s.to_string(), e.map(|v| v.to_string())),
            None => return Some(ExEffect::Ok), // no-op
        }
    };

    // Collect lines using the rope API.
    let row_count = editor.buffer().row_count();
    let top_c = top.min(row_count.saturating_sub(1));
    let bot_c = bot.min(row_count.saturating_sub(1));

    let rope = editor.buffer().rope();
    let lines: Vec<String> = (top_c..=bot_c)
        .map(|r| hjkl_buffer::rope_line_str(&rope, r))
        .collect();

    let mut new_lines: Vec<String> = Vec::with_capacity(lines.len());
    for line in &lines {
        let trimmed = line.trim_start();
        if trimmed.is_empty() {
            new_lines.push(line.clone());
            continue;
        }
        let indent_len = line.len() - trimmed.len();
        let indent = &line[..indent_len];

        if let Some(after_start) = trimmed.strip_prefix(start.as_str()) {
            let after_space = after_start.strip_prefix(' ').unwrap_or(after_start);
            let text = if let Some(ref end_marker) = end {
                after_space
                    .trim_end()
                    .strip_suffix(end_marker.as_str())
                    .map(|s| s.trim_end())
                    .unwrap_or(after_space)
            } else {
                after_space
            };
            new_lines.push(format!("{indent}{text}"));
        } else {
            // Not commented — leave unchanged.
            new_lines.push(line.clone());
        }
    }

    editor.push_undo();
    let total_rows = editor.buffer().row_count();
    let all_before: Vec<String> = (0..top_c)
        .map(|r| hjkl_buffer::rope_line_str(&rope, r))
        .collect();
    let all_after: Vec<String> = ((bot_c + 1)..total_rows)
        .map(|r| hjkl_buffer::rope_line_str(&rope, r))
        .collect();
    let mut all: Vec<String> = all_before;
    all.extend(new_lines);
    all.extend(all_after);
    editor.restore(all, (top_c, 0));

    Some(ExEffect::Ok)
}

/// Resolve a `LineRange` to `(top, bot)` 0-based row indices.
/// No range → current cursor line.
fn resolve_comment_range<H: Host>(
    editor: &hjkl_engine::Editor<hjkl_buffer::Buffer, H>,
    range: Option<LineRange>,
) -> (usize, usize) {
    match range {
        Some(lr) => {
            let top = lr.start_one_based().saturating_sub(1);
            let bot = lr.end_one_based().saturating_sub(1);
            (top, bot)
        }
        None => {
            let row = editor.cursor().0;
            (row, row)
        }
    }
}

// ---- unit tests ------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::range::LineRange;
    use hjkl_engine::{DefaultHost, Editor, Options};

    // ── helpers ──────────────────────────────────────────────────────────────

    fn make_editor() -> Editor<hjkl_buffer::Buffer, DefaultHost> {
        let buf = hjkl_buffer::Buffer::new();
        let host = DefaultHost::new();
        Editor::new(buf, host, Options::default())
    }

    fn make_editor_with_lines(lines: &[&str]) -> Editor<hjkl_buffer::Buffer, DefaultHost> {
        let content = lines.join("\n");
        let buf = hjkl_buffer::Buffer::from_str(&content);
        let host = DefaultHost::new();
        Editor::new(buf, host, Options::default())
    }

    fn buf_line(editor: &Editor<hjkl_buffer::Buffer, DefaultHost>, row: usize) -> String {
        hjkl_buffer::rope_line_str(&editor.buffer().rope(), row)
    }

    fn buf_lines(editor: &Editor<hjkl_buffer::Buffer, DefaultHost>) -> Vec<String> {
        let rope = editor.buffer().rope();
        (0..rope.len_lines())
            .map(|i| hjkl_buffer::rope_line_str(&rope, i))
            .collect()
    }

    // ── quit_handler ─────────────────────────────────────────────────────────

    #[test]
    fn quit_handler_returns_quit_no_force_no_save() {
        let mut ed = make_editor();
        let result = quit_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: false,
                save: false
            })
        );
    }

    // ── quit_force_handler ───────────────────────────────────────────────────

    #[test]
    fn quit_force_handler_returns_quit_force_no_save() {
        let mut ed = make_editor();
        let result = quit_force_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: true,
                save: false
            })
        );
    }

    // ── write_handler ────────────────────────────────────────────────────────

    #[test]
    fn write_handler_no_args_returns_save() {
        let mut ed = make_editor();
        let result = write_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Save));
    }

    #[test]
    fn write_handler_with_path_returns_save_as() {
        let mut ed = make_editor();
        let result = write_handler(&mut ed, "  /tmp/test.txt  ", None);
        assert_eq!(result, Some(ExEffect::SaveAs("/tmp/test.txt".to_string())));
    }

    #[test]
    fn write_handler_whitespace_only_returns_save() {
        let mut ed = make_editor();
        let result = write_handler(&mut ed, "   ", None);
        // trim() → empty → Save
        assert_eq!(result, Some(ExEffect::Save));
    }

    // ── wall_handler ─────────────────────────────────────────────────────────

    #[test]
    fn wall_handler_returns_save() {
        let mut ed = make_editor();
        let result = wall_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Save));
    }

    // ── edit_handler ─────────────────────────────────────────────────────────

    #[test]
    fn edit_handler_with_path_returns_edit_file_no_force() {
        let mut ed = make_editor();
        let result = edit_handler(&mut ed, "  foo.txt  ", None);
        assert_eq!(
            result,
            Some(ExEffect::EditFile {
                path: "foo.txt".to_string(),
                force: false,
            })
        );
    }

    #[test]
    fn edit_force_handler_sets_force_flag() {
        let mut ed = make_editor();
        let result = edit_force_handler(&mut ed, "bar.txt", None);
        assert_eq!(
            result,
            Some(ExEffect::EditFile {
                path: "bar.txt".to_string(),
                force: true,
            })
        );
    }

    // ── bdelete / bwipeout ───────────────────────────────────────────────────

    #[test]
    fn bdelete_handler_returns_buffer_delete_no_force_no_wipe() {
        let mut ed = make_editor();
        let result = bdelete_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::BufferDelete {
                force: false,
                wipe: false,
            })
        );
    }

    #[test]
    fn bdelete_force_handler_returns_buffer_delete_force_no_wipe() {
        let mut ed = make_editor();
        let result = bdelete_force_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::BufferDelete {
                force: true,
                wipe: false,
            })
        );
    }

    #[test]
    fn bwipeout_handler_returns_buffer_delete_no_force_wipe() {
        let mut ed = make_editor();
        let result = bwipeout_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::BufferDelete {
                force: false,
                wipe: true,
            })
        );
    }

    #[test]
    fn bwipeout_force_handler_returns_buffer_delete_force_wipe() {
        let mut ed = make_editor();
        let result = bwipeout_force_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::BufferDelete {
                force: true,
                wipe: true,
            })
        );
    }

    // bdelete vs bwipeout — wipe flag must differ
    #[test]
    fn bdelete_and_bwipeout_differ_only_in_wipe_flag() {
        let mut ed = make_editor();
        let bd = bdelete_handler(&mut ed, "", None);
        let bw = bwipeout_handler(&mut ed, "", None);
        match (bd, bw) {
            (
                Some(ExEffect::BufferDelete {
                    wipe: bd_wipe,
                    force: bd_force,
                }),
                Some(ExEffect::BufferDelete {
                    wipe: bw_wipe,
                    force: bw_force,
                }),
            ) => {
                assert!(!bd_wipe, "bdelete wipe must be false");
                assert!(bw_wipe, "bwipeout wipe must be true");
                assert_eq!(bd_force, bw_force, "force flag should match");
            }
            other => panic!("unexpected: {other:?}"),
        }
    }

    // ── wq_handler / wq_force_handler ────────────────────────────────────────

    #[test]
    fn wq_handler_returns_quit_save_no_force() {
        let mut ed = make_editor();
        let result = wq_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: false,
                save: true,
            })
        );
    }

    #[test]
    fn wq_force_handler_returns_quit_save_force() {
        let mut ed = make_editor();
        let result = wq_force_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: true,
                save: true,
            })
        );
    }

    // ── wqall / qall / qall_force ────────────────────────────────────────────

    #[test]
    fn wqall_handler_returns_quit_save_no_force() {
        let mut ed = make_editor();
        let result = wqall_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: false,
                save: true,
            })
        );
    }

    #[test]
    fn qall_handler_returns_quit_no_save_no_force() {
        let mut ed = make_editor();
        let result = qall_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: false,
                save: false,
            })
        );
    }

    #[test]
    fn qall_force_handler_returns_quit_force_no_save() {
        let mut ed = make_editor();
        let result = qall_force_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::Quit {
                force: true,
                save: false,
            })
        );
    }

    // ── nohlsearch_handler ───────────────────────────────────────────────────

    #[test]
    fn nohlsearch_clears_active_search_pattern() {
        let mut ed = make_editor();
        // Install a pattern then clear it.
        ed.set_search_pattern(Some(regex::Regex::new("foo").unwrap()));
        assert!(
            ed.search_state().pattern.is_some(),
            "setup: pattern must be set"
        );
        let result = nohlsearch_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        assert!(
            ed.search_state().pattern.is_none(),
            "pattern should be cleared"
        );
    }

    #[test]
    fn nohlsearch_on_already_clear_returns_ok() {
        let mut ed = make_editor();
        // Pattern is None by default.
        let result = nohlsearch_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        assert!(ed.search_state().pattern.is_none());
    }

    // ── undo / redo ──────────────────────────────────────────────────────────

    #[test]
    fn undo_handler_returns_ok() {
        let mut ed = make_editor();
        let result = undo_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    #[test]
    fn redo_handler_returns_ok() {
        let mut ed = make_editor();
        let result = redo_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    // ── registers / marks / jumps / changes ──────────────────────────────────

    #[test]
    fn registers_handler_returns_info_titled() {
        let mut ed = make_editor();
        let result = registers_handler(&mut ed, "", None);
        match result {
            Some(ExEffect::InfoTitled { title, content }) => {
                assert_eq!(title, "registers");
                assert!(
                    content.contains("Registers"),
                    "expected Registers header, got: {content}"
                );
            }
            other => panic!("expected InfoTitled, got {other:?}"),
        }
    }

    #[test]
    fn marks_handler_returns_info_titled() {
        let mut ed = make_editor();
        let result = marks_handler(&mut ed, "", None);
        match result {
            Some(ExEffect::InfoTitled { title, content }) => {
                assert_eq!(title, "marks");
                assert!(
                    content.contains("Marks"),
                    "expected Marks header, got: {content}"
                );
            }
            other => panic!("expected InfoTitled, got {other:?}"),
        }
    }

    #[test]
    fn jumps_handler_returns_info_titled() {
        let mut ed = make_editor();
        let result = jumps_handler(&mut ed, "", None);
        // Empty jump list → "(no jumps recorded)" as Info (single line), not InfoTitled.
        match result {
            Some(ExEffect::InfoTitled { title, content }) => {
                assert_eq!(title, "jumps");
                assert!(
                    content.contains("jump") || content.contains("no jumps"),
                    "unexpected content: {content}"
                );
            }
            other => panic!("expected InfoTitled, got {other:?}"),
        }
    }

    #[test]
    fn changes_handler_returns_info_titled() {
        let mut ed = make_editor();
        let result = changes_handler(&mut ed, "", None);
        match result {
            Some(ExEffect::InfoTitled { title, content }) => {
                assert_eq!(title, "changes");
                assert!(
                    content.contains("change") || content.contains("no changes"),
                    "unexpected content: {content}"
                );
            }
            other => panic!("expected InfoTitled, got {other:?}"),
        }
    }

    // ── delete_handler ───────────────────────────────────────────────────────

    #[test]
    fn delete_handler_default_range_deletes_cursor_line() {
        let mut ed = make_editor_with_lines(&["aaa", "bbb", "ccc"]);
        // Cursor at row 0 (default). Deletes line 1 (1-based).
        let result = delete_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert!(
            !lines.contains(&"aaa".to_string()),
            "first line should be deleted: {lines:?}"
        );
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn delete_handler_explicit_range_deletes_lines() {
        let mut ed = make_editor_with_lines(&["l1", "l2", "l3", "l4"]);
        let range = LineRange::new(2, 3);
        let result = delete_handler(&mut ed, "", Some(range));
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert_eq!(lines.len(), 2, "expected 2 remaining lines: {lines:?}");
        assert!(lines.contains(&"l1".to_string()));
        assert!(lines.contains(&"l4".to_string()));
    }

    #[test]
    fn delete_handler_single_line_buffer_clears_content() {
        let mut ed = make_editor_with_lines(&["only line"]);
        let result = delete_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        // Buffer keeps one empty line rather than zero rows.
        assert_eq!(ed.buffer().row_count(), 1);
        assert_eq!(buf_line(&ed, 0), "");
    }

    #[test]
    fn delete_handler_empty_buffer_returns_ok() {
        let mut ed = make_editor();
        let result = delete_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    // ── sort_handler ─────────────────────────────────────────────────────────

    #[test]
    fn sort_handler_basic_alphabetical() {
        let mut ed = make_editor_with_lines(&["banana", "apple", "cherry"]);
        let result = sort_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert_eq!(lines, vec!["apple", "banana", "cherry"]);
    }

    #[test]
    fn sort_handler_reverse_flag() {
        let mut ed = make_editor_with_lines(&["banana", "apple", "cherry"]);
        let result = sort_handler(&mut ed, "!", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert_eq!(lines, vec!["cherry", "banana", "apple"]);
    }

    #[test]
    fn sort_handler_unique_flag_removes_duplicates() {
        let mut ed = make_editor_with_lines(&["b", "a", "b", "c", "a"]);
        let result = sort_handler(&mut ed, "u", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        // sorted + unique: a, b, c
        assert_eq!(lines, vec!["a", "b", "c"]);
    }

    #[test]
    fn sort_handler_ignore_case_flag() {
        let mut ed = make_editor_with_lines(&["Banana", "apple", "Cherry"]);
        let result = sort_handler(&mut ed, "i", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        // case-insensitive: apple < Banana < Cherry
        let lower: Vec<String> = lines.iter().map(|s| s.to_lowercase()).collect();
        assert_eq!(lower, vec!["apple", "banana", "cherry"]);
    }

    #[test]
    fn sort_handler_numeric_flag() {
        let mut ed = make_editor_with_lines(&["10 items", "2 things", "20 stuff"]);
        let result = sort_handler(&mut ed, "n", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert_eq!(lines[0], "2 things");
        assert_eq!(lines[1], "10 items");
        assert_eq!(lines[2], "20 stuff");
    }

    #[test]
    fn sort_handler_bad_flag_returns_error() {
        let mut ed = make_editor_with_lines(&["a", "b"]);
        let result = sort_handler(&mut ed, "z", None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "got: {result:?}"
        );
    }

    #[test]
    fn sort_handler_range_sorts_only_slice() {
        let mut ed = make_editor_with_lines(&["zzz", "banana", "apple", "aaa"]);
        // Sort lines 2-3 (1-based): "banana","apple" → "apple","banana"
        let range = LineRange::new(2, 3);
        let result = sort_handler(&mut ed, "", Some(range));
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert_eq!(lines[0], "zzz", "line 1 untouched");
        assert_eq!(lines[1], "apple");
        assert_eq!(lines[2], "banana");
        assert_eq!(lines[3], "aaa", "line 4 untouched");
    }

    // ── extract_leading_number (helper) ──────────────────────────────────────

    #[test]
    fn extract_leading_number_positive() {
        assert_eq!(extract_leading_number("42 items"), 42);
    }

    #[test]
    fn extract_leading_number_negative() {
        assert_eq!(extract_leading_number("-5 below zero"), -5);
    }

    #[test]
    fn extract_leading_number_no_number_returns_min() {
        assert_eq!(extract_leading_number("no numbers here"), i64::MIN);
    }

    #[test]
    fn extract_leading_number_bare_minus_returns_min() {
        // "-" with no digits after is not a valid number
        assert_eq!(extract_leading_number("-"), i64::MIN);
    }

    // ── substitute_handler ───────────────────────────────────────────────────

    #[test]
    fn substitute_simple_replace() {
        let mut ed = make_editor_with_lines(&["hello world"]);
        let result = substitute_handler(&mut ed, "/hello/goodbye", None);
        match result {
            Some(ExEffect::Substituted { count, .. }) => {
                assert_eq!(count, 1);
            }
            other => panic!("expected Substituted, got {other:?}"),
        }
        let line = buf_line(&ed, 0);
        assert!(line.contains("goodbye"), "line: {line}");
    }

    #[test]
    fn substitute_global_flag_replaces_all() {
        let mut ed = make_editor_with_lines(&["aXbXcX"]);
        let result = substitute_handler(&mut ed, "/X/Y/g", None);
        match result {
            Some(ExEffect::Substituted { count, .. }) => {
                assert_eq!(count, 3);
            }
            other => panic!("expected Substituted, got {other:?}"),
        }
        assert_eq!(buf_line(&ed, 0), "aYbYcY");
    }

    #[test]
    fn substitute_ignore_case_flag() {
        let mut ed = make_editor_with_lines(&["Hello World"]);
        let result = substitute_handler(&mut ed, "/hello/bye/i", None);
        match result {
            Some(ExEffect::Substituted { count, .. }) => assert!(count >= 1),
            other => panic!("expected Substituted, got {other:?}"),
        }
    }

    #[test]
    fn substitute_no_match_returns_substituted_zero() {
        let mut ed = make_editor_with_lines(&["no match here"]);
        let result = substitute_handler(&mut ed, "/zzz/yyy", None);
        match result {
            Some(ExEffect::Substituted {
                count,
                lines_changed,
            }) => {
                assert_eq!(count, 0);
                assert_eq!(lines_changed, 0);
            }
            other => panic!("expected Substituted, got {other:?}"),
        }
    }

    #[test]
    fn substitute_bad_pattern_returns_error() {
        let mut ed = make_editor_with_lines(&["text"]);
        let result = substitute_handler(&mut ed, "/[bad/ok", None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "got: {result:?}"
        );
    }

    #[test]
    fn substitute_range_limits_scope() {
        let mut ed = make_editor_with_lines(&["foo", "foo", "foo"]);
        // Only substitute on line 2 (1-based).
        let range = LineRange::new(2, 2);
        let result = substitute_handler(&mut ed, "/foo/bar", Some(range));
        match result {
            Some(ExEffect::Substituted { count, .. }) => assert_eq!(count, 1),
            other => panic!("expected Substituted, got {other:?}"),
        }
        assert_eq!(buf_line(&ed, 0), "foo", "line 1 untouched");
        assert_eq!(buf_line(&ed, 1), "bar", "line 2 changed");
        assert_eq!(buf_line(&ed, 2), "foo", "line 3 untouched");
    }

    // ── read_handler ─────────────────────────────────────────────────────────

    #[test]
    fn read_handler_empty_args_returns_none() {
        let mut ed = make_editor_with_lines(&["first"]);
        let result = read_handler(&mut ed, "   ", None);
        assert!(
            result.is_none(),
            "empty args should return None, got {result:?}"
        );
    }

    #[test]
    fn read_handler_missing_file_returns_error() {
        let mut ed = make_editor_with_lines(&["first"]);
        let result = read_handler(&mut ed, "/nonexistent/path/that/does/not/exist.txt", None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "got: {result:?}"
        );
    }

    #[test]
    fn read_handler_file_inserts_content_below_cursor() {
        use std::io::Write;
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        writeln!(tmp, "inserted line").unwrap();
        let path = tmp.path().to_str().unwrap().to_string();

        let mut ed = make_editor_with_lines(&["first"]);
        let result = read_handler(&mut ed, &path, None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert!(
            lines.contains(&"inserted line".to_string()),
            "lines: {lines:?}"
        );
    }

    #[test]
    fn read_handler_shell_cmd_success_inserts_output() {
        let mut ed = make_editor_with_lines(&["first"]);
        let result = read_handler(&mut ed, "!echo hello", None);
        assert_eq!(result, Some(ExEffect::Ok));
        let lines = buf_lines(&ed);
        assert!(lines.contains(&"hello".to_string()), "lines: {lines:?}");
    }

    #[test]
    fn read_handler_shell_cmd_nonzero_exit_returns_error() {
        let mut ed = make_editor_with_lines(&["first"]);
        // `false` always exits 1
        let result = read_handler(&mut ed, "!false", None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "got: {result:?}"
        );
    }

    #[test]
    fn read_handler_shell_cmd_stderr_included_in_error() {
        let mut ed = make_editor_with_lines(&["first"]);
        // Output to stderr then exit non-zero so we can observe it in the error
        let result = read_handler(&mut ed, "!sh -c 'echo boom >&2; exit 1'", None);
        match result {
            Some(ExEffect::Error(msg)) => {
                assert!(msg.contains("boom"), "expected stderr in error, got: {msg}");
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    #[test]
    fn read_handler_empty_shell_cmd_returns_error() {
        let mut ed = make_editor();
        let result = read_handler(&mut ed, "! ", None);
        match result {
            Some(ExEffect::Error(msg)) => {
                assert!(
                    msg.contains("needs a shell command"),
                    "unexpected error: {msg}"
                );
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    // ── set_handler (smoke — deep coverage is in setopt.rs) ──────────────────

    #[test]
    fn set_handler_bare_returns_info() {
        let mut ed = make_editor();
        let result = set_handler(&mut ed, "", None);
        assert!(matches!(result, Some(ExEffect::Info(_))), "got: {result:?}");
    }

    #[test]
    fn set_handler_known_option_returns_ok() {
        let mut ed = make_editor();
        let result = set_handler(&mut ed, "number", None);
        assert_eq!(result, Some(ExEffect::Ok));
        assert!(ed.settings().number);
    }

    #[test]
    fn set_handler_unknown_option_returns_error() {
        let mut ed = make_editor();
        let result = set_handler(&mut ed, "nosuchoption", None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "got: {result:?}"
        );
    }

    // ── :syntax (engine handler is a no-op; app overrides via host registry) ──

    #[test]
    fn syntax_handler_on_returns_ok() {
        let mut ed = make_editor();
        let result = syntax_handler(&mut ed, "on", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    #[test]
    fn syntax_handler_off_returns_ok() {
        let mut ed = make_editor();
        let result = syntax_handler(&mut ed, "off", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    #[test]
    fn syntax_handler_unknown_arg_returns_ok() {
        let mut ed = make_editor();
        let result = syntax_handler(&mut ed, "sync", None);
        assert_eq!(result, Some(ExEffect::Ok));
    }

    #[test]
    fn syntax_resolves_via_prefix_syn() {
        let reg = crate::default_registry::<hjkl_engine::DefaultHost>();
        assert!(reg.resolve("syn").is_some(), ":syn must resolve");
        assert!(reg.resolve("syntax").is_some(), ":syntax must resolve");
        // Below min_prefix=3: must NOT resolve to syntax via prefix path.
        // (`:s` correctly resolves to `substitute` instead.)
        let sy = reg.resolve("sy");
        assert!(
            sy.map(|c| c.name != "syntax").unwrap_or(true),
            "`:sy` must not resolve to syntax (min_prefix=3)"
        );
    }

    // ── register_builtins registry smoke ─────────────────────────────────────

    #[test]
    fn register_builtins_populates_quit_and_write() {
        let mut reg = crate::registry::Registry::<DefaultHost>::new();
        register_builtins(&mut reg);
        assert!(reg.resolve("quit").is_some());
        assert!(reg.resolve("q").is_some());
        assert!(reg.resolve("write").is_some());
        assert!(reg.resolve("w").is_some());
        assert!(reg.resolve("bdelete").is_some());
        assert!(reg.resolve("bd").is_some());
        assert!(reg.resolve("bwipeout").is_some());
        assert!(reg.resolve("bw").is_some());
        assert!(reg.resolve("substitute").is_some());
        assert!(reg.resolve("sort").is_some());
        assert!(reg.resolve("set").is_some());
        assert!(reg.resolve("nohlsearch").is_some());
        assert!(reg.resolve("noh").is_some());
    }

    // ── put_handler ──────────────────────────────────────────────────────────

    #[test]
    fn put_handler_no_args_uses_unnamed_register() {
        let mut ed = make_editor();
        let result = put_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::PutRegister {
                reg: '"',
                above: false
            })
        );
    }

    #[test]
    fn put_handler_with_reg_uses_given_register() {
        let mut ed = make_editor();
        let result = put_handler(&mut ed, "a", None);
        assert_eq!(
            result,
            Some(ExEffect::PutRegister {
                reg: 'a',
                above: false
            })
        );
    }

    #[test]
    fn put_above_handler_no_args_uses_unnamed_register() {
        let mut ed = make_editor();
        let result = put_above_handler(&mut ed, "", None);
        assert_eq!(
            result,
            Some(ExEffect::PutRegister {
                reg: '"',
                above: true
            })
        );
    }

    #[test]
    fn put_handler_percent_register() {
        let mut ed = make_editor();
        let result = put_handler(&mut ed, "%", None);
        assert_eq!(
            result,
            Some(ExEffect::PutRegister {
                reg: '%',
                above: false
            })
        );
    }

    // ── cd_handler / pwd_handler ─────────────────────────────────────────────

    #[test]
    fn cd_handler_valid_dir_returns_cwd() {
        let mut ed = make_editor();
        let tmp = std::env::temp_dir();
        let result = cd_handler(&mut ed, &tmp.to_string_lossy(), None);
        match result {
            Some(ExEffect::Cwd(path)) => {
                assert!(!path.is_empty(), "Cwd path must not be empty");
            }
            other => panic!("expected Cwd, got {other:?}"),
        }
    }

    #[test]
    fn cd_handler_invalid_dir_returns_error() {
        let mut ed = make_editor();
        let bogus = std::env::temp_dir().join("nonexistent_hjkl_test_dir_xyz");
        let result = cd_handler(&mut ed, &bogus.to_string_lossy(), None);
        assert!(
            matches!(result, Some(ExEffect::Error(_))),
            "expected Error, got {result:?}"
        );
    }

    #[test]
    fn pwd_handler_returns_info() {
        let mut ed = make_editor();
        let result = pwd_handler(&mut ed, "", None);
        assert!(
            matches!(result, Some(ExEffect::Info(_))),
            "expected Info, got {result:?}"
        );
    }

    // ── repeat_substitute_handler (:& / :&&) ─────────────────────────────────

    #[test]
    fn repeat_substitute_no_prior_returns_error() {
        let mut ed = make_editor_with_lines(&["foo"]);
        let result = repeat_substitute_handler(&mut ed, false, None);
        assert!(
            matches!(result, ExEffect::Error(_)),
            "expected Error, got {result:?}"
        );
    }

    #[test]
    fn repeat_substitute_repeats_on_current_line() {
        let mut ed = make_editor_with_lines(&["foo", "foo"]);
        substitute_handler(&mut ed, "/foo/bar", None);
        assert_eq!(buf_line(&ed, 0), "bar");
        ed.goto_line(2);
        let result = repeat_substitute_handler(&mut ed, false, None);
        assert!(
            matches!(result, ExEffect::Substituted { count: 1, .. }),
            "expected Substituted(1), got {result:?}"
        );
        assert_eq!(buf_line(&ed, 1), "bar");
    }

    #[test]
    fn repeat_substitute_amp_amp_keeps_global_flag() {
        let mut ed = make_editor_with_lines(&["x x x", "x x x"]);
        substitute_handler(&mut ed, "/x/y/g", None);
        assert_eq!(buf_line(&ed, 0), "y y y");
        ed.goto_line(2);
        let result = repeat_substitute_handler(&mut ed, true, None);
        assert!(
            matches!(result, ExEffect::Substituted { count: 3, .. }),
            "expected Substituted(3), got {result:?}"
        );
        assert_eq!(buf_line(&ed, 1), "y y y");
    }

    #[test]
    fn repeat_substitute_amp_drops_global_flag() {
        let mut ed = make_editor_with_lines(&["x x x", "x x x"]);
        substitute_handler(&mut ed, "/x/y/g", None);
        assert_eq!(buf_line(&ed, 0), "y y y");
        ed.goto_line(2);
        let result = repeat_substitute_handler(&mut ed, false, None);
        assert!(
            matches!(result, ExEffect::Substituted { count: 1, .. }),
            "expected Substituted(1) (first only), got {result:?}"
        );
        assert_eq!(buf_line(&ed, 1), "y x x");
    }

    // ── comment_handler / uncomment_handler (#187) ────────────────────────────

    fn make_rust_editor() -> Editor<hjkl_buffer::Buffer, DefaultHost> {
        let buf = hjkl_buffer::Buffer::from_str("let a = 1;\nlet b = 2;\nlet c = 3;");
        let host = DefaultHost::new();
        let opts = Options {
            filetype: "rust".to_string(),
            ..Options::default()
        };
        Editor::new(buf, host, opts)
    }

    #[test]
    fn comment_handler_gcc_toggles_current_line() {
        let mut ed = make_rust_editor();
        // No range → cursor line (row 0).
        let result = comment_handler(&mut ed, "", None);
        assert_eq!(result, Some(ExEffect::Ok));
        assert_eq!(buf_line(&ed, 0), "// let a = 1;");
        assert_eq!(buf_line(&ed, 1), "let b = 2;");
    }

    #[test]
    fn comment_handler_range_toggles_range() {
        let mut ed = make_rust_editor();
        let range = LineRange::new(1, 3); // 1-based: lines 1–3
        let result = comment_handler(&mut ed, "", Some(range));
        assert_eq!(result, Some(ExEffect::Ok));
        assert_eq!(buf_line(&ed, 0), "// let a = 1;");
        assert_eq!(buf_line(&ed, 1), "// let b = 2;");
        assert_eq!(buf_line(&ed, 2), "// let c = 3;");
    }

    #[test]
    fn comment_handler_whole_buffer_toggle() {
        // :%comment equivalent — toggle all lines.
        let mut ed = make_rust_editor();
        let range = LineRange::new(1, 3);
        comment_handler(&mut ed, "", Some(range));
        // All should be commented now.
        assert!(buf_line(&ed, 0).starts_with("//"));
        assert!(buf_line(&ed, 1).starts_with("//"));
        // Toggle again → all uncommented.
        comment_handler(&mut ed, "", Some(range));
        assert!(!buf_line(&ed, 0).starts_with("//"));
        assert!(!buf_line(&ed, 1).starts_with("//"));
    }

    #[test]
    fn uncomment_handler_strips_comments_idempotent() {
        let buf = hjkl_buffer::Buffer::from_str("// let a = 1;\nlet b = 2;");
        let host = DefaultHost::new();
        let opts = Options {
            filetype: "rust".to_string(),
            ..Options::default()
        };
        let mut ed = Editor::new(buf, host, opts);
        let range = LineRange::new(1, 2);
        let result = uncomment_handler(&mut ed, "", Some(range));
        assert_eq!(result, Some(ExEffect::Ok));
        // Line 0: comment stripped.
        assert_eq!(buf_line(&ed, 0), "let a = 1;");
        // Line 1: already uncommented — unchanged.
        assert_eq!(buf_line(&ed, 1), "let b = 2;");
    }

    #[test]
    fn mixed_state_range_gets_fully_commented() {
        // 3 uncommented + 2 commented → all 5 get commented (vim-commentary parity).
        let buf = hjkl_buffer::Buffer::from_str(
            "let a = 1;\n// let b = 2;\nlet c = 3;\n// let d = 4;\nlet e = 5;",
        );
        let host = DefaultHost::new();
        let opts = Options {
            filetype: "rust".to_string(),
            ..Options::default()
        };
        let mut ed = Editor::new(buf, host, opts);
        let range = LineRange::new(1, 5);
        comment_handler(&mut ed, "", Some(range));
        for row in 0..5 {
            let l = buf_line(&ed, row);
            assert!(
                l.trim_start().starts_with("//"),
                "row {row} should be commented; got {l:?}"
            );
        }
    }
}