summaryrefslogtreecommitdiff
path: root/src/modal.zig
blob: 8e36d1ae5480794870ea987cad4869a89cd9334a (plain) (blame)
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
const std = @import("std");

// Modal-editing text math, kept free of vaxis/ghostty so it can be unit-tested
// in isolation (see the `unit-test` build step). main.zig wires this onto the
// pane's cursor + (for file panes) its content.
//
// The cursor sits ON a character: col is a char index in [0, line.len]; col ==
// line.len means "on the line terminator / after the last char". Motions are
// written to land on real characters; main.zig clamps for display.

pub const Cursor = struct {
    row: usize = 0,
    col: usize = 0,

    pub fn eql(a: Cursor, b: Cursor) bool {
        return a.row == b.row and a.col == b.col;
    }
};

// word char classes (matches ad/vim/kakoune: word = alnum + _, punct = other
// non-ws, ws = space/tab/newline).
pub const Kind = enum { word, punct, ws };

pub fn kindOf(c: u8) Kind {
    if (c == ' ' or c == '\t' or c == '\n' or c == '\r') return .ws;
    if (std.ascii.isAlphanumeric(c) or c == '_') return .word;
    return .punct;
}

// "long word" (W/B/E): only whitespace separates; punct is part of a word.
fn kindOfLong(c: u8) Kind {
    if (c == ' ' or c == '\t' or c == '\n' or c == '\r') return .ws;
    return .word;
}

fn kindAt(lines: []const []const u8, c: Cursor, long: bool) Kind {
    if (c.row >= lines.len) return .ws;
    const line = lines[c.row];
    if (c.col >= line.len) return .ws; // line terminator / EOF = whitespace
    return if (long) kindOfLong(line[c.col]) else kindOf(line[c.col]);
}

fn lineLenOf(lines: []const []const u8, row: usize) usize {
    if (row >= lines.len) return 0;
    return lines[row].len;
}

// advance one position across line boundaries (line terminators are positions
// too: col == line.len is the newline). Returns false at EOF.
fn stepFwd(lines: []const []const u8, c: *Cursor) bool {
    if (c.row >= lines.len) return false;
    const llen = lineLenOf(lines, c.row);
    if (c.col < llen) {
        c.col += 1;
        return true;
    }
    // at the newline: move to next line start
    if (c.row + 1 < lines.len) {
        c.row += 1;
        c.col = 0;
        return true;
    }
    return false; // EOF
}

fn stepBwd(lines: []const []const u8, c: *Cursor) bool {
    if (c.col > 0) {
        c.col -= 1;
        return true;
    }
    if (c.row == 0) return false;
    c.row -= 1;
    c.col = lineLenOf(lines, c.row); // the previous line's newline
    return true;
}

// at EOF? (past the last line's last char)
fn atEof(lines: []const []const u8, c: Cursor) bool {
    if (c.row >= lines.len) return true;
    if (c.row + 1 < lines.len) return false;
    return c.col >= lines[c.row].len;
}

pub fn firstNonWs(line: []const u8) usize {
    var i: usize = 0;
    while (i < line.len and (line[i] == ' ' or line[i] == '\t')) i += 1;
    return i;
}

// ---- per-line motions ----

pub fn lineStart(c: Cursor) Cursor {
    return .{ .row = c.row, .col = 0 };
}

pub fn lineEnd(lines: []const []const u8, c: Cursor) Cursor {
    const llen = lineLenOf(lines, c.row);
    return .{ .row = c.row, .col = if (llen == 0) 0 else llen - 1 };
}

pub fn firstNonWsOf(lines: []const []const u8, c: Cursor) Cursor {
    // the row can sit past the content (mouse click below a short pane's
    // last line) — out of range reads as an empty line, like lineLenOf
    if (c.row >= lines.len) return .{ .row = c.row, .col = 0 };
    return .{ .row = c.row, .col = firstNonWs(lines[c.row]) };
}

// ---- char/line motions ----

pub fn charLeft(c: Cursor) Cursor {
    return .{ .row = c.row, .col = if (c.col > 0) c.col - 1 else 0 };
}

pub fn charRight(lines: []const []const u8, c: Cursor) Cursor {
    const llen = lineLenOf(lines, c.row);
    const last = if (llen == 0) 0 else llen - 1;
    return .{ .row = c.row, .col = if (c.col < last) c.col + 1 else last };
}

pub fn lineDown(lines: []const []const u8, c: Cursor) Cursor {
    const nr = if (c.row + 1 < lines.len) c.row + 1 else c.row;
    const llen = lineLenOf(lines, nr);
    const last = if (llen == 0) 0 else llen - 1;
    return .{ .row = nr, .col = if (c.col < last) c.col else last };
}

pub fn lineUp(lines: []const []const u8, c: Cursor) Cursor {
    const nr = if (c.row > 0) c.row - 1 else c.row;
    const llen = lineLenOf(lines, nr);
    const last = if (llen == 0) 0 else llen - 1;
    return .{ .row = nr, .col = if (c.col < last) c.col else last };
}

// ---- word motions ----

// `w`/`W`: to the start of the next word.
pub fn nextWordStart(lines: []const []const u8, c: Cursor, long: bool) Cursor {
    var p = c;
    const start_kind = kindAt(lines, p, long);
    if (start_kind != .ws) {
        // skip the rest of the current word-class run
        while (!atEof(lines, p) and kindAt(lines, p, long) == start_kind) {
            if (!stepFwd(lines, &p)) break;
        }
    }
    // skip whitespace (incl. newlines) to the next word start
    while (!atEof(lines, p) and kindAt(lines, p, long) == .ws) {
        if (!stepFwd(lines, &p)) break;
    }
    // p now sits on the next word's first char (or EOF -> last valid pos)
    return clampToChar(lines, p);
}

// `b`/`B`: to the start of the previous word.
pub fn prevWordStart(lines: []const []const u8, c: Cursor, long: bool) Cursor {
    var p = c;
    if (!stepBwd(lines, &p)) return c; // at buffer start
    // skip whitespace backward
    while (kindAt(lines, p, long) == .ws) {
        if (!stepBwd(lines, &p)) return .{ .row = 0, .col = 0 };
    }
    // now on the end of the previous word; walk back to its start
    const k = kindAt(lines, p, long);
    while (true) {
        var q = p;
        if (!stepBwd(lines, &q)) {
            p.col = 0;
            break;
        }
        if (kindAt(lines, q, long) != k) break; // crossed into prior class
        p = q;
    }
    return clampToChar(lines, p);
}

// `e`/`E`: to the end of the current/next word.
pub fn nextWordEnd(lines: []const []const u8, c: Cursor, long: bool) Cursor {
    var p = c;
    if (!stepFwd(lines, &p)) return clampToChar(lines, c);
    // skip whitespace forward
    while (!atEof(lines, p) and kindAt(lines, p, long) == .ws) {
        if (!stepFwd(lines, &p)) break;
    }
    if (atEof(lines, p)) return clampToChar(lines, p);
    // now on a word's first char; advance to the last char of this run
    const k = kindAt(lines, p, long);
    while (!atEof(lines, p)) {
        var q = p;
        if (!stepFwd(lines, &q)) break;
        if (kindAt(lines, q, long) != k) break;
        p = q;
    }
    return clampToChar(lines, p);
}

// ---- goto ----

pub fn gotoFirst() Cursor {
    return .{ .row = 0, .col = 0 };
}

pub fn gotoLast(lines: []const []const u8) Cursor {
    const r = if (lines.len == 0) 0 else lines.len - 1;
    return .{ .row = r, .col = 0 };
}

// half/full page: target row, caller clamps + scrolls.
pub fn pageDown(c: Cursor, page: usize) Cursor {
    return .{ .row = c.row + page, .col = c.col };
}

pub fn pageUp(c: Cursor, page: usize) Cursor {
    return .{ .row = if (c.row > page) c.row - page else 0, .col = c.col };
}

// the character the cursor sits on; line terminators / EOF read as '\n'.
fn charAt(lines: []const []const u8, c: Cursor) u8 {
    if (c.row >= lines.len) return '\n';
    const line = lines[c.row];
    if (c.col >= line.len) return '\n';
    return line[c.col];
}

// `f`/`F`/`t`/`T`: the nth occurrence of `ch` after/before the cursor, across
// line boundaries (helix: not confined to the line). `till` stops one position
// short of the hit. Returns null (no move) when there aren't n occurrences.
pub fn findChar(lines: []const []const u8, c: Cursor, ch: u21, fwd: bool, till: bool, n: usize) ?Cursor {
    if (ch > 0x7f) return null; // ponytail: ASCII targets only (byte columns)
    const target: u8 = @intCast(ch);
    var p = clampToChar(lines, c);
    var left = if (n == 0) 1 else n;
    while (left > 0) {
        if (fwd) {
            if (!stepFwd(lines, &p)) return null;
        } else {
            if (!stepBwd(lines, &p)) return null;
        }
        if (charAt(lines, p) == target) left -= 1;
    }
    if (till) {
        if (fwd) _ = stepBwd(lines, &p) else _ = stepFwd(lines, &p);
    }
    return clampToChar(lines, p);
}

// `mm`: the bracket matching the one under the cursor (dumb text scan with
// nesting; no tree-sitter). Null when the cursor is not on a bracket.
pub fn matchBracket(lines: []const []const u8, c: Cursor) ?Cursor {
    const opens = "([{<";
    const closes = ")]}>";
    const start = clampToChar(lines, c);
    const ch = charAt(lines, start);
    if (std.mem.indexOfScalar(u8, opens, ch)) |i| {
        var depth: usize = 0;
        var p = start;
        while (true) {
            const cc = charAt(lines, p);
            if (cc == opens[i]) depth += 1;
            if (cc == closes[i]) {
                depth -= 1;
                if (depth == 0) return p;
            }
            if (!stepFwd(lines, &p)) return null;
        }
    }
    if (std.mem.indexOfScalar(u8, closes, ch)) |i| {
        var depth: usize = 0;
        var p = start;
        while (true) {
            const cc = charAt(lines, p);
            if (cc == closes[i]) depth += 1;
            if (cc == opens[i]) {
                depth -= 1;
                if (depth == 0) return p;
            }
            if (!stepBwd(lines, &p)) return null;
        }
    }
    return null;
}

fn isBlank(line: []const u8) bool {
    return firstNonWs(line) == line.len;
}

// `]p`: the start of the next blank-line-delimited block (or the last line).
pub fn paragraphFwd(lines: []const []const u8, c: Cursor) Cursor {
    var r = c.row;
    while (r < lines.len and !isBlank(lines[r])) r += 1;
    while (r < lines.len and isBlank(lines[r])) r += 1;
    if (r >= lines.len) return gotoLast(lines);
    return .{ .row = r, .col = 0 };
}

// `[p`: the start of the current block, or of the previous one when already
// on a block start / a blank line.
pub fn paragraphBwd(lines: []const []const u8, c: Cursor) Cursor {
    if (c.row == 0 or lines.len == 0) return .{ .row = 0, .col = 0 };
    var r = @min(c.row, lines.len) - 1;
    while (r > 0 and isBlank(lines[r])) r -= 1;
    while (r > 0 and !isBlank(lines[r - 1])) r -= 1;
    return .{ .row = r, .col = 0 };
}

// ---- textobject / surround range math (mi/ma/ms/mr/md) ----

// an inclusive char range [a, b] in document order
pub const Range = struct { a: Cursor, b: Cursor };

// the nearest pair of brackets enclosing the cursor (nesting-aware; the
// cursor sitting ON a bracket belongs to that pair). Positions of the
// bracket chars themselves.
pub fn enclosingPair(lines: []const []const u8, c: Cursor, open: u8, close: u8) ?Range {
    var a = clampToChar(lines, c);
    if (charAt(lines, a) != open) {
        var depth: usize = 0;
        while (true) {
            if (!stepBwd(lines, &a)) return null;
            const ch = charAt(lines, a);
            if (ch == close) depth += 1;
            if (ch == open) {
                if (depth == 0) break;
                depth -= 1;
            }
        }
    }
    const b = matchBracket(lines, a) orelse return null;
    return .{ .a = a, .b = b };
}

// the quote pair around the cursor, scanned on the cursor's line only
// (plain-text strings don't span lines). Positions of the quote chars.
pub fn enclosingQuote(lines: []const []const u8, c0: Cursor, q: u8) ?Range {
    const c = clampToChar(lines, c0);
    if (c.row >= lines.len) return null;
    const line = lines[c.row];
    var i: usize = 0;
    while (i < line.len) {
        const o = std.mem.indexOfScalarPos(u8, line, i, q) orelse return null;
        const e = std.mem.indexOfScalarPos(u8, line, o + 1, q) orelse return null;
        if (c.col < o) return null; // the cursor sits before any pair
        if (c.col <= e) return .{ .a = .{ .row = c.row, .col = o }, .b = .{ .row = c.row, .col = e } };
        i = e + 1;
    }
    return null;
}

// mi/ma over a bracket pair: `around` keeps the brackets, inside shrinks them
// off (null when nothing is left between them).
pub fn pairRange(lines: []const []const u8, c: Cursor, open: u8, close: u8, around: bool) ?Range {
    const r = enclosingPair(lines, c, open, close) orelse return null;
    if (around) return r;
    return shrinkOffDelims(lines, r);
}

pub fn quoteRange(lines: []const []const u8, c: Cursor, q: u8, around: bool) ?Range {
    const r = enclosingQuote(lines, c, q) orelse return null;
    if (around) return r;
    return shrinkOffDelims(lines, r);
}

fn shrinkOffDelims(lines: []const []const u8, r: Range) ?Range {
    var a = r.a;
    var b = r.b;
    if (!stepFwd(lines, &a)) return null;
    if (!stepBwd(lines, &b)) return null;
    if (b.row < a.row or (b.row == a.row and b.col < a.col)) return null; // empty inside
    return .{ .a = a, .b = b };
}

// miw/maw (and W): the word run under the cursor; `around` adds the trailing
// whitespace on the line (or the leading run when there is none).
pub fn wordRange(lines: []const []const u8, c0: Cursor, long: bool, around: bool) ?Range {
    const c = clampToChar(lines, c0);
    if (c.row >= lines.len) return null;
    const line = lines[c.row];
    if (line.len == 0 or c.col >= line.len) return null;
    const k = kindAt(lines, c, long);
    if (k == .ws) return null;
    var lo = c.col;
    while (lo > 0 and kindAt(lines, .{ .row = c.row, .col = lo - 1 }, long) == k) lo -= 1;
    var hi = c.col;
    while (hi + 1 < line.len and kindAt(lines, .{ .row = c.row, .col = hi + 1 }, long) == k) hi += 1;
    if (around) {
        var h2 = hi;
        while (h2 + 1 < line.len and (line[h2 + 1] == ' ' or line[h2 + 1] == '\t')) h2 += 1;
        if (h2 != hi) {
            hi = h2;
        } else {
            while (lo > 0 and (line[lo - 1] == ' ' or line[lo - 1] == '\t')) lo -= 1;
        }
    }
    return .{ .a = .{ .row = c.row, .col = lo }, .b = .{ .row = c.row, .col = hi } };
}

// mip/map: the blank-line-delimited block around the cursor; `around` adds the
// trailing blank lines (or the leading ones when there are none).
pub fn paragraphRange(lines: []const []const u8, c0: Cursor, around: bool) ?Range {
    const c = clampToChar(lines, c0);
    if (c.row >= lines.len or isBlank(lines[c.row])) return null;
    var r0 = c.row;
    while (r0 > 0 and !isBlank(lines[r0 - 1])) r0 -= 1;
    var r1 = c.row;
    while (r1 + 1 < lines.len and !isBlank(lines[r1 + 1])) r1 += 1;
    if (around) {
        var r2 = r1;
        while (r2 + 1 < lines.len and isBlank(lines[r2 + 1])) r2 += 1;
        if (r2 != r1) {
            r1 = r2;
        } else {
            while (r0 > 0 and isBlank(lines[r0 - 1])) r0 -= 1;
        }
    }
    const llen = lineLenOf(lines, r1);
    return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = if (llen == 0) 0 else llen - 1 } };
}

// ---- helpers used by motions + main.zig ----

// clamp a (possibly terminator/EOF) position onto a real character.
pub fn clampToChar(lines: []const []const u8, c: Cursor) Cursor {
    if (c.row >= lines.len) {
        return .{ .row = if (lines.len == 0) 0 else lines.len - 1, .col = 0 };
    }
    const llen = lineLenOf(lines, c.row);
    if (llen == 0) return .{ .row = c.row, .col = 0 };
    return .{ .row = c.row, .col = @min(c.col, llen - 1) };
}

pub fn lineCount(content: []const u8) usize {
    if (content.len == 0) return 0;
    return std.mem.count(u8, content, "\n") + 1;
}

// byte offset of the start of line `row` (0-based). row may == lineCount()
// (== content.len, the end).
pub fn lineStartOffset(content: []const u8, row: usize) usize {
    var off: usize = 0;
    var r: usize = 0;
    while (r < row) : (r += 1) {
        const nl = std.mem.indexOfScalarPos(u8, content, off, '\n') orelse return content.len;
        off = nl + 1;
    }
    return off;
}

// the text of line `row` (no terminator), a slice into `content`.
pub fn lineSlice(content: []const u8, row: usize) []const u8 {
    const start = lineStartOffset(content, row);
    if (start >= content.len) return "";
    const nl = std.mem.indexOfPos(u8, content, start, "\n") orelse content.len;
    return content[start..nl];
}

// ---- file content mutations. caller frees the returned slice + the old one. ----

// insert `text` at (row, col). col is clamped to the line length.
pub fn insertAt(alloc: std.mem.Allocator, content: []const u8, c: Cursor, text: []const u8) ![]u8 {
    const row = if (c.row >= lineCount(content)) lineCount(content) -| 1 else c.row;
    const line = lineSlice(content, row);
    const col = @min(c.col, line.len);
    const off = lineStartOffset(content, row) + col;
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..off]);
    try out.appendSlice(alloc, text);
    try out.appendSlice(alloc, content[off..]);
    return out.toOwnedSlice(alloc);
}

// delete the character at (row, col). no-op if col is past the line end.
pub fn deleteChar(alloc: std.mem.Allocator, content: []const u8, c: Cursor) ![]u8 {
    const line = lineSlice(content, c.row);
    if (c.col >= line.len) return alloc.dupe(u8, content);
    const off = lineStartOffset(content, c.row) + c.col;
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..off]);
    try out.appendSlice(alloc, content[off + 1 ..]);
    return out.toOwnedSlice(alloc);
}

// delete whole lines [r0, r1] inclusive (the line content + their terminators).
// returns the new content; `deleted` is the joined removed text (no terminators).
pub const Deleted = struct { content: []u8, deleted: []u8 };

pub fn deleteLines(alloc: std.mem.Allocator, content: []const u8, r0: usize, r1: usize) !Deleted {
    const n = lineCount(content);
    const lo = @min(r0, r1);
    const hi = @min(@max(r0, r1), if (n == 0) 0 else n - 1);
    if (n == 0 or hi < lo) return .{ .content = try alloc.dupe(u8, content), .deleted = try alloc.dupe(u8, "") };

    const start = lineStartOffset(content, lo);
    // end = start of line (hi+1), or content.len if hi is the last line.
    const end = if (hi + 1 < n) lineStartOffset(content, hi + 1) else content.len;
    // if we're removing the last line and there's a preceding newline, also
    // drop that newline so we don't leave a trailing blank line.
    var cut_lo = start;
    const cut_hi = end;
    if (hi + 1 == n and start > 0) cut_lo -= 1; // remove the '\n' before the last line

    var deleted: std.ArrayList(u8) = .empty;
    {
        var r = lo;
        while (r <= hi) : (r += 1) {
            if (r > lo) try deleted.append(alloc, '\n');
            try deleted.appendSlice(alloc, lineSlice(content, r));
        }
    }
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..cut_lo]);
    try out.appendSlice(alloc, content[cut_hi..]);
    return .{ .content = try out.toOwnedSlice(alloc), .deleted = try deleted.toOwnedSlice(alloc) };
}

// normalize two cursors into document order (lo <= hi), then byte offsets of the
// INCLUSIVE range [lo .. hi] (the char under hi is included). e == s means empty.
fn rangeBytes(content: []const u8, a: Cursor, b: Cursor) struct { s: usize, e: usize } {
    var lo = a;
    var hi = b;
    if (hi.row < lo.row or (hi.row == lo.row and hi.col < lo.col)) {
        lo = b;
        hi = a;
    }
    const s = lineStartOffset(content, lo.row) + @min(lo.col, lineSlice(content, lo.row).len);
    var e = lineStartOffset(content, hi.row) + @min(hi.col, lineSlice(content, hi.row).len);
    if (e < content.len) e += 1; // include the char under the head
    return .{ .s = s, .e = @max(s, e) };
}

// the text of the inclusive char range [a, b] (cursors in either order). Caller frees.
pub fn rangeText(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor) ![]u8 {
    const r = rangeBytes(content, a, b);
    return alloc.dupe(u8, content[r.s..r.e]);
}

// delete the inclusive char range [a, b]. returns new content + the removed text.
pub fn deleteRange(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor) !Deleted {
    const r = rangeBytes(content, a, b);
    const deleted = try alloc.dupe(u8, content[r.s..r.e]);
    errdefer alloc.free(deleted);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..r.s]);
    try out.appendSlice(alloc, content[r.e..]);
    return .{ .content = try out.toOwnedSlice(alloc), .deleted = deleted };
}

// replace line `row`'s text with "" (keep the line, empty it). For `c`hange line.
pub fn clearLine(alloc: std.mem.Allocator, content: []const u8, row: usize) ![]u8 {
    const line = lineSlice(content, row);
    const start = lineStartOffset(content, row);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..start]);
    try out.appendSlice(alloc, content[start + line.len ..]);
    return out.toOwnedSlice(alloc);
}

// paste `text` as a new line BELOW `row`. Multiline `text` becomes several lines.
pub fn pasteLineBelow(alloc: std.mem.Allocator, content: []const u8, row: usize, text: []const u8) ![]u8 {
    const n = lineCount(content);
    const off = if (row + 1 < n) lineStartOffset(content, row + 1) else content.len;
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..off]);
    if (off < content.len or (content.len > 0 and content[content.len - 1] == '\n')) {
        // mid-buffer, or below the last line of newline-terminated content:
        // the pasted block carries its own terminator
        try out.appendSlice(alloc, text);
        try out.append(alloc, '\n');
    } else {
        // below a terminator-less last line: open it with a newline instead
        if (off > 0) try out.append(alloc, '\n');
        try out.appendSlice(alloc, text);
    }
    try out.appendSlice(alloc, content[off..]);
    return out.toOwnedSlice(alloc);
}

// the cursor position AFTER `text` inserted at `c` (one past its last char).
pub fn advanceBy(c: Cursor, text: []const u8) Cursor {
    var r = c.row;
    var col = c.col;
    for (text) |ch| {
        if (ch == '\n') {
            r += 1;
            col = 0;
        } else col += 1;
    }
    return .{ .row = r, .col = col };
}

// replace the inclusive char range [a, b] with `text` (R replace-with-yank).
pub fn replaceRange(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor, text: []const u8) ![]u8 {
    const r = rangeBytes(content, a, b);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..r.s]);
    try out.appendSlice(alloc, text);
    try out.appendSlice(alloc, content[r.e..]);
    return out.toOwnedSlice(alloc);
}

// `r<ch>`: overwrite every char in the inclusive range [a, b] with `ch` —
// NEWLINES TOO (helix replace maps every grapheme, so `xrz` joins lines).
pub fn replaceChars(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor, ch: u8) ![]u8 {
    const r = rangeBytes(content, a, b);
    const out = try alloc.dupe(u8, content);
    for (out[r.s..r.e]) |*p| p.* = ch;
    return out;
}

// `~` / `` ` `` / ``Alt-` ``: case-map the inclusive range [a, b].
pub const CaseOp = enum { toggle, lower, upper };

pub fn changeCase(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor, op: CaseOp) ![]u8 {
    const r = rangeBytes(content, a, b);
    const out = try alloc.dupe(u8, content);
    for (out[r.s..r.e]) |*p| {
        p.* = switch (op) {
            .toggle => if (std.ascii.isUpper(p.*)) std.ascii.toLower(p.*) else std.ascii.toUpper(p.*),
            .lower => std.ascii.toLower(p.*),
            .upper => std.ascii.toUpper(p.*),
        };
    }
    return out;
}

// `J`: join line `row` with the next — the newline and the next line's leading
// whitespace become one space (helix join). `col` is the space's column.
// Null when `row` is the last line.
pub fn joinLine(alloc: std.mem.Allocator, content: []const u8, row: usize) !?struct { content: []u8, col: usize } {
    if (row + 1 >= lineCount(content)) return null;
    const a = lineSlice(content, row);
    const next = lineSlice(content, row + 1);
    const b = std.mem.trimStart(u8, next, " \t");
    const start = lineStartOffset(content, row);
    const rest = lineStartOffset(content, row + 1) + (next.len - b.len);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0 .. start + a.len]);
    try out.append(alloc, ' ');
    try out.appendSlice(alloc, content[rest..]);
    return .{ .content = try out.toOwnedSlice(alloc), .col = a.len };
}

// `>` / `<`: indent/unindent lines [r0, r1]. Fixed width — pardes has no
// per-language indent config; 4 spaces, one tab counts as one level out.
pub const INDENT_W = 4;

pub fn indentLines(alloc: std.mem.Allocator, content: []const u8, r0: usize, r1: usize, add: bool) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    var it = std.mem.splitScalar(u8, content, '\n');
    var row: usize = 0;
    while (it.next()) |line| : (row += 1) {
        if (row > 0) try out.append(alloc, '\n');
        if (row >= @min(r0, r1) and row <= @max(r0, r1)) {
            if (add) {
                if (line.len != 0) try out.appendSlice(alloc, " " ** INDENT_W); // empty lines stay empty (helix)
                try out.appendSlice(alloc, line);
            } else {
                var cut: usize = 0;
                if (line.len > 0 and line[0] == '\t') {
                    cut = 1;
                } else while (cut < line.len and cut < INDENT_W and line[cut] == ' ') cut += 1;
                try out.appendSlice(alloc, line[cut..]);
            }
        } else try out.appendSlice(alloc, line);
    }
    return out.toOwnedSlice(alloc);
}

// `Ctrl-a`/`Ctrl-x`: add `delta` to the decimal integer under the cursor
// (helix: under the cursor only, no forward scan). Null when the cursor is
// not on a number. The new cursor sits on the number's last digit.
pub fn adjustNumber(alloc: std.mem.Allocator, content: []const u8, c: Cursor, delta: i64) !?struct { content: []u8, cur: Cursor } {
    const line = lineSlice(content, c.row);
    if (c.col >= line.len) return null;
    var s = c.col;
    var e = c.col;
    if (!std.ascii.isDigit(line[s])) {
        // sitting on the '-' of a negative number counts
        if (!(line[s] == '-' and s + 1 < line.len and std.ascii.isDigit(line[s + 1]))) return null;
        e = s + 1;
    }
    while (s > 0 and std.ascii.isDigit(line[s - 1])) s -= 1;
    if (s > 0 and line[s - 1] == '-') s -= 1;
    while (e < line.len and std.ascii.isDigit(line[e])) e += 1;
    const val = std.fmt.parseInt(i64, line[s..e], 10) catch return null;
    const nv = val +| delta;
    var buf: [24]u8 = undefined;
    // "{d}" prints '+' for positive signed ints — format the magnitude unsigned
    const numstr = if (nv < 0)
        std.fmt.bufPrint(&buf, "-{d}", .{@abs(nv)}) catch return null
    else
        std.fmt.bufPrint(&buf, "{d}", .{@abs(nv)}) catch return null;
    const off = lineStartOffset(content, c.row);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0 .. off + s]);
    try out.appendSlice(alloc, numstr);
    try out.appendSlice(alloc, content[off + e ..]);
    return .{ .content = try out.toOwnedSlice(alloc), .cur = .{ .row = c.row, .col = s + numstr.len - 1 } };
}

// delete the EXCLUSIVE span [a, b) — insert-mode kills. col may equal the
// line length (the newline); a kill crossing it passes b = (row+1, 0).
pub fn deleteSpan(alloc: std.mem.Allocator, content: []const u8, a: Cursor, b: Cursor) ![]u8 {
    const s = lineStartOffset(content, a.row) + @min(a.col, lineSlice(content, a.row).len);
    const e = lineStartOffset(content, b.row) + @min(b.col, lineSlice(content, b.row).len);
    if (e <= s) return alloc.dupe(u8, content);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(alloc, content[0..s]);
    try out.appendSlice(alloc, content[e..]);
    return out.toOwnedSlice(alloc);
}

// ---- helix range engine (phase 5) ----
//
// Gap-offset ranges over the FLAT buffer, ported faithfully from
// helix-core/src/movement.rs + selection.rs @ 278b24389 (the genizah
// checkout). Positions are gap offsets 0..=text.len — "char indices" in
// helix terms, bytes here (ASCII-exact; UTF-8 stepped by sequence, matching
// the byte-column convention of the rest of pardes). A range with
// head > anchor selects [anchor, head) with the block cursor ON head-1;
// head < anchor selects [head, anchor) with the cursor ON head. The
// differential suite (test/hxcases, `zig build hxdiff`) pins every behavior
// here key-for-key against a real helix.

pub const HxRange = struct { anchor: usize, head: usize };

/// one grapheme forward (UTF-8 sequence step), clamped at text.len
pub fn nextGrapheme(text: []const u8, off: usize) usize {
    if (off >= text.len) return text.len;
    var o = off + 1;
    while (o < text.len and (text[o] & 0xC0) == 0x80) o += 1;
    return o;
}

pub fn prevGrapheme(text: []const u8, off: usize) usize {
    if (off == 0) return 0;
    var o = off - 1;
    while (o > 0 and (text[o] & 0xC0) == 0x80) o -= 1;
    return o;
}

/// the block cursor cell of a range (helix Range::cursor)
pub fn hxCursor(text: []const u8, r: HxRange) usize {
    return if (r.head > r.anchor) prevGrapheme(text, r.head) else r.head;
}

/// helix Range::put_cursor: park the block cursor at cell `idx`, optionally
/// extending — the anchor shifts one grapheme when the head crosses it so the
/// anchor CELL stays fixed.
pub fn hxPutCursor(text: []const u8, r: HxRange, idx: usize, extend: bool) HxRange {
    if (!extend) return .{ .anchor = idx, .head = idx };
    var anchor = r.anchor;
    if (r.head >= r.anchor and idx < r.anchor) {
        anchor = nextGrapheme(text, r.anchor);
    } else if (r.head < r.anchor and idx >= r.anchor) {
        anchor = prevGrapheme(text, r.anchor);
    }
    if (anchor <= idx) return .{ .anchor = anchor, .head = nextGrapheme(text, idx) };
    return .{ .anchor = anchor, .head = idx };
}

// ropey-style line math: len_lines = count('\n') + 1 — the slot after a
// trailing '\n' is a real, empty last line and the cursor can sit there.
pub fn hxLineCount(text: []const u8) usize {
    return std.mem.count(u8, text, "\n") + 1;
}

pub fn hxLineOf(text: []const u8, off: usize) usize {
    return std.mem.count(u8, text[0..@min(off, text.len)], "\n");
}

/// offset of line's terminator ('\n'), or text.len on the last line
pub fn hxLineEndIdx(text: []const u8, line: usize) usize {
    const s = lineStartOffset(text, line);
    return if (std.mem.indexOfScalarPos(u8, text, s, '\n')) |nl| nl else text.len;
}

/// gap offset -> (row, col) cell
pub fn hxPos(text: []const u8, off: usize) Cursor {
    const o = @min(off, text.len);
    // The line start is the byte after the last '\n' BEFORE off, which is the
    // same number lineStartOffset(text, row) walks the whole prefix to reach —
    // one backward scan of a single line instead of a second pass over
    // everything above the cursor. On a multi-MB buffer that second pass was
    // most of what a keystroke cost.
    const s = if (std.mem.lastIndexOfScalar(u8, text[0..o], '\n')) |nl| nl + 1 else 0;
    return .{ .row = hxLineOf(text, off), .col = o - s };
}

/// (row, col) -> clamped gap offset; col == line length lands ON the '\n'
pub fn hxOff(text: []const u8, c: Cursor) usize {
    const row = @min(c.row, hxLineCount(text) - 1);
    const s = lineStartOffset(text, row);
    // hxLineEndIdx(text, row) inlined: it starts by walking to `row` again,
    // and we are already standing there
    const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len;
    return @min(s + c.col, e);
}

pub const WordTarget = enum {
    next_word_start,
    next_word_end,
    prev_word_start,
    prev_word_end,
    next_long_word_start,
    next_long_word_end,
    prev_long_word_start,
    prev_long_word_end,
};

// helix categorize_char: Eol is its OWN category, distinct from Whitespace —
// that distinction is load-bearing in reached_target.
const HxCat = enum { word, punct, ws, eol };

fn hxCat(b: u8) HxCat {
    if (b == '\n' or b == '\r') return .eol;
    if (b == ' ' or b == '\t' or b == 0x0b or b == 0x0c) return .ws;
    if (std.ascii.isAlphanumeric(b) or b == '_' or b >= 0x80) return .word;
    return .punct;
}

fn hxIsWs(b: u8) bool { // Rust char::is_whitespace (includes line endings)
    const c = hxCat(b);
    return c == .ws or c == .eol;
}

fn hxIsWordBoundary(a: u8, b: u8) bool {
    return hxCat(a) != hxCat(b);
}

fn hxIsLongBoundary(a: u8, b: u8) bool {
    const ca = hxCat(a);
    const cb = hxCat(b);
    if ((ca == .word and cb == .punct) or (ca == .punct and cb == .word)) return false;
    return ca != cb;
}

fn hxReached(target: WordTarget, prev: u8, next: u8) bool {
    return switch (target) {
        .next_word_start, .prev_word_end => hxIsWordBoundary(prev, next) and (hxCat(next) == .eol or !hxIsWs(next)),
        .next_word_end, .prev_word_start => hxIsWordBoundary(prev, next) and (!hxIsWs(prev) or hxCat(next) == .eol),
        .next_long_word_start, .prev_long_word_end => hxIsLongBoundary(prev, next) and (hxCat(next) == .eol or !hxIsWs(next)),
        .next_long_word_end, .prev_long_word_start => hxIsLongBoundary(prev, next) and (!hxIsWs(prev) or hxCat(next) == .eol),
    };
}

fn wmIsPrev(t: WordTarget) bool {
    return switch (t) {
        .prev_word_start, .prev_word_end, .prev_long_word_start, .prev_long_word_end => true,
        else => false,
    };
}

/// w/b/e/W/B/E: helix word_move — each step selects the traversed span.
pub fn hxWordMove(text: []const u8, r0: HxRange, count: usize, target: WordTarget) HxRange {
    const is_prev = wmIsPrev(target);
    if ((is_prev and r0.head == 0) or (!is_prev and r0.head == text.len)) return r0;
    // block-cursor prep: collapse to the 1-wide cell at the head, pointing
    // in the motion direction (the anchor of the input is irrelevant)
    var r: HxRange = if (is_prev)
        (if (r0.anchor < r0.head)
            .{ .anchor = r0.head, .head = prevGrapheme(text, r0.head) }
        else
            .{ .anchor = nextGrapheme(text, r0.head), .head = r0.head })
    else
        (if (r0.anchor < r0.head)
            .{ .anchor = prevGrapheme(text, r0.head), .head = r0.head }
        else
            .{ .anchor = r0.head, .head = nextGrapheme(text, r0.head) });
    for (0..@max(1, count)) |_| {
        const next = hxRangeToTarget(text, target, r, is_prev);
        if (next.anchor == r.anchor and next.head == r.head) break;
        r = next;
    }
    return r;
}

// port of CharHelpers::range_to_target — a char iterator walking away from
// origin.head; when reversed, "next" reads the byte just behind the position.
fn hxRangeToTarget(text: []const u8, target: WordTarget, origin: HxRange, is_prev: bool) HxRange {
    var anchor = origin.anchor;
    var head = origin.head;
    var it = origin.head;
    var prev_ch: ?u8 = if (is_prev)
        (if (it < text.len) text[it] else null)
    else
        (if (it > 0) text[it - 1] else null);

    // skip any initial newline characters
    while (true) {
        const ch: u8 = if (is_prev) blk: {
            if (it == 0) break;
            break :blk text[it - 1];
        } else blk: {
            if (it >= text.len) break;
            break :blk text[it];
        };
        if (ch != '\n' and ch != '\r') break;
        if (is_prev) it -= 1 else it += 1;
        prev_ch = ch;
        if (is_prev) head -|= 1 else head += 1;
    }
    if (prev_ch != null and hxCat(prev_ch.?) == .eol) anchor = head;

    // find the target position
    const head_start = head;
    while (true) {
        const next_ch: u8 = if (is_prev) blk: {
            if (it == 0) break;
            it -= 1;
            break :blk text[it];
        } else blk: {
            if (it >= text.len) break;
            const c = text[it];
            it += 1;
            break :blk c;
        };
        if (prev_ch == null or hxReached(target, prev_ch.?, next_ch)) {
            if (head == head_start) anchor = head else break;
        }
        prev_ch = next_ch;
        if (is_prev) head -|= 1 else head += 1;
    }
    return .{ .anchor = anchor, .head = head };
}

/// a ropey "line is a line ending" — the line has no content of its own
fn hxLineIsEmpty(text: []const u8, line: usize) bool {
    return lineStartOffset(text, line) == hxLineEndIdx(text, line);
}

/// ]p / [p: helix move_next_paragraph / move_prev_paragraph
pub fn hxParaMove(text: []const u8, r: HxRange, count: usize, fwd: bool, extend: bool) HxRange {
    const nlines = hxLineCount(text);
    const cursor = hxCursor(text, r);
    var line = hxLineOf(text, cursor);
    if (fwd) {
        const nxt_start = if (line + 1 >= nlines) text.len else lineStartOffset(text, line + 1);
        const last_char = prevGrapheme(text, nxt_start) == cursor;
        const curr_empty = hxLineIsEmpty(text, line);
        const next_empty = hxLineIsEmpty(text, @min(nlines - 1, line + 1));
        const curr_empty_to_line = curr_empty and !next_empty;
        // skip the character after the paragraph boundary
        if (curr_empty_to_line and last_char) line += 1;
        var l = line;
        var last_line = l;
        for (0..@max(1, count)) |_| {
            while (l < nlines and !hxLineIsEmpty(text, l)) l += 1;
            while (l < nlines and hxLineIsEmpty(text, l)) l += 1;
            if (l == last_line) break;
            last_line = l;
        }
        const head = if (l >= nlines) text.len else lineStartOffset(text, l);
        const anchor = if (extend)
            hxPutCursor(text, r, head, true).anchor
        else if (curr_empty_to_line and last_char)
            r.head
        else
            cursor;
        return .{ .anchor = anchor, .head = head };
    }
    const first_char = lineStartOffset(text, line) == cursor;
    const prev_empty = hxLineIsEmpty(text, line -| 1);
    const curr_empty = hxLineIsEmpty(text, line);
    const prev_empty_to_line = prev_empty and !curr_empty;
    // skip the character before the paragraph boundary
    if (prev_empty_to_line and !first_char) line += 1;
    var l = line;
    var last_line = l;
    for (0..@max(1, count)) |_| {
        while (l > 0 and hxLineIsEmpty(text, l - 1)) l -= 1;
        while (l > 0 and !hxLineIsEmpty(text, l - 1)) l -= 1;
        if (l == last_line) break;
        last_line = l;
    }
    const head = lineStartOffset(text, l);
    const anchor = if (extend)
        hxPutCursor(text, r, head, true).anchor
    else if (prev_empty_to_line and first_char)
        cursor
    else
        r.head;
    return .{ .anchor = anchor, .head = head };
}

/// j/k target: helix move_vertically — goal_col clamps to the line's content
/// length, i.e. the cursor may land ON the '\n' of a shorter line.
pub fn hxVertTarget(text: []const u8, pos: usize, down: bool, count: usize, goal_col: usize) usize {
    const nlines = hxLineCount(text);
    const line = hxLineOf(text, pos);
    const nline = if (down) @min(line + @max(1, count), nlines - 1) else line -| @max(1, count);
    const s = lineStartOffset(text, nline);
    // hxLineEndIdx(text, nline) without its second walk to nline (see hxOff)
    const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len;
    return @min(s + goal_col, e);
}

/// f/F/t/T target cell. helix find_char: the exclusive (till) search starts
/// one further out so repeats make progress; not-found = null (no move).
pub fn hxFindTarget(text: []const u8, cursor: usize, ch: u8, fwd: bool, till: bool, count: usize) ?usize {
    var left = @max(1, count);
    if (fwd) {
        const head = nextGrapheme(text, cursor);
        var i = if (till) head + 1 else head;
        if (i > text.len) return null;
        while (i < text.len) : (i += 1) {
            if (text[i] == ch) {
                left -= 1;
                if (left == 0) return if (till) i - 1 else i;
            }
        }
        return null;
    }
    var i = if (till) cursor -| 1 else cursor;
    while (i > 0) {
        i -= 1;
        if (text[i] == ch) {
            left -= 1;
            if (left == 0) return if (till) i + 1 else i;
        }
    }
    return null;
}

// helix textobject.rs find_word_boundary
fn hxFindWordBoundary(text: []const u8, pos0: usize, fwd: bool, long: bool) usize {
    var prev: HxCat = if (fwd)
        (if (pos0 == 0) .ws else hxCat(text[pos0 - 1]))
    else
        (if (pos0 >= text.len) .ws else hxCat(text[pos0]));
    var pos = pos0;
    var it = pos0;
    while (true) {
        const ch: u8 = if (fwd) blk: {
            if (it >= text.len) break;
            const c = text[it];
            it += 1;
            break :blk c;
        } else blk: {
            if (it == 0) break;
            it -= 1;
            break :blk text[it];
        };
        const cat = hxCat(ch);
        if (cat == .eol or cat == .ws) return pos;
        if (!long and cat != prev and pos != 0 and pos != text.len) return pos;
        if (fwd) pos += 1 else pos -|= 1;
        prev = cat;
    }
    return pos;
}

/// miw/maw (and W): helix textobject_word — on whitespace it selects the
/// whitespace run's boundary (a 1-wide cursor there)
pub fn hxTextobjectWord(text: []const u8, r: HxRange, around: bool, long: bool) HxRange {
    const pos = hxCursor(text, r);
    const word_start = hxFindWordBoundary(text, pos, false, long);
    const cat: HxCat = if (pos < text.len) hxCat(text[pos]) else .ws;
    const word_end = if (cat == .ws or cat == .eol) pos else hxFindWordBoundary(text, pos + 1, true, long);
    if (word_start == word_end or !around) return .{ .anchor = word_start, .head = word_end };
    var end = word_end;
    while (end < text.len and hxIsWs(text[end]) and hxCat(text[end]) != .eol) end += 1;
    if (end > word_end) return .{ .anchor = word_start, .head = end };
    var start = word_start;
    while (start > 0 and hxIsWs(text[start - 1]) and hxCat(text[start - 1]) != .eol) start -= 1;
    return .{ .anchor = start, .head = word_end };
}

/// mip/map: helix textobject_paragraph
pub fn hxTextobjectParagraph(text: []const u8, r: HxRange, around: bool, count: usize) HxRange {
    const nlines = hxLineCount(text);
    const cursor = hxCursor(text, r);
    var line = hxLineOf(text, cursor);
    const prev_empty = hxLineIsEmpty(text, line -| 1);
    const curr_empty = hxLineIsEmpty(text, line);
    const next_empty = line + 1 >= nlines or hxLineIsEmpty(text, line + 1);
    const nxt_start = if (line + 1 >= nlines) text.len else lineStartOffset(text, line + 1);
    const last_char = prevGrapheme(text, nxt_start) == cursor;
    const prev_empty_to_line = prev_empty and !curr_empty;
    const curr_empty_to_line = curr_empty and !next_empty;

    var line_back = line;
    if (prev_empty_to_line or curr_empty_to_line) line_back += 1;
    // do not include the current paragraph on a paragraph end (include next)
    if (!(curr_empty_to_line and last_char)) {
        while (line_back > 0 and hxLineIsEmpty(text, line_back - 1)) line_back -= 1;
        while (line_back > 0 and !hxLineIsEmpty(text, line_back - 1)) line_back -= 1;
    }
    if (curr_empty_to_line and last_char) line += 1;
    const n = @max(1, count);
    var count_done: usize = 0;
    for (0..n) |_| {
        var done = false;
        while (line < nlines and !hxLineIsEmpty(text, line)) {
            line += 1;
            done = true;
        }
        while (line < nlines and hxLineIsEmpty(text, line)) line += 1;
        if (done) count_done += 1;
    }
    // search one paragraph backwards when we ran off the end
    if (count_done != n and line >= nlines) {
        while (line_back > 0 and hxLineIsEmpty(text, line_back - 1)) line_back -= 1;
        while (line_back > 0 and !hxLineIsEmpty(text, line_back - 1)) line_back -= 1;
    }
    if (!around) {
        // inside: drop the trailing whitespace paragraph
        while (line > 0 and hxLineIsEmpty(text, line - 1)) line -= 1;
    }
    return .{
        .anchor = lineStartOffset(text, line_back),
        .head = if (line >= nlines) text.len else lineStartOffset(text, line),
    };
}

test "hx textobject word and paragraph" {
    const t = "alpha beta gamma\n";
    // miw mid-word
    var r = hxTextobjectWord(t, .{ .anchor = 8, .head = 9 }, false, false);
    try std.testing.expectEqual(@as(usize, 6), r.anchor);
    try std.testing.expectEqual(@as(usize, 10), r.head);
    // maw on the space after "beta": collapses to the boundary
    r = hxTextobjectWord(t, .{ .anchor = 10, .head = 11 }, true, false);
    try std.testing.expectEqual(@as(usize, 10), r.anchor);
    try std.testing.expectEqual(@as(usize, 10), r.head);
    const t2 = "aa\n\ncc\n";
    // mip from the blank line selects the NEXT paragraph
    r = hxTextobjectParagraph(t2, .{ .anchor = 3, .head = 4 }, false, 1);
    try std.testing.expectEqual(@as(usize, 4), r.anchor);
    try std.testing.expectEqual(@as(usize, 7), r.head);
}

/// leading-whitespace visual width (tab -> next multiple of INDENT_W)
pub fn hxIndentWidth(line: []const u8) usize {
    var w: usize = 0;
    for (line) |ch| {
        if (ch == ' ') w += 1 else if (ch == '\t') w = (w / INDENT_W + 1) * INDENT_W else break;
    }
    return w;
}

/// full indent LEVELS of a line as spaces (helix indent_level_for_line:
/// partial levels round down) — what o/O/insert-newline copy.
pub fn hxIndentString(line: []const u8) []const u8 {
    const level = hxIndentWidth(line) / INDENT_W;
    const max = "                                "; // 8 levels is plenty (ponytail)
    return max[0..@min(level * INDENT_W, max.len)];
}

/// helix Ctrl-a / Ctrl-x: increment the SELECTED text as a decimal integer.
/// Zero-padding is preserved (width follows sign flips, helix-style).
/// Ponytail: no 0x/0o/0b bases, no '_' separators — decimal only.
pub fn hxIncrement(alloc: std.mem.Allocator, frag: []const u8, amount: i64) !?[]u8 {
    if (frag.len == 0) return null;
    const neg = frag[0] == '-';
    const digits = if (neg) frag[1..] else frag;
    if (digits.len == 0) return null;
    for (digits) |ch| if (!std.ascii.isDigit(ch)) return null;
    const val = std.fmt.parseInt(i128, frag, 10) catch return null;
    const nv = val +| @as(i128, amount);
    const pad = digits[0] == '0';
    const neg_after = nv < 0;
    // format_length includes the sign, adjusted when the sign flips
    var flen: usize = frag.len;
    if (neg and !neg_after) flen -= 1;
    if (!neg and neg_after) flen += 1;
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(alloc);
    var buf: [48]u8 = undefined;
    // "{d}" prints '+' for positive signed ints — format the magnitude unsigned
    const mag = std.fmt.bufPrint(&buf, "{d}", .{@abs(nv)}) catch return null;
    if (neg_after) try out.append(alloc, '-');
    if (pad) {
        const want = flen - @as(usize, if (neg_after) 1 else 0);
        var i = mag.len;
        while (i < want) : (i += 1) try out.append(alloc, '0');
    }
    try out.appendSlice(alloc, mag);
    return try out.toOwnedSlice(alloc);
}

test "hx word moves match helix" {
    const t = "alpha beta\n";
    // w from a fresh 1-wide cursor selects "alpha " (cursor on the space)
    var r = hxWordMove(t, .{ .anchor = 0, .head = 1 }, 1, .next_word_start);
    try std.testing.expectEqual(@as(usize, 0), r.anchor);
    try std.testing.expectEqual(@as(usize, 6), r.head);
    // e from the same start ends on 'a' of alpha
    r = hxWordMove(t, .{ .anchor = 0, .head = 1 }, 1, .next_word_end);
    try std.testing.expectEqual(@as(usize, 5), r.head);
    try std.testing.expectEqual(@as(usize, 0), r.anchor);
    // b from the w result selects "alpha" backward
    r = hxWordMove(t, .{ .anchor = 6, .head = 10 }, 1, .prev_word_start);
    try std.testing.expectEqual(@as(usize, 10), r.anchor);
    try std.testing.expectEqual(@as(usize, 6), r.head);
    // 2w on "one two three": anchor comes from the last hop only
    const t2 = "one two three\n";
    r = hxWordMove(t2, .{ .anchor = 0, .head = 1 }, 2, .next_word_start);
    try std.testing.expectEqual(@as(usize, 4), r.anchor);
    try std.testing.expectEqual(@as(usize, 8), r.head);
    // w at EOF collapses to a zero-width range at len
    const t3 = "alpha\n";
    r = hxWordMove(t3, .{ .anchor = 0, .head = 5 }, 1, .next_word_start);
    try std.testing.expectEqual(@as(usize, 6), r.head);
    try std.testing.expectEqual(@as(usize, 6), r.anchor);
    // W treats punct runs as word chars
    const t4 = "foo.bar baz\n";
    r = hxWordMove(t4, .{ .anchor = 0, .head = 1 }, 1, .next_long_word_start);
    try std.testing.expectEqual(@as(usize, 0), r.anchor);
    try std.testing.expectEqual(@as(usize, 8), r.head);
}

test "hx put cursor keeps the anchor cell across crossings" {
    const t = "abcdef\n";
    // forward range [2,3) extended left of the anchor: anchor cell stays 2
    var r = hxPutCursor(t, .{ .anchor = 2, .head = 3 }, 0, true);
    try std.testing.expectEqual(@as(usize, 3), r.anchor);
    try std.testing.expectEqual(@as(usize, 0), r.head);
    try std.testing.expectEqual(@as(usize, 0), hxCursor(t, r));
    // and back: cursor to 4 -> forward again, anchor gap back to 2
    r = hxPutCursor(t, r, 4, true);
    try std.testing.expectEqual(@as(usize, 2), r.anchor);
    try std.testing.expectEqual(@as(usize, 5), r.head);
}

test "hx paragraph moves" {
    const t = "aa\nbb\n\ncc\ndd\n\nee\n";
    // ]p from the top selects through the blank line to the next block
    var r = hxParaMove(t, .{ .anchor = 0, .head = 1 }, 1, true, false);
    try std.testing.expectEqual(@as(usize, 0), r.anchor);
    try std.testing.expectEqual(@as(usize, 7), r.head);
    // [p from "ee" (line 6, offset 14) goes back to "cc" block start
    r = hxParaMove(t, .{ .anchor = 14, .head = 15 }, 1, false, false);
    try std.testing.expectEqual(@as(usize, 14), r.anchor);
    try std.testing.expectEqual(@as(usize, 7), r.head);
}

test "hx vertical: goal col clamps onto the newline cell" {
    const t = "abcdef\nab\nabcdef\n";
    // from (0,5) down: line "ab" clamps to its '\n' at offset 9
    try std.testing.expectEqual(@as(usize, 9), hxVertTarget(t, 5, true, 1, 5));
    // two down with the same goal restores col 5
    try std.testing.expectEqual(@as(usize, 15), hxVertTarget(t, 9, true, 1, 5));
}

test "hx find targets" {
    const t = "abcabc\n";
    try std.testing.expectEqual(@as(usize, 2), hxFindTarget(t, 0, 'c', true, false, 1).?);
    try std.testing.expectEqual(@as(usize, 5), hxFindTarget(t, 0, 'c', true, false, 2).?);
    try std.testing.expectEqual(@as(usize, 1), hxFindTarget(t, 0, 'c', true, true, 1).?);
    // till repeat skips the adjacent target: from cell 1, next tc reaches 4
    try std.testing.expectEqual(@as(usize, 4), hxFindTarget(t, 1, 'c', true, true, 1).?);
    try std.testing.expectEqual(@as(usize, 3), hxFindTarget(t, 5, 'a', false, false, 1).?);
    try std.testing.expectEqual(@as(usize, 4), hxFindTarget(t, 5, 'a', false, true, 1).?);
    try std.testing.expectEqual(@as(?usize, null), hxFindTarget(t, 0, 'z', true, false, 1));
}

test "hx increment" {
    const a = std.testing.allocator;
    {
        const r = (try hxIncrement(a, "15", 1)).?;
        defer a.free(r);
        try std.testing.expectEqualStrings("16", r);
    }
    {
        const r = (try hxIncrement(a, "007", 1)).?;
        defer a.free(r);
        try std.testing.expectEqualStrings("008", r);
    }
    {
        const r = (try hxIncrement(a, "-3", 1)).?;
        defer a.free(r);
        try std.testing.expectEqualStrings("-2", r);
    }
    {
        const r = (try hxIncrement(a, "9", -10)).?;
        defer a.free(r);
        try std.testing.expectEqualStrings("-1", r);
    }
    try std.testing.expectEqual(@as(?[]u8, null), try hxIncrement(a, "a 1", 1));
    try std.testing.expectEqual(@as(?[]u8, null), try hxIncrement(a, "", 1));
}

// ---- retired standalone file-pane modal prototype ----
// This old pure-std model has no production or harness callers. It remains
// only as context for the primitive algorithms around it; normal_input.zig is
// the sole BODY-NORMAL recognizer and Pardes owns Action execution.

pub const Key = union(enum) {
    ch: u21, // a printable codepoint (insert inserts its UTF-8 bytes)
    esc,
    enter,
    backspace,
    left,
    right,
    up,
    down,
    home,
    end,
    page_down,
    page_up,
    half_down, // Ctrl-d
    half_up, // Ctrl-u
};

pub const FileMode = enum { normal, insert };

pub const FileState = struct {
    cur: Cursor = .{},
    mode: FileMode = .normal,
    pending: u21 = 0, // prefix codepoint in flight: 'g' or 'z'
    msel_active: bool = false,
    msel_r0: i32 = 0,
    msel_r1: i32 = 0,
};

// The view the cursor must stay inside. `scroll` is read/written so viewport
// alignment (zt/zz/zb) and page motions can adjust it; the app syncs it back to
// the file pane's scroll. The unit-test Sim passes a large rows + a dummy scroll
// so visibility is a no-op (content is what's asserted).
pub const View = struct {
    rows: usize,
    scroll: *usize,
};

fn chEq(key: Key, cp: u21) bool {
    return switch (key) {
        .ch => |c| c == cp,
        else => false,
    };
}

fn tagOf(key: Key) std.meta.Tag(Key) {
    return std.meta.activeTag(key);
}

fn splitLines(alloc: std.mem.Allocator, content: []const u8) ![][]const u8 {
    var ls: std.ArrayList([]const u8) = .empty;
    var it = std.mem.splitScalar(u8, content, '\n');
    while (it.next()) |ln| try ls.append(alloc, ln);
    return ls.toOwnedSlice(alloc);
}

fn ensureVisible(view: View, row: usize) void {
    const s = view.scroll.*;
    if (row < s) {
        view.scroll.* = row;
        return;
    }
    const last = s +| (view.rows -| 1);
    if (row > last) view.scroll.* = row -| (view.rows -| 1);
}

// helix `x`: start a line selection at the cursor, or extend it down by one.
fn lineSelectFile(st: *FileState, lines: []const []const u8) void {
    if (!st.msel_active) {
        st.msel_active = true;
        st.msel_r0 = @intCast(st.cur.row);
        st.msel_r1 = @intCast(st.cur.row);
    } else {
        const last: i32 = @intCast(if (lines.len == 0) 0 else lines.len - 1);
        st.msel_r1 = @min(st.msel_r1 + 1, last);
        st.cur.row = @intCast(st.msel_r1);
    }
    st.cur.col = 0;
    st.pending = 0;
}

// `d`: delete the selected lines (yanking them), or the char at the cursor.
fn deleteFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, lines: []const []const u8, yank: *?[]u8) !?[]u8 {
    if (st.msel_active) {
        const r0: i32 = @min(st.msel_r0, st.msel_r1);
        const r1: i32 = @max(st.msel_r0, st.msel_r1);
        const d = try deleteLines(alloc, content, @intCast(@max(0, r0)), @intCast(@max(0, r1)));
        if (yank.*) |old| alloc.free(old);
        yank.* = try alloc.dupe(u8, d.deleted);
        alloc.free(d.deleted);
        const n = lineCount(d.content);
        st.cur = .{ .row = @intCast(@min(@as(usize, @intCast(@max(0, r0))), if (n == 0) 0 else n - 1)), .col = 0 };
        st.msel_active = false;
        st.pending = 0;
        return d.content;
    }
    // no selection: delete the char at the cursor (no-op if past end)
    const llen = lineLenOf(lines, st.cur.row);
    if (st.cur.col >= llen) {
        st.pending = 0;
        return null;
    }
    const new = try deleteChar(alloc, content, st.cur);
    st.pending = 0;
    return new;
}

// `y`: yank the selected lines, or the current line. Cursor moves to the
// selection start; the selection is collapsed.
fn yankFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, yank: *?[]u8) !void {
    if (st.msel_active) {
        const r0: usize = @intCast(@max(0, @min(st.msel_r0, st.msel_r1)));
        const r1: usize = @intCast(@max(0, @max(st.msel_r0, st.msel_r1)));
        var buf: std.ArrayList(u8) = .empty;
        var r: usize = r0;
        while (r <= r1) : (r += 1) {
            if (r > r0) try buf.append(alloc, '\n');
            try buf.appendSlice(alloc, lineSlice(content, r));
        }
        if (yank.*) |old| alloc.free(old);
        yank.* = try buf.toOwnedSlice(alloc);
        st.cur = .{ .row = r0, .col = 0 };
        st.msel_active = false;
    } else {
        if (yank.*) |old| alloc.free(old);
        yank.* = try alloc.dupe(u8, lineSlice(content, st.cur.row));
    }
    st.pending = 0;
}

// `p`: paste the yanked text as a new line below the cursor.
fn pasteFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, yank: *?[]u8) !?[]u8 {
    const y = yank.* orelse {
        st.pending = 0;
        return null;
    };
    const new = try pasteLineBelow(alloc, content, st.cur.row, y);
    st.cur = .{ .row = st.cur.row + 1, .col = 0 };
    st.pending = 0;
    return new;
}

// `c`: change the selection (delete + enter INSERT, keeping one empty line), or
// change the char at the cursor. Yanks the removed text.
fn changeFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, lines: []const []const u8, yank: *?[]u8) !?[]u8 {
    if (st.msel_active) {
        const r0: usize = @intCast(@max(0, @min(st.msel_r0, st.msel_r1)));
        const r1: usize = @intCast(@max(0, @max(st.msel_r0, st.msel_r1)));
        // yank the original lines first (from the un-mutated content)
        var buf: std.ArrayList(u8) = .empty;
        var r: usize = r0;
        while (r <= r1) : (r += 1) {
            if (r > r0) try buf.append(alloc, '\n');
            try buf.appendSlice(alloc, lineSlice(content, r));
        }
        if (yank.*) |old| alloc.free(old);
        yank.* = try buf.toOwnedSlice(alloc);
        // drop the extra lines (keep one), then empty the kept line
        const d = if (r1 > r0) try deleteLines(alloc, content, r0 + 1, r1) else null;
        defer if (d) |dd| alloc.free(dd.deleted);
        const after_del: []const u8 = if (d) |dd| dd.content else content;
        const cl = try clearLine(alloc, after_del, r0);
        if (d) |dd| alloc.free(dd.content); // free the intermediate (after_del copy)
        st.cur = .{ .row = r0, .col = 0 };
        st.mode = .insert;
        st.msel_active = false;
        st.pending = 0;
        return cl;
    }
    // no selection: delete the char at the cursor (if any), then enter INSERT
    const llen = lineLenOf(lines, st.cur.row);
    if (st.cur.col >= llen) {
        st.mode = .insert;
        st.msel_active = false;
        st.pending = 0;
        return null;
    }
    const new = try deleteChar(alloc, content, st.cur);
    st.mode = .insert;
    st.msel_active = false;
    st.pending = 0;
    return new;
}

// INSERT-mode key on a file pane. Returns new content or null (no change).
fn stepInsertFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, lines: []const []const u8, key: Key) !?[]u8 {
    switch (key) {
        .esc => {
            st.mode = .normal;
            st.msel_active = false;
            st.pending = 0;
            return null;
        },
        .ch => |cp| {
            if (cp == '\n') return try stepInsertFile(alloc, content, st, lines, .enter);
            var buf: [4]u8 = undefined;
            const n = std.unicode.utf8Encode(cp, &buf) catch return null;
            const new = try insertAt(alloc, content, st.cur, buf[0..n]);
            st.cur.col += n; // col is a byte offset; advance by the char's byte length
            st.pending = 0;
            return new;
        },
        .enter => {
            const new = try insertAt(alloc, content, st.cur, "\n");
            st.cur = .{ .row = st.cur.row + 1, .col = 0 };
            st.pending = 0;
            return new;
        },
        .backspace => {
            if (st.cur.col > 0) {
                const new = try deleteChar(alloc, content, .{ .row = st.cur.row, .col = st.cur.col - 1 });
                st.cur.col -= 1;
                return new;
            } else if (st.cur.row > 0) {
                const prevlen = lineSlice(content, st.cur.row - 1).len;
                const new = try deleteChar(alloc, content, .{ .row = st.cur.row - 1, .col = prevlen });
                st.cur = .{ .row = st.cur.row - 1, .col = prevlen };
                return new;
            }
            return null;
        },
        .left => {
            st.cur = charLeft(st.cur);
            return null;
        },
        .right => {
            st.cur = charRight(lines, st.cur);
            return null;
        },
        .up => {
            st.cur = lineUp(lines, st.cur);
            return null;
        },
        .down => {
            st.cur = lineDown(lines, st.cur);
            return null;
        },
        .home => {
            st.cur = lineStart(st.cur);
            return null;
        },
        .end => {
            st.cur = lineEnd(lines, st.cur);
            return null;
        },
        else => return null,
    }
}

// RETIRED LEGACY REFERENCE INTERPRETER. Nothing in production or the test
// harness calls this mini-parser; BODY-NORMAL recognition lives exclusively
// in normal_input.zig and Pardes executes its semantic Actions for text/PDF.
// Keep this frozen only as old modal-algorithm context; do not add bindings or
// infer current behavior from it.
pub fn stepFile(alloc: std.mem.Allocator, content: []const u8, st: *FileState, view: View, key: Key, yank: *?[]u8) !?[]u8 {
    const lines = try splitLines(alloc, content);
    defer alloc.free(lines);
    if (st.mode == .insert) return try stepInsertFile(alloc, content, st, lines, key);

    var cur = clampToChar(lines, st.cur);

    // prefix continuations
    if (st.pending != 0) {
        const p = st.pending;
        st.pending = 0;
        if (p == 'g') {
            if (chEq(key, 'g')) cur = gotoFirst() else if (chEq(key, 'e')) cur = gotoLast(lines) else if (chEq(key, 'h')) cur = lineStart(cur) else if (chEq(key, 'l')) cur = lineEnd(lines, cur) else return null; // unknown continuation: consume, no-op
            st.cur = cur;
            st.msel_active = false;
            return null;
        }
        if (p == 'z') {
            if (chEq(key, 't')) {
                view.scroll.* = cur.row;
            } else if (chEq(key, 'z')) {
                view.scroll.* = @intCast(@max(0, @as(i32, @intCast(cur.row)) - @as(i32, @intCast(view.rows / 2))));
            } else if (chEq(key, 'b')) {
                view.scroll.* = @intCast(@max(0, @as(i32, @intCast(cur.row)) - @as(i32, @intCast(view.rows)) + 1));
            } else return null;
            st.msel_active = false;
            return null;
        }
    }
    if (chEq(key, 'g')) {
        st.pending = 'g';
        return null;
    }
    if (chEq(key, 'z')) {
        st.pending = 'z';
        return null;
    }

    // motions -> move cursor, collapse selection, keep visible
    var moved: ?Cursor = null;
    if (chEq(key, 'h') or tagOf(key) == .left) moved = charLeft(cur) else if (chEq(key, 'l') or tagOf(key) == .right) moved = charRight(lines, cur) else if (chEq(key, 'j') or tagOf(key) == .down) moved = lineDown(lines, cur) else if (chEq(key, 'k') or tagOf(key) == .up) moved = lineUp(lines, cur) else if (chEq(key, 'w')) moved = nextWordStart(lines, cur, false) else if (chEq(key, 'W')) moved = nextWordStart(lines, cur, true) else if (chEq(key, 'b')) moved = prevWordStart(lines, cur, false) else if (chEq(key, 'B')) moved = prevWordStart(lines, cur, true) else if (chEq(key, 'e')) moved = nextWordEnd(lines, cur, false) else if (chEq(key, 'E')) moved = nextWordEnd(lines, cur, true) else if (chEq(key, '0') or tagOf(key) == .home) moved = lineStart(cur) else if (chEq(key, '$') or tagOf(key) == .end) moved = lineEnd(lines, cur) else if (chEq(key, '^')) moved = firstNonWsOf(lines, cur) else if (chEq(key, 'G')) moved = gotoLast(lines) else if (tagOf(key) == .half_down) moved = clampToChar(lines, pageDown(cur, @max(1, view.rows / 2))) else if (tagOf(key) == .half_up) moved = clampToChar(lines, pageUp(cur, @max(1, view.rows / 2))) else if (tagOf(key) == .page_down) moved = clampToChar(lines, pageDown(cur, view.rows)) else if (tagOf(key) == .page_up) moved = clampToChar(lines, pageUp(cur, view.rows));
    if (moved) |m| {
        st.cur = m;
        st.msel_active = false;
        st.pending = 0;
        ensureVisible(view, m.row);
        return null;
    }

    // insert entry
    if (chEq(key, 'i')) {
        st.mode = .insert;
        st.cur = cur;
        st.msel_active = false;
        st.pending = 0;
        return null;
    }
    if (chEq(key, 'a')) {
        st.mode = .insert;
        st.cur = charRight(lines, cur);
        st.msel_active = false;
        st.pending = 0;
        return null;
    }
    if (chEq(key, 'I')) {
        st.mode = .insert;
        st.cur = firstNonWsOf(lines, cur);
        st.msel_active = false;
        st.pending = 0;
        return null;
    }
    if (chEq(key, 'A')) {
        st.mode = .insert;
        st.cur = .{ .row = cur.row, .col = lineLenOf(lines, cur.row) };
        st.msel_active = false;
        st.pending = 0;
        return null;
    }
    if (chEq(key, 'o')) {
        const new = try insertAt(alloc, content, .{ .row = cur.row, .col = lineLenOf(lines, cur.row) }, "\n");
        st.cur = .{ .row = cur.row + 1, .col = 0 };
        st.mode = .insert;
        st.msel_active = false;
        st.pending = 0;
        ensureVisible(view, st.cur.row);
        return new;
    }
    if (chEq(key, 'O')) {
        const new = try insertAt(alloc, content, .{ .row = cur.row, .col = 0 }, "\n");
        st.cur = .{ .row = cur.row, .col = 0 };
        st.mode = .insert;
        st.msel_active = false;
        st.pending = 0;
        ensureVisible(view, st.cur.row);
        return new;
    }

    // select / edit
    if (chEq(key, 'x')) {
        lineSelectFile(st, lines);
        return null;
    }
    if (chEq(key, 'd')) return try deleteFile(alloc, content, st, lines, yank);
    if (chEq(key, 'c')) return try changeFile(alloc, content, st, lines, yank);
    if (chEq(key, 'y')) {
        try yankFile(alloc, content, st, yank);
        return null;
    }
    if (chEq(key, 'p')) return try pasteFile(alloc, content, st, yank);

    // Enter / other keys: no-op on a file (no tty mode)
    return null;
}

// ---- tests ----

const testEq = struct {
    fn cur(lines: []const []const u8, s: []const u8) Cursor {
        var row: usize = 0;
        for (lines) |ln| {
            if (std.mem.eql(u8, ln, s)) return .{ .row = row, .col = 0 };
            row += 1;
        }
        unreachable;
    }
};

test "kindOf" {
    try std.testing.expectEqual(Kind.word, kindOf('a'));
    try std.testing.expectEqual(Kind.word, kindOf('_'));
    try std.testing.expectEqual(Kind.word, kindOf('9'));
    try std.testing.expectEqual(Kind.punct, kindOf('.'));
    try std.testing.expectEqual(Kind.punct, kindOf('('));
    try std.testing.expectEqual(Kind.ws, kindOf(' '));
    try std.testing.expectEqual(Kind.ws, kindOf('\n'));
}

test "char/line motions" {
    const lines = [_][]const u8{ "alpha beta", "  two words", "x" };
    const c = Cursor{ .row = 0, .col = 5 };
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 4 }, charLeft(c));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 6 }, charRight(&lines, c));
    try std.testing.expectEqual(Cursor{ .row = 1, .col = 5 }, lineDown(&lines, c));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, lineUp(&lines, Cursor{ .row = 1, .col = 5 }));
    // line ends
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 9 }, lineEnd(&lines, c));
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 0 }, lineEnd(&lines, Cursor{ .row = 2, .col = 0 }));
    // first non-ws
    try std.testing.expectEqual(Cursor{ .row = 1, .col = 2 }, firstNonWsOf(&lines, Cursor{ .row = 1, .col = 0 }));
    // cursor row past the content (mouse click below a short pane): no panic
    try std.testing.expectEqual(Cursor{ .row = 24, .col = 0 }, firstNonWsOf(&lines, Cursor{ .row = 24, .col = 3 }));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, paragraphBwd(&lines, Cursor{ .row = 24, .col = 0 }));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, paragraphBwd(&[_][]const u8{}, Cursor{ .row = 5, .col = 0 }));
}

test "word motions w/b/e" {
    const lines = [_][]const u8{"this is a test"};
    const w = &lines;
    // "this is a test", indices 0..13
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, nextWordStart(w, Cursor{ .row = 0, .col = 0 }, false)); // t->next word "is"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 8 }, nextWordStart(w, Cursor{ .row = 0, .col = 5 }, false)); // -> "a"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 10 }, nextWordStart(w, Cursor{ .row = 0, .col = 8 }, false)); // -> "test"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 10 }, nextWordStart(w, Cursor{ .row = 0, .col = 9 }, false)); // from ws
    // b
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 8 }, prevWordStart(w, Cursor{ .row = 0, .col = 10 }, false)); // test -> "a"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, prevWordStart(w, Cursor{ .row = 0, .col = 8 }, false)); // -> "is"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, prevWordStart(w, Cursor{ .row = 0, .col = 5 }, false)); // -> "this"
    // e
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 3 }, nextWordEnd(w, Cursor{ .row = 0, .col = 0 }, false)); // this[3]
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 6 }, nextWordEnd(w, Cursor{ .row = 0, .col = 3 }, false)); // -> "is"[6]
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 13 }, nextWordEnd(w, Cursor{ .row = 0, .col = 10 }, false)); // -> "test"[13]
}

test "word motions cross line" {
    const lines = [_][]const u8{ "foo bar", "", "baz" };
    const w = &lines;
    // from end of "foo bar" (row0 col6) w crosses the blank line to "baz"
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 0 }, nextWordStart(w, Cursor{ .row = 0, .col = 6 }, false));
    // b from "baz" crosses back to "bar"
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 4 }, prevWordStart(w, Cursor{ .row = 2, .col = 0 }, false));
    // e from row0 col0 -> "foo" end (col2)
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 2 }, nextWordEnd(w, Cursor{ .row = 0, .col = 0 }, false));
}

test "long word W treats punct as word" {
    // "foo.bar baz" : W from 0 -> "baz" at 8 (foo.bar is one long word)
    const lines = [_][]const u8{"foo.bar baz"};
    const w = &lines;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 8 }, nextWordStart(w, Cursor{ .row = 0, .col = 0 }, true));
    // w (non-long) from 0 -> '.' at 3 (punct is its own word, like vim/helix)
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 3 }, nextWordStart(w, Cursor{ .row = 0, .col = 0 }, false));
}

test "goto" {
    const lines = [_][]const u8{ "a", "b", "c" };
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, gotoFirst());
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 0 }, gotoLast(&lines));
}

test "lineStartOffset + lineSlice" {
    const content = "alpha\nbeta\n\ngamma";
    try std.testing.expectEqual(@as(usize, 0), lineStartOffset(content, 0));
    try std.testing.expectEqual(@as(usize, 6), lineStartOffset(content, 1));
    try std.testing.expectEqual(@as(usize, 11), lineStartOffset(content, 2));
    try std.testing.expectEqual(@as(usize, 12), lineStartOffset(content, 3));
    try std.testing.expectEqual(@as(usize, 17), lineStartOffset(content, 4)); // past end
    try std.testing.expectEqualStrings("alpha", lineSlice(content, 0));
    try std.testing.expectEqualStrings("beta", lineSlice(content, 1));
    try std.testing.expectEqualStrings("", lineSlice(content, 2));
    try std.testing.expectEqualStrings("gamma", lineSlice(content, 3));
    try std.testing.expectEqual(@as(usize, 4), lineCount(content));
}

test "insertAt mid-line and at end" {
    const content = "hello world";
    const a = std.testing.allocator;
    const r1 = try insertAt(a, content, .{ .row = 0, .col = 5 }, "!");
    defer a.free(r1);
    try std.testing.expectEqualStrings("hello! world", r1);
    const r2 = try insertAt(a, content, .{ .row = 0, .col = 99 }, "!");
    defer a.free(r2);
    try std.testing.expectEqualStrings("hello world!", r2);
}

test "insertAt multiline creates lines" {
    const content = "a\nb";
    const a = std.testing.allocator;
    const r = try insertAt(a, content, .{ .row = 0, .col = 1 }, "X\nY");
    defer a.free(r);
    try std.testing.expectEqualStrings("aX\nY\nb", r);
    try std.testing.expectEqual(@as(usize, 3), lineCount(r));
}

test "deleteChar" {
    const content = "abc";
    const a = std.testing.allocator;
    const r = try deleteChar(a, content, .{ .row = 0, .col = 1 });
    defer a.free(r);
    try std.testing.expectEqualStrings("ac", r);
    // past end: no-op
    const r2 = try deleteChar(a, content, .{ .row = 0, .col = 5 });
    defer a.free(r2);
    try std.testing.expectEqualStrings("abc", r2);
}

test "deleteLines middle" {
    const content = "one\ntwo\nthree\nfour";
    const a = std.testing.allocator;
    const d = try deleteLines(a, content, 1, 2);
    defer a.free(d.content);
    defer a.free(d.deleted);
    try std.testing.expectEqualStrings("one\nfour", d.content);
    try std.testing.expectEqualStrings("two\nthree", d.deleted);
}

test "deleteLines last line drops preceding newline" {
    const content = "one\ntwo\nthree";
    const a = std.testing.allocator;
    const d = try deleteLines(a, content, 2, 2);
    defer a.free(d.content);
    defer a.free(d.deleted);
    try std.testing.expectEqualStrings("one\ntwo", d.content);
    try std.testing.expectEqualStrings("three", d.deleted);
}

test "deleteLines only line" {
    const content = "only";
    const a = std.testing.allocator;
    const d = try deleteLines(a, content, 0, 0);
    defer a.free(d.content);
    defer a.free(d.deleted);
    try std.testing.expectEqualStrings("", d.content);
    try std.testing.expectEqualStrings("only", d.deleted);
}

test "rangeText + deleteRange (char-wise select)" {
    const a = std.testing.allocator;
    const content = "hello\nworld\nfoo";
    // same-line inclusive range: "hello"[1..3] -> "ell"
    const t1 = try rangeText(a, content, .{ .row = 0, .col = 1 }, .{ .row = 0, .col = 3 });
    defer a.free(t1);
    try std.testing.expectEqualStrings("ell", t1);
    // reversed cursors give the same range
    const t2 = try rangeText(a, content, .{ .row = 0, .col = 3 }, .{ .row = 0, .col = 1 });
    defer a.free(t2);
    try std.testing.expectEqualStrings("ell", t2);
    // cross-line range includes the newline: row0 col3 .. row1 col1 -> "lo\nwo"
    const t3 = try rangeText(a, content, .{ .row = 0, .col = 3 }, .{ .row = 1, .col = 1 });
    defer a.free(t3);
    try std.testing.expectEqualStrings("lo\nwo", t3);
    // delete the same cross-line range
    const d = try deleteRange(a, content, .{ .row = 0, .col = 3 }, .{ .row = 1, .col = 1 });
    defer a.free(d.content);
    defer a.free(d.deleted);
    try std.testing.expectEqualStrings("helrld\nfoo", d.content);
    try std.testing.expectEqualStrings("lo\nwo", d.deleted);
}

test "clearLine" {
    const content = "keep\nzap me\nkeep2";
    const a = std.testing.allocator;
    const r = try clearLine(a, content, 1);
    defer a.free(r);
    try std.testing.expectEqualStrings("keep\n\nkeep2", r);
}

test "findChar f/F/t/T across lines and counts" {
    const lines = [_][]const u8{ "abcabc", "xa" };
    const w = &lines;
    // f: next occurrence, on it
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 3 }, findChar(w, .{ .row = 0, .col = 0 }, 'a', true, false, 1).?);
    // count: 2fa crosses into the next line
    try std.testing.expectEqual(Cursor{ .row = 1, .col = 1 }, findChar(w, .{ .row = 0, .col = 0 }, 'a', true, false, 2).?);
    // t stops one short
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 2 }, findChar(w, .{ .row = 0, .col = 0 }, 'a', true, true, 1).?);
    // F backward, on it
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, findChar(w, .{ .row = 0, .col = 3 }, 'a', false, false, 1).?);
    // T backward stops one after
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 1 }, findChar(w, .{ .row = 0, .col = 3 }, 'a', false, true, 1).?);
    // not found: null, no move
    try std.testing.expectEqual(@as(?Cursor, null), findChar(w, .{ .row = 0, .col = 0 }, 'z', true, false, 1));
}

test "matchBracket nesting both directions" {
    const lines = [_][]const u8{"a (b (c) d) e"};
    const w = &lines;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 10 }, matchBracket(w, .{ .row = 0, .col = 2 }).?);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 2 }, matchBracket(w, .{ .row = 0, .col = 10 }).?);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 7 }, matchBracket(w, .{ .row = 0, .col = 5 }).?);
    try std.testing.expectEqual(@as(?Cursor, null), matchBracket(w, .{ .row = 0, .col = 0 }));
}

test "matchBracket across lines" {
    const lines = [_][]const u8{ "if (x) {", "  y", "}" };
    const w = &lines;
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 0 }, matchBracket(w, .{ .row = 0, .col = 7 }).?);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 7 }, matchBracket(w, .{ .row = 2, .col = 0 }).?);
}

test "paragraph motions" {
    const lines = [_][]const u8{ "one", "two", "", "", "three", "four", "", "five" };
    const w = &lines;
    try std.testing.expectEqual(Cursor{ .row = 4, .col = 0 }, paragraphFwd(w, .{ .row = 0, .col = 1 }));
    try std.testing.expectEqual(Cursor{ .row = 7, .col = 0 }, paragraphFwd(w, .{ .row = 4, .col = 0 }));
    // no next block: the last line
    try std.testing.expectEqual(Cursor{ .row = 7, .col = 0 }, paragraphFwd(w, .{ .row = 7, .col = 0 }));
    // from mid-block up to its start; from a start up to the previous block's
    try std.testing.expectEqual(Cursor{ .row = 4, .col = 0 }, paragraphBwd(w, .{ .row = 5, .col = 1 }));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, paragraphBwd(w, .{ .row = 4, .col = 0 }));
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, paragraphBwd(w, .{ .row = 0, .col = 0 }));
}

test "pairRange inside/around, cursor on and between brackets" {
    const lines = [_][]const u8{"f(a, (b))"};
    const w = &lines;
    const around = pairRange(w, .{ .row = 0, .col = 3 }, '(', ')', true).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 1 }, around.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 8 }, around.b);
    const inside = pairRange(w, .{ .row = 0, .col = 3 }, '(', ')', false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 2 }, inside.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 7 }, inside.b);
    // cursor on the nested open picks the nested pair
    const nested = pairRange(w, .{ .row = 0, .col = 5 }, '(', ')', false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 6 }, nested.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 6 }, nested.b);
    // empty pair: no inside
    const empty = [_][]const u8{"()"};
    try std.testing.expectEqual(@as(?Range, null), pairRange(&empty, .{ .row = 0, .col = 0 }, '(', ')', false));
    // not enclosed
    try std.testing.expectEqual(@as(?Range, null), pairRange(&empty, .{ .row = 0, .col = 1 }, '[', ']', false));
}

test "quoteRange line-scoped" {
    const lines = [_][]const u8{"say 'hi there' end"};
    const w = &lines;
    const r = quoteRange(w, .{ .row = 0, .col = 7 }, '\'', true).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 4 }, r.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 13 }, r.b);
    const ri = quoteRange(w, .{ .row = 0, .col = 7 }, '\'', false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, ri.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 12 }, ri.b);
    // cursor after the pair: not enclosed
    try std.testing.expectEqual(@as(?Range, null), quoteRange(w, .{ .row = 0, .col = 16 }, '\'', true));
}

test "wordRange inside/around" {
    const lines = [_][]const u8{"one  two.three"};
    const w = &lines;
    const r = wordRange(w, .{ .row = 0, .col = 1 }, false, false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, r.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 2 }, r.b);
    // around eats the trailing spaces
    const ra = wordRange(w, .{ .row = 0, .col = 1 }, false, true).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 4 }, ra.b);
    // long word spans the dot
    const rl = wordRange(w, .{ .row = 0, .col = 6 }, true, false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, rl.a);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 13 }, rl.b);
    // on whitespace: none
    try std.testing.expectEqual(@as(?Range, null), wordRange(w, .{ .row = 0, .col = 3 }, false, false));
}

test "paragraphRange inside/around" {
    const lines = [_][]const u8{ "a", "b", "", "c" };
    const w = &lines;
    const r = paragraphRange(w, .{ .row = 1, .col = 0 }, false).?;
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 0 }, r.a);
    try std.testing.expectEqual(Cursor{ .row = 1, .col = 0 }, r.b);
    const ra = paragraphRange(w, .{ .row = 1, .col = 0 }, true).?;
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 0 }, ra.b);
    try std.testing.expectEqual(@as(?Range, null), paragraphRange(w, .{ .row = 2, .col = 0 }, false));
}

test "advanceBy" {
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 5 }, advanceBy(.{ .row = 0, .col = 2 }, "abc"));
    try std.testing.expectEqual(Cursor{ .row = 2, .col = 1 }, advanceBy(.{ .row = 0, .col = 2 }, "a\nbc\nd"));
}

test "replaceRange" {
    const a = std.testing.allocator;
    const r = try replaceRange(a, "hello world", .{ .row = 0, .col = 0 }, .{ .row = 0, .col = 4 }, "bye");
    defer a.free(r);
    try std.testing.expectEqualStrings("bye world", r);
}

test "replaceChars overwrites newlines too" {
    const a = std.testing.allocator;
    const r = try replaceChars(a, "ab\ncd", .{ .row = 0, .col = 1 }, .{ .row = 1, .col = 0 }, 'x');
    defer a.free(r);
    try std.testing.expectEqualStrings("axxxd", r);
}

test "changeCase" {
    const a = std.testing.allocator;
    const t = try changeCase(a, "aB cD", .{ .row = 0, .col = 0 }, .{ .row = 0, .col = 4 }, .toggle);
    defer a.free(t);
    try std.testing.expectEqualStrings("Ab Cd", t);
    const lo = try changeCase(a, "AB CD", .{ .row = 0, .col = 0 }, .{ .row = 0, .col = 1 }, .lower);
    defer a.free(lo);
    try std.testing.expectEqualStrings("ab CD", lo);
    const up = try changeCase(a, "ab cd", .{ .row = 0, .col = 3 }, .{ .row = 0, .col = 4 }, .upper);
    defer a.free(up);
    try std.testing.expectEqualStrings("ab CD", up);
}

test "joinLine" {
    const a = std.testing.allocator;
    const r = (try joinLine(a, "one\n   two\nthree", 0)).?;
    defer a.free(r.content);
    try std.testing.expectEqualStrings("one two\nthree", r.content);
    try std.testing.expectEqual(@as(usize, 3), r.col);
    // last line: nothing to join
    try std.testing.expectEqual(@as(?@TypeOf(r), null), try joinLine(a, "one", 0));
}

test "indentLines add and remove" {
    const a = std.testing.allocator;
    const r = try indentLines(a, "one\n\ntwo", 0, 2, true);
    defer a.free(r);
    try std.testing.expectEqualStrings("    one\n\n    two", r);
    const u = try indentLines(a, "    one\n\ttwo\n  three\nx", 0, 2, false);
    defer a.free(u);
    try std.testing.expectEqualStrings("one\ntwo\nthree\nx", u);
}

test "adjustNumber" {
    const a = std.testing.allocator;
    const r = (try adjustNumber(a, "x 41 y", .{ .row = 0, .col = 3 }, 1)).?;
    defer a.free(r.content);
    try std.testing.expectEqualStrings("x 42 y", r.content);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 3 }, r.cur);
    // negative, cursor on the '-'
    const n = (try adjustNumber(a, "v=-1;", .{ .row = 0, .col = 2 }, -1)).?;
    defer a.free(n.content);
    try std.testing.expectEqualStrings("v=-2;", n.content);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 3 }, n.cur);
    // width change moves the last-digit column
    const g = (try adjustNumber(a, "9", .{ .row = 0, .col = 0 }, 1)).?;
    defer a.free(g.content);
    try std.testing.expectEqualStrings("10", g.content);
    try std.testing.expectEqual(Cursor{ .row = 0, .col = 1 }, g.cur);
    // not on a number
    try std.testing.expectEqual(@as(?@TypeOf(r), null), try adjustNumber(a, "abc", .{ .row = 0, .col = 0 }, 1));
}

test "deleteSpan including the newline" {
    const a = std.testing.allocator;
    const r = try deleteSpan(a, "hello world", .{ .row = 0, .col = 2 }, .{ .row = 0, .col = 5 });
    defer a.free(r);
    try std.testing.expectEqualStrings("he world", r);
    const j = try deleteSpan(a, "ab\ncd", .{ .row = 0, .col = 2 }, .{ .row = 1, .col = 0 });
    defer a.free(j);
    try std.testing.expectEqualStrings("abcd", j);
    // empty span: copy
    const e = try deleteSpan(a, "ab", .{ .row = 0, .col = 1 }, .{ .row = 0, .col = 1 });
    defer a.free(e);
    try std.testing.expectEqualStrings("ab", e);
}

test "pasteLineBelow" {
    const content = "one\ntwo";
    const a = std.testing.allocator;
    const r = try pasteLineBelow(a, content, 0, "INSERTED");
    defer a.free(r);
    try std.testing.expectEqualStrings("one\nINSERTED\ntwo", r);
    // paste below last line
    const r2 = try pasteLineBelow(a, content, 1, "END");
    defer a.free(r2);
    try std.testing.expectEqualStrings("one\ntwo\nEND", r2);
    // multiline yanked text
    const r3 = try pasteLineBelow(a, content, 0, "a\nb");
    defer a.free(r3);
    try std.testing.expectEqualStrings("one\na\nb\ntwo", r3);
}