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
|
//! Helix normal mode: a key read against the configured bindings becomes
//! modal actions, replayed across every selection, and each action is done
//! to the pane (a kind's pane takes its own keys first, Kind.key).
const pardes = @import("root.zig");
const tagline = @import("tagline.zig");
const exec = @import("exec.zig");
const look = @import("look.zig");
const std = @import("std");
const regexp = @import("regexp.zig");
const syntax = @import("syntax.zig");
const modal = @import("modal.zig");
const panes = @import("panes.zig");
const edit = @import("edit.zig");
const config = @import("config.zig");
const keyboard = @import("keys.zig");
const Pane = panes.Pane;
const Text = @import("Text.zig");
const File = @import("File.zig");
const Key = @import("plain").Key;
const hit = @import("Event.zig").hit;
const sel_slot = pardes.sel_slot;
const Pardes = pardes.Pardes;
const Macro = pardes.Macro;
const Editor = @import("Editor.zig");
const Prompt = @import("Prompt.zig");
fn isPrefix(key: Key, cp: u21) bool {
return key.cp == cp and !key.ctrl and !key.alt;
}
pub fn multiOnce(e: Editor) bool {
e.multi_stop.* = true;
return e.multi_first.*;
}
fn regexMarker(mode: modal.Normal.RegexMode) []const u8 {
return switch (mode) {
.select => config.select_marker,
.split => config.split_marker,
.keep => config.keep_marker,
.remove => config.remove_marker,
};
}
pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal.RegexMode } {
if (pane.prompt != .search or pane.nsel_snap == 0) return null;
const armed = pane.input.own orelse "";
const mode: modal.Normal.RegexMode = for (std.enums.values(modal.Normal.RegexMode)) |m| {
if (std.mem.startsWith(u8, armed, regexMarker(m))) break m;
} else return null;
const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null;
return .{ .pat = armed[slash + 1 ..], .mode = mode };
}
/// Select (or split on, keep or remove by) `pat` inside the selections `t`
/// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on
/// `pane`. The ranges it found: none, the snapshot's back.
pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) usize {
return selectByRegex(p.editor(), t, pane.sel_snap[0..pane.nsel_snap], pane.sel_snap_pri, pane.sel_snap_expl, pat, mode);
}
/// Select (or split on, keep or remove by) `pat` inside `snap`, the
/// ranges there were (primary `pri`) when s/S/K/Alt-K was pressed; the
/// ranges it found.
pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, expl: bool, pat: []const u8, mode: modal.Normal.RegexMode) usize {
const text = edit.flatSurface(e, t) catch |err| {
e.reportError(err);
return 0;
};
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
if (regexp.Regex.compile(pat)) |compiled| {
var re = compiled;
var hay_all = text;
if (for (pat) |c| {
if (std.ascii.isUpper(c)) break false;
} else true) hay_all = std.ascii.allocLowerString(e.scratch, text) catch |err| {
e.reportError(err);
return 0;
};
for (snap) |r| {
const from = @min(r.anchor, r.head);
const to = @min(@max(r.anchor, r.head), text.len);
if (from >= to) continue;
if (mode == .keep or mode == .remove) {
// helix keep_or_remove_matches: the range stays when a match
// starts inside it (K), or when none does (Alt-K)
const hit_at = re.find(hay_all, from, to, to) catch null;
const found = if (hit_at) |h| h.start < to else false;
if (found == (mode == .keep) and m < Text.max_selections) {
out[m] = r;
m += 1;
}
continue;
}
// Searched as sam searches, the way addr does (regexp.zig): the
// text around the selection still says where its lines begin.
var at = from;
var piece = from; // split: where the next piece begins
while (at < to and m < Text.max_selections) {
// A search too slow to finish keeps what it found so far.
const hit_at = (re.find(hay_all, at, to, to) catch break) orelse break;
if (mode == .split) {
out[m] = .{ .anchor = piece, .head = hit_at.start };
m += 1;
piece = hit_at.end;
} else if (hit_at.start != to) {
out[m] = .{ .anchor = hit_at.start, .head = hit_at.end };
m += 1;
}
// an empty match would otherwise never advance
at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1;
}
if (mode == .split and piece < to and m < Text.max_selections) {
out[m] = .{ .anchor = piece, .head = to };
m += 1;
}
}
} else |_| {}
if (m == 0) {
// the text CAN move under an armed prompt (a tag chord runs a
// builtin), and these are raw offsets into the surface as it was
for (snap) |*r| {
r.anchor = @min(r.anchor, text.len);
r.head = @min(r.head, text.len);
}
t.setRanges(e.tab, text, snap, &.{}, pri, expl);
return 0;
}
t.setRanges(e.tab, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO)
return m;
}
fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match {
var last: ?regexp.Regex.Match = null;
var at = from;
while (at <= to) {
const found = re.find(hay, at, to) orelse break;
last = found;
at = if (found.end > found.start) found.end else modal.nextGrapheme(hay, found.end);
if (at <= found.start) break;
}
return last;
}
// mvzr's word boundary is ASCII-only. Strip outer boundaries and check
// them against Unicode characters for search-selection patterns. A pane's
// Places keep one of these, compiled with the gpa, for as long as they live.
pub const SearchRegex = struct {
const Branch = struct { re: regexp.Regex, start_word: bool, end_word: bool };
branches: []Branch,
pub fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex {
if (std.mem.indexOf(u8, pattern, "\\b") == null) {
const branches = try arena.alloc(Branch, 1);
errdefer arena.free(branches);
branches[0] = try branch(pattern);
return .{ .branches = branches };
}
var branches: std.ArrayList(Branch) = .empty;
errdefer branches.deinit(arena);
var from: usize = 0;
var depth: usize = 0;
var escaped = false;
var in_class = false;
for (pattern, 0..) |c, i| {
if (escaped) {
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (c == '[') in_class = true else if (c == ']') in_class = false;
if (in_class) continue;
if (c == '(') depth += 1 else if (c == ')') depth -|= 1;
if (c == '|' and depth == 0) {
try branches.append(arena, try branch(pattern[from..i]));
from = i + 1;
}
}
try branches.append(arena, try branch(pattern[from..]));
for (branches.items) |*b| b.re.steps = regexp.Regex.budget / branches.items.len;
return .{ .branches = try branches.toOwnedSlice(arena) };
}
fn branch(pattern: []const u8) !Branch {
var pat = pattern;
const start = std.mem.startsWith(u8, pat, "\\b");
if (start) pat = pat[2..];
const end = std.mem.endsWith(u8, pat, "\\b") and !std.mem.endsWith(u8, pat, "\\\\b");
if (end) pat = pat[0 .. pat.len - 2];
return .{ .re = try regexp.Regex.compile(pat), .start_word = start, .end_word = end };
}
pub fn find(self: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match {
var best: ?regexp.Regex.Match = null;
for (self.branches) |*b| {
var at = from;
while (at <= to) {
const found = (b.re.find(hay, at, to, to) catch break) orelse break;
if ((!b.start_word or modal.searchWordBefore(hay, found.start) != modal.searchWordAt(hay, found.start)) and
(!b.end_word or modal.searchWordBefore(hay, found.end) != modal.searchWordAt(hay, found.end)))
{
if (best == null or found.start < best.?.start) best = found;
break;
}
at = modal.nextGrapheme(hay, found.start);
if (at <= found.start) break;
}
}
return best;
}
};
pub fn appendSearchLiteral(out: *std.ArrayList(u8), arena: std.mem.Allocator, text: []const u8) !void {
for (text) |c| {
if (std.mem.indexOfScalar(u8, "\\^$.[]()|*+?{}", c) != null) try out.append(arena, '\\');
if (c == '\n') try out.appendSlice(arena, "\\n") else try out.append(arena, c);
}
}
/// The file's parse, made on the first key that walks it after an edit and
/// kept until the next: never made again for a key that changed nothing.
/// Of the file's text, as every parse is (File.fileText: the `Changes`
/// layer's lines are none of it).
pub fn fileTree(p: *Pardes, f: *panes.File.State) ?*anyopaque {
if (f.node_tree == null or f.node_tree_revision != f.revision) {
const text = panes.File.fileText(f, p.scratch.allocator()) catch return null;
const old = f.node_tree;
f.node_tree = syntax.parseTree(f.path, text, if (f.node_tree_edits == f.revision) old else null);
if (old) |o| syntax.freeTree(o);
f.node_tree_revision = f.revision;
f.node_tree_edits = f.revision;
for (f.node_history.items) |step| p.gpa.free(step.ranges);
f.node_history.clearRetainingCapacity();
}
return f.node_tree;
}
/// The parse a body's tree-sitter walks read: its file's (`fileTree`), or
/// in the library the one its caller handed in (lib_editor.Syntax); null
/// without a grammar, and the walk leaves the ranges as they are.
pub fn nodeTree(e: Editor, t: *Text, text: []const u8) ?Editor.Tree {
if (t.what != .body) return null;
if (comptime Editor.lib) return (e.syntax orelse return null).walkTree(text);
const pane = t.pane() orelse return null;
const f = if (pane.file) |*file| file else return null;
const root = fileTree(e.p, f) orelse return null;
const parsed = panes.File.fileText(f, e.scratch) catch return null;
return .{ .root = root, .path = f.path, .history = &f.node_history, .gpa = e.gpa, .text = parsed, .file = f };
}
/// `]f`/`[f` and kin (helix goto_ts_object): to the next object starting
/// after the cursor or the previous one ending before it, count times; select
/// mode stretches the range to it.
fn objectJump(e: Editor, t: *Text, text: []const u8, range: modal.Selection, object: modal.Normal.Object, forward: bool, count: u32) void {
const tree = nodeTree(e, t, text) orelse return;
var last = range;
for (0..count) |_| {
const s = syntax.objectNext(tree.path, tree.root, tree.text, object, forward, tree.in(modal.selectionCursor(text, last)), null) orelse break;
const next: modal.Selection = .{ .anchor = tree.out(s.from, false), .head = tree.out(s.to, s.to > s.from) };
if (std.meta.eql(next, last)) break;
last = next;
}
if (std.meta.eql(last, range)) return;
if (t.select) {
const head = if (last.head < range.anchor) last.anchor else last.head;
return t.setRange(e.tab, text, 0, .{ .anchor = range.anchor, .head = head }, false);
}
const out: modal.Selection = if (forward) last else .{ .anchor = last.head, .head = last.anchor };
t.setRange(e.tab, text, 0, out, false);
}
/// helix's tree-sitter selection keys: every range walks the text's parse
/// (`nodeTree`), which is made on the first of these keys after an edit and
/// kept, never made again for a key that changed nothing. A range the tree
/// has nothing to say about stays as it was; a text without a grammar, all
/// of them.
pub fn nodeSelect(e: Editor, t: *Text, text: []const u8, walk: modal.Normal.NodeWalk) edit.Error!void {
const tree = nodeTree(e, t, text) orelse return;
const expl = t.vsel.active and t.vsel.explicit;
const arena = e.scratch;
const rs = try arena.alloc(modal.Selection, Text.max_selections);
const got = t.ranges(text, 0, rs[0..Text.max_selections]);
if (walk == .shrink_node) if (tree.history.pop()) |prev| {
defer tree.gpa.free(prev.ranges);
// back to what Alt-o grew from, while the selection still holds it
const holds = for (prev.ranges) |pr| {
const pf = @min(pr.anchor, pr.head);
const pt = @max(pr.anchor, pr.head);
if (for (rs[0..got.n]) |r| {
if (@min(r.anchor, r.head) <= pf and pt <= @max(r.anchor, r.head)) break true;
} else false) continue;
break false;
} else true;
if (holds) return t.setRanges(e.tab, text, prev.ranges, &.{}, prev.primary, expl);
for (tree.history.items) |step| tree.gpa.free(step.ranges);
tree.history.clearRetainingCapacity();
};
const out = try arena.alloc(modal.Selection, Text.max_selections);
const spans = try arena.alloc(syntax.Span, Text.max_selections);
var m: usize = 0;
for (rs[0..got.n]) |r| {
if (m == out.len) break;
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
const back = r.head < r.anchor;
const n = syntax.walkNodes(tree.root, walk, tree.in(from), tree.in(to), tree.in(modal.selectionCursor(text, r)), spans[0 .. out.len - m]);
for (spans[0..n]) |*s| s.* = .{ .from = tree.out(s.from, false), .to = tree.out(s.to, s.to > s.from) };
if (n == 0) {
out[m] = r;
m += 1;
continue;
}
for (spans[0..n]) |s| {
out[m] = switch (walk) {
.next_sibling => .{ .anchor = s.from, .head = s.to },
.prev_sibling => .{ .anchor = s.to, .head = s.from },
// helix move_parent_node_end: a one-character range on the
// bound, or stretched to it in select mode
.parent_node_end, .parent_node_start => bound: {
const head = s.from;
if (t.select) {
const anchor = r.anchor;
break :bound .{ .anchor = anchor, .head = if (head >= anchor) modal.nextGrapheme(text, head) else head };
}
const next = modal.nextGrapheme(text, head);
break :bound if (back) .{ .anchor = next, .head = head } else .{ .anchor = head, .head = next };
},
else => if (back) .{ .anchor = s.to, .head = s.from } else .{ .anchor = s.from, .head = s.to },
};
m += 1;
}
}
const same = m == got.n and std.mem.eql(u8, std.mem.sliceAsBytes(out[0..m]), std.mem.sliceAsBytes(rs[0..m]));
if (walk == .expand_node and !same) remember: {
const ranges = tree.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember;
tree.history.append(tree.gpa, .{ .ranges = ranges, .primary = got.pri }) catch tree.gpa.free(ranges);
}
t.setRanges(e.tab, text, out[0..m], &.{}, @min(got.pri, m - 1), expl);
}
/// `gw` (helix goto_word): label the words in view, nearest the cursor first,
/// with two letters each; the next two keys choose one (`jumpKey`).
fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void {
if (t.what != .body) return;
const text = try edit.flatSurface(p.editor(), t);
const cursor = modal.selectionCursor(text, t.primaryRange(text, 0));
const top: usize = @intCast(@max(0, pane.scroll()));
// A file's words the body shows, its rows' bytes; a terminal's rows
// are its lines.
const shown = if (pane.file != null) File.shownBytes(p.settings.tab, pane) else File.Bytes{ .start = modal.lineStartOffset(text, top), .end = modal.lineStartOffset(text, top + pane.rows) };
const start = @min(shown.start, text.len);
const end = @min(shown.end, text.len);
const letters = config.jump_label_alphabet.len;
try pane.jump.resize(p.gpa, letters * letters);
const n = modal.jumpWords(text, cursor, start, end, pane.jump.items);
// A word the body's first row starts inside of (a wrapped line's row
// cut mid-word) begins above it: no label it would not show.
var kept: usize = 0;
for (pane.jump.items[0..n]) |r| if (@min(r.anchor, r.head) >= start) {
pane.jump.items[kept] = r;
kept += 1;
};
pane.jump.shrinkRetainingCapacity(kept);
pane.jump_first = null;
}
/// A key while `gw`'s labels are up: a label's first letter, then its
/// second, which selects that word; anything else takes the labels away.
pub fn jumpKey(p: *Pardes, pane: *Pane, t: *Text, key: Key) void {
const letters = config.jump_label_alphabet;
const at = if (key.ctrl or key.alt or key.cp > 0x7f) null else std.mem.indexOfScalar(u8, letters, @intCast(key.cp));
const i = at orelse return pane.jump.clearRetainingCapacity();
const first = pane.jump_first orelse {
if (i * letters.len > pane.jump.items.len) return pane.jump.clearRetainingCapacity();
pane.jump_first = @intCast(i);
return;
};
const chosen = first * letters.len + i;
defer pane.jump.clearRetainingCapacity();
if (chosen >= pane.jump.items.len) return;
const r = pane.jump.items[chosen];
const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(p.view().active), "edit", err);
if (!t.select) return t.setRange(p.settings.tab, text, 0, .{ .anchor = @min(r.anchor, r.head), .head = @max(r.anchor, r.head) }, true);
// select mode stretches the primary to the word (helix Movement::Extend)
const pr = t.primaryRange(text, 0);
const anchor = if (r.anchor < r.head) @min(r.anchor, @min(pr.anchor, pr.head)) else @max(r.anchor, @max(pr.anchor, pr.head));
t.setRange(p.settings.tab, text, 0, .{ .anchor = anchor, .head = r.head }, true);
}
const KeyState = struct {
mode: Text.Mode,
select: bool,
normal: modal.Normal.State,
find_op: ?modal.Normal.Find,
find_ch: u21,
restore_cursor: bool,
reg_wait: bool,
fn of(t: *Text) KeyState {
return .{
.mode = t.mode,
.select = t.select,
.normal = t.normal,
.find_op = t.find_op,
.find_ch = t.find_ch,
.restore_cursor = t.restore_cursor,
.reg_wait = t.reg_wait,
};
}
fn into(s: KeyState, t: *Text) void {
t.mode = s.mode;
t.select = s.select;
t.normal = s.normal;
t.find_op = s.find_op;
t.find_ch = s.find_ch;
t.restore_cursor = s.restore_cursor;
t.reg_wait = s.reg_wait;
}
};
/// what a replayed key does at each cursor
const Replay = union(enum) {
normal: modal.Normal.Action,
insert: Key,
};
/// a range's start CELL (document order key) โ the smaller of its two ends
fn selStart(s: Text.SelRange) struct { row: i32, col: i32 } {
if (s.arow < s.row or (s.arow == s.row and s.acol < s.col)) return .{ .row = s.arow, .col = s.acol };
return .{ .row = s.row, .col = s.col };
}
pub fn replaySels(e: Editor, t: *Text, what: Replay) void {
const id = if (comptime Editor.lib) 0 else e.p.view().active;
// a header belongs to no pane and cannot go away under the replay
const owner = t.pane();
const serial = if (owner) |pane| pane.serial else 0;
// the whole selection in text coordinates, document order. t.sels
// is already ordered, so this only slots the primary into place.
var list: [Text.max_selections]Text.SelRange = undefined;
var n: usize = 0;
var pri: usize = 0;
const prim: Text.SelRange = .{
.row = t.cur_row,
.col = t.cur_col,
.arow = if (t.vsel.active) t.vsel.row else t.cur_row,
.acol = if (t.vsel.active) t.vsel.col else t.cur_col,
.sticky = t.sticky_col,
};
const pr = selStart(prim);
var placed = false;
for (t.sels[0..t.nsel]) |s| {
const sr = selStart(s);
if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) {
pri = n;
list[n] = prim;
n += 1;
placed = true;
}
list[n] = s;
n += 1;
}
if (!placed) {
pri = n;
list[n] = prim;
n += 1;
}
const saved = KeyState.of(t);
const explicit = t.vsel.explicit;
var after = saved;
var after_expl = explicit;
// each pass's result: cursor and anchor cells as distances from the
// end of the surface text, plus the range's own j/k goal column
var res: [Text.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined;
e.multi_stop.* = false;
var passes: usize = 0;
var i: usize = n;
while (i > 0) {
i -= 1;
e.multi_first.* = passes == 0;
e.multi_index.* = i;
e.multi_count.* = n;
passes += 1;
saved.into(t);
t.nsel = 0; // the handler underneath sees ONE selection
t.cur_row = list[i].row;
t.cur_col = list[i].col;
t.vsel = .{
.active = list[i].arow != list[i].row or list[i].acol != list[i].col or t.select,
.row = list[i].arow,
.col = list[i].acol,
.explicit = explicit,
};
t.sticky_col = list[i].sticky;
(switch (what) {
.normal => |normal_action| actionPass(e, t, normal_action),
.insert => |insert_key| edit.insertKey(e, t, insert_key),
}) catch |err| e.reportError(err);
if (e.multi_stop.*) break;
if (i == pri) {
after = KeyState.of(t);
after_expl = t.vsel.explicit;
}
const text = edit.flatSurface(e, t) catch {
e.multi_stop.* = true;
break;
};
const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
const ao = if (t.vsel.active)
modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) })
else
co;
res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = t.sticky_col };
}
e.multi_first.* = true;
e.multi_index.* = 0;
e.multi_count.* = 1;
if (e.multi_stop.*) {
e.multi_stop.* = false;
if (owner != null) {
const pn = e.p.panes[id] orelse return;
if (pn.serial != serial) return;
}
t.nsel = 0;
return;
}
const text = edit.flatSurface(e, t) catch |err| return e.reportError(err);
var rs: [Text.max_selections]modal.Selection = undefined;
var st: [Text.max_selections]i32 = undefined;
for (res[0..n], 0..) |r, k| {
rs[k] = Text.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len));
st[k] = r.sticky;
}
t.setRanges(e.tab, text, rs[0..n], st[0..n], pri, after_expl);
after.into(t);
t.show(e.tab); // the view follows the PRIMARY, not the last pass
}
fn normalInput(key: Key) modal.Normal.Input {
var out: modal.Normal.Input = .{
.cp = key.cp,
.ctrl = key.ctrl,
.alt = key.alt,
};
inline for (std.enums.values(modal.Normal.Role)) |role| {
const name = @tagName(role);
const binding = @field(config, name);
const matched = if (@TypeOf(binding) == comptime_int)
isPrefix(key, binding)
else if (@TypeOf(binding) == []const config.Chord)
hit(key, binding)
else
@compileError("normal input binding has unsupported type: " ++ name);
if (matched) out.roles.insert(role);
}
return out;
}
/// A key in a text's normal or insert mode, as keys.zig hands it on after
/// its own intercepts, and as the library takes it (lib_editor.zig): what
/// the parse made of it, `.ignored` for a key typed in insert mode.
pub fn textKey(e: Editor, t: *Text, key: Key) modal.Normal.Result {
switch (t.mode) {
.normal => return handleNormal(e, t, key),
.insert => if (hit(key, config.escape) and !t.reg_wait)
edit.exitInsert(e, t)
else
edit.handleInsert(e, t, key),
.tty => unreachable, // the terminal's (keys.zig)
}
return .ignored;
}
pub fn handleNormal(e: Editor, t: *Text, key: Key) modal.Normal.Result {
// `"<reg>` is held by the parser until the command it names arrives
const named = t.normal.register;
const parsed = modal.Normal.parse(&t.normal, normalInput(key));
const action = switch (parsed) {
.pending, .ignored, .unbound => return parsed,
.action => |value| value,
};
t.normal.register = 0;
// the core's roles are the library's caller's
if (comptime Editor.lib) if (!textRole(action.role, e.syntax != null)) return parsed;
e.register.* = named;
defer e.register.* = 0;
runAction(e, t, action);
return parsed;
}
/// A normal-mode action run across every range, or once for the
/// selection as a whole.
pub fn runAction(e: Editor, t: *Text, action: modal.Normal.Action) void {
if (t.nsel == 0 or action.once())
return actionPass(e, t, action) catch |err| e.reportError(err);
replaySels(e, t, .{ .normal = action });
}
/// One pass of an action: the core's, which hands the text its own roles;
/// the library has the text's alone.
fn actionPass(e: Editor, t: *Text, action: modal.Normal.Action) edit.Error!void {
if (comptime Editor.lib) return textAction(e, t, action);
return executeNormalAction(e.p, t, action);
}
fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void {
// A body's prompt is its tag's (Prompt.zig); a tag's or a header's asks
// on the notice band.
if (t.what == .body) return Prompt.open(p, pane, Prompt.ofMode(mode));
const text = try edit.flatSurface(p.editor(), t);
const got = t.ranges(text, 0, &pane.sel_snap);
pane.nsel_snap = @intCast(got.n);
pane.sel_snap_pri = @intCast(got.pri);
pane.sel_snap_expl = t.vsel.active and t.vsel.explicit;
panes.startPrompt(p, pane, t, .{ .search = regexMarker(mode) });
}
/// Search only the primary range, as Helix does. Select mode adds a new
/// match and makes it primary; normal mode replaces only the primary.
fn searchStep(e: Editor, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void {
const v = e.p.view();
const name = if (e.register.* != 0) e.register.* else e.registers.last_search;
const pat = e.registers.value(name, 0) orelse return;
var re = SearchRegex.compile(e.scratch, pat) catch {
e.p.setMessage(.at(v.active), "invalid search pattern");
return;
};
var hay = text;
if (for (pat) |c| {
if (std.ascii.isUpper(c)) break false;
} else true) hay = try std.ascii.allocLowerString(e.scratch, text);
for (0..count) |_| {
var ranges: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &ranges);
const old = ranges[got.pri];
const from = @min(old.anchor, old.head);
const to = @max(old.anchor, old.head);
var wrapped = false;
const found = (if (forward) blk: {
if (re.find(hay, to, hay.len)) |h| break :blk h;
wrapped = true;
break :blk re.find(hay, 0, hay.len);
} else blk: {
if (lastMatch(&re, hay, 0, from)) |h| break :blk h;
wrapped = true;
break :blk lastMatch(&re, hay, from, hay.len);
}) orelse {
e.p.setMessage(.at(v.active), "no more matches");
return;
};
if (found.end == 0) return;
const next: modal.Selection = if (old.anchor > old.head)
.{ .anchor = found.end, .head = found.start }
else
.{ .anchor = found.start, .head = found.end };
if (t.select and got.n < ranges.len) {
ranges[got.n] = next;
t.setRanges(e.tab, text, ranges[0 .. got.n + 1], &.{}, got.n, true);
} else {
ranges[got.pri] = next;
t.setRanges(e.tab, text, ranges[0..got.n], &.{}, got.pri, true);
}
if (wrapped) e.p.setMessage(.at(v.active), "wrapped around document");
}
t.show(e.tab);
}
pub fn searchSelection(e: Editor, t: *Text, text: []const u8, boundary: bool) edit.Error!void {
var ranges: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &ranges);
var pattern: std.ArrayList(u8) = .empty;
const arena = e.scratch;
for (ranges[0..got.n], 0..) |r, i| {
const from = @min(r.anchor, r.head);
const to = @min(text.len, @max(r.anchor, r.head));
if (i > 0) try pattern.append(arena, '|');
if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) try pattern.appendSlice(arena, "\\b");
try appendSearchLiteral(&pattern, arena, text[from..to]);
if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) try pattern.appendSlice(arena, "\\b");
}
const name = if (e.register.* != 0) e.register.* else '/';
try e.registers.put(e.gpa, name, pattern.items, 0, 1, true);
e.registers.last_search = name;
}
fn multiSelAction(tab: u16, t: *Text, text: []const u8, role: modal.Normal.Role, cnt: usize) void {
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &rs);
const n = got.n;
const expl = t.vsel.active and t.vsel.explicit;
if (role == .remove_primary_sel) {
if (n < 2) return; // helix: "no selections remaining"
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
for (rs[0..n], 0..) |r, i| {
if (i == got.pri) continue;
out[m] = r;
m += 1;
}
// helix Selection::remove: the NEXT range takes over, or the
// previous one when the primary was last
return t.setRanges(tab, text, out[0..m], &.{}, @min(got.pri, m - 1), expl);
}
if (role == .rotate_sel_fwd or role == .rotate_sel_back) {
const turn = cnt % n;
const pri = if (role == .rotate_sel_fwd) (got.pri + turn) % n else (got.pri + (n - turn)) % n;
return t.setRanges(tab, text, rs[0..n], &.{}, pri, expl);
}
if (role == .merge_sels) {
// helix merge_selections: first.merge(last) โ the ranges are
// sorted, so that is simply the whole span
const lo = @min(rs[0].anchor, rs[0].head);
const hi = @max(rs[n - 1].anchor, rs[n - 1].head);
const rev = rs[0].anchor > rs[0].head and rs[n - 1].anchor > rs[n - 1].head;
const one: modal.Selection = if (rev) .{ .anchor = hi, .head = lo } else .{ .anchor = lo, .head = hi };
return t.setRanges(tab, text, &.{one}, &.{}, 0, expl);
}
if (role == .merge_consecutive_sels) {
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
var pri: usize = 0;
for (rs[0..n], 0..) |r, i| {
if (m > 0 and @min(r.anchor, r.head) == @max(out[m - 1].anchor, out[m - 1].head)) {
const lo = @min(@min(out[m - 1].anchor, out[m - 1].head), @min(r.anchor, r.head));
const hi = @max(@max(out[m - 1].anchor, out[m - 1].head), @max(r.anchor, r.head));
out[m - 1] = .{ .anchor = lo, .head = hi };
if (i == got.pri) pri = m - 1;
continue;
}
if (i == got.pri) pri = m;
out[m] = r;
m += 1;
}
return t.setRanges(tab, text, out[0..m], &.{}, pri, expl);
}
if (role == .ensure_forward) {
// helix ensure_selections_forward: every range points forward
for (rs[0..n]) |*r| {
const from = @min(r.anchor, r.head);
r.head = @max(r.anchor, r.head);
r.anchor = from;
}
return t.setRanges(tab, text, rs[0..n], &.{}, got.pri, expl);
}
if (role == .split_sel_newline) {
// helix selection::split_on_newline โ one range per line the
// selection covers, the newlines themselves left out
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
for (rs[0..n]) |r| {
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
if (from == to) {
if (m < Text.max_selections) {
out[m] = r;
m += 1;
}
continue;
}
var start = from;
while (start < to and m < Text.max_selections) {
const eol = modal.lineEndOffset(text, modal.lineAtOffset(text, start));
if (eol >= to) {
out[m] = .{ .anchor = start, .head = to };
m += 1;
break;
}
out[m] = .{ .anchor = start, .head = eol };
m += 1;
start = eol + 1;
}
}
if (m == 0) return;
return t.setRanges(tab, text, out[0..m], &.{}, 0, true); // helix keeps primary 0
}
if (role == .trim_sels) {
// helix trim_selections: whitespace off both ends; ranges that are
// empty or all whitespace are dropped entirely
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
for (rs[0..n]) |r| {
var from = @min(r.anchor, r.head);
var to = @max(r.anchor, r.head);
while (from < to and std.ascii.isWhitespace(text[from])) from += 1;
while (to > from and std.ascii.isWhitespace(text[to - 1])) to -= 1;
if (from >= to) continue;
out[m] = if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to };
m += 1;
}
if (m == 0) { // helix: collapse_selection + keep_primary_selection
const c = modal.selectionCursor(text, rs[got.pri]);
return t.setRange(tab, text, 0, .{ .anchor = c, .head = c }, false);
}
// helix: the first survivor that OVERLAPS the old primary, else the last
const pf = @min(rs[got.pri].anchor, rs[got.pri].head);
const pt = @max(rs[got.pri].anchor, rs[got.pri].head);
var pri = m - 1;
for (out[0..m], 0..) |r, i| {
const f = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
if (f == pf or (to > pf and pt > f)) {
pri = i;
break;
}
}
return t.setRanges(tab, text, out[0..m], &.{}, pri, expl);
}
const below = role == .copy_sel_below;
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
var pri: usize = 0;
const nlines = modal.cursorLineCount(text);
for (rs[0..n], 0..) |r, ri| {
const is_pri = ri == got.pri;
// head-exclusive: back the leading end off onto its own cell
const h_off = if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head;
const a_off = if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor);
const hp = modal.positionAt(text, h_off);
const ap = modal.positionAt(text, a_off);
var al: LineWalk = .of(text, a_off, ap.row);
var hl: LineWalk = .of(text, h_off, hp.row);
const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1;
if (m >= Text.max_selections) break;
if (is_pri) pri = m;
out[m] = r;
m += 1;
var made: usize = 0;
var k: usize = 0;
while (made < cnt and m < Text.max_selections) : (k += 1) {
const d = (k + 1) * height;
const arow = if (below) ap.row + d else ap.row -| d;
const hrow = if (below) hp.row + d else hp.row -| d;
if (arow >= nlines or hrow >= nlines) break;
// a line too short to reach the column is skipped, not clamped
const a2 = al.cell(text, arow, ap.col);
const h2 = hl.cell(text, hrow, hp.col);
if (a2 != null and h2 != null) {
if (is_pri) pri = m;
out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2.?, .head = a2.? }, h2.?, true);
m += 1;
made += 1;
}
if (arow == 0 and hrow == 0) break;
}
}
t.setRanges(tab, text, out[0..m], &.{}, pri, expl);
}
/// A line's start, walked on from the row C or Alt-C last tried: found
/// from the text's start, each try was a pass over all before it, and a
/// column no near line reaches hung the editor on a long text.
const LineWalk = struct {
row: usize,
start: usize,
fn of(text: []const u8, off: usize, row: usize) LineWalk {
return .{ .row = row, .start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0 };
}
/// Column `col` of `row`, or null where the line ends before it or a
/// grapheme there spans it.
fn cell(w: *LineWalk, text: []const u8, row: usize, col: usize) ?usize {
while (w.row < row) : (w.row += 1) w.start = std.mem.indexOfScalarPos(u8, text, w.start, '\n').? + 1;
while (w.row > row) : (w.row -= 1) w.start = if (std.mem.lastIndexOfScalar(u8, text[0 .. w.start - 1], '\n')) |nl| nl + 1 else 0;
const e = std.mem.indexOfScalarPos(u8, text, w.start, '\n') orelse text.len;
const g = modal.graphemeStart(text[w.start..e], @min(col, e - w.start));
return if (g == col) w.start + g else null;
}
};
fn maxLine(text: []const u8) usize {
const nl = modal.cursorLineCount(text);
return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1;
}
/// point-target motion: collapse there (extend in select mode)
fn pointMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, target: usize) void {
t.setRange(tab, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false);
}
/// word motions select their traversed span (extend mode: head only)
fn wordMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, cnt: usize, target: modal.WordTarget) void {
const wr = modal.moveWord(text, range, cnt, target);
const res = if (t.select) modal.moveSelectionCursor(text, range, modal.selectionCursor(text, wr), true) else wr;
t.setRange(tab, text, 0, res, false);
}
/// f/t/F/T: anchor at the old cursor cell, head on the hit (not found: no move)
fn findMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, ch: u21, kind: modal.Normal.Find, cnt: usize) void {
const cur = modal.selectionCursor(text, range);
const target = modal.findTarget(text, cur, ch, kind, cnt) orelse return;
const res = if (t.select)
modal.moveSelectionCursor(text, range, target, true)
else
modal.moveSelectionCursor(text, .{ .anchor = cur, .head = cur }, target, true);
t.setRange(tab, text, 0, res, false);
}
/// The file pane whose text `text` is, when `t` is its body: its rows are
/// measured through their table pads (File.rowPads), so j and k keep the
/// column a table shows, not the one its source has.
inline fn filePane(t: *Text, text: []const u8) ?*const Pane {
if (comptime Editor.lib) return null;
if (t.what != .body) return null;
const fp = t.pane() orelse return null;
const f = if (fp.file) |*file| file else return null;
return if (f.content.ptr == text.ptr and f.content.len == text.len) fp else null;
}
/// j/k (`width` 0: a line is one row) and gj/gk (the rows a body `width`
/// cells wide wraps a line into): sticky goal column, clamped onto short
/// lines' newline.
fn verticalMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, down: bool, cnt: usize, width: usize) void {
const cur = modal.selectionCursor(text, range);
const pos = File.textPosition(t, text, cur);
const last_row = File.textLineCount(t, text) - 1;
var row = pos.row;
var line = File.textLine(t, text, row);
var vrow = File.visualRow(tab, line, pos.col, width);
const shown = filePane(t, text);
const goal: usize = if (t.sticky_col >= 0)
@intCast(t.sticky_col)
else if (shown) |fp|
@intCast(@max(0, File.displayOffset(tab, fp, @intCast(row), @intCast(vrow.start), @intCast(pos.col))))
else
File.rawDisplayCol(tab, line[vrow.start..vrow.end], pos.col -| vrow.start);
if (width == 0) {
row = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt);
line = File.textLine(t, text, row);
vrow = .{ .start = 0, .end = line.len };
} else for (0..@max(1, cnt)) |_| {
if (down) {
if (vrow.end < line.len) {
vrow = File.visualRow(tab, line, vrow.end, width);
continue;
}
if (row == last_row) break;
row += 1;
line = File.textLine(t, text, row);
vrow = File.visualRow(tab, line, 0, width);
} else {
if (vrow.start > 0) {
vrow = File.visualRow(tab, line, vrow.start - 1, width);
continue;
}
if (row == 0) break;
row -= 1;
line = File.textLine(t, text, row);
vrow = File.visualRow(tab, line, line.len, width);
}
}
// The newline slot is a real cursor position, but the first byte of the
// NEXT visual row is not: landing there would read as two rows moved.
var target_col: usize = if (shown) |fp|
@intCast(File.byteAtRowDisplay(tab, fp, @intCast(row), @intCast(vrow.start), @intCast(@min(goal, std.math.maxInt(i32)))))
else
vrow.start + File.rawAtDisplay(tab, line[vrow.start..vrow.end], goal);
if (vrow.end < line.len and target_col >= vrow.end)
target_col = modal.graphemeStart(line, vrow.end - 1);
const target = File.textOffset(t, text, .{ .row = row, .col = target_col });
// extend mode never walks onto the empty trailing line (helix)
if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return;
t.setRange(tab, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false);
t.sticky_col = @intCast(goal);
}
/// Ctrl-d/u: the view half the body's rows on, and the cursor where it
/// stood on the screen (inside the margins): on the line whose first row is
/// now there, the next one the way it went past a wrapped line's later
/// row, and the rows the view could not move (the text's end) further.
/// None in the body (inside a line taller than it): it stays, off the
/// view, and the view where it went. A terminal's rows are its lines: both
/// move by them.
fn halfPageMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, down: bool) void {
// a view to move through is a body's; a tag or an answer is all shown
if (t.what != .body) return;
const w = t.pane() orelse return;
const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2));
if (w.file == null) {
w.scrollBy(tab, if (down) half else -half);
return verticalMove(tab, t, text, range, down, @intCast(half), 0);
}
const body: i64 = File.shownRows(tab, w);
const margin = @min(config.scroll_off, @divTrunc(body - 1, 2));
const from = File.top(tab, w);
const line: usize = @intCast(@max(0, t.cur_row));
const on: i64 = if (File.rowsTo(tab, w, from, line, @intCast(body))) |d| d + File.rowOf(tab, w, line, @intCast(@max(0, t.cur_col))) else if (line < from.line) 0 else body - 1;
const moved = File.scrollRows(tab, w, if (down) half else -half);
const to = File.textRowLine(tab, w, on + (if (down) half else -half) - moved, margin, if (down) .down else .up) orelse return;
if (to == t.cur_row) return;
verticalMove(tab, t, text, range, to > t.cur_row, @abs(to - t.cur_row), 0);
}
/// gt/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window)
fn gotoWindow(tab: u16, t: *Text, text: []const u8, range: modal.Selection, which: enum { top, bottom }, cnt: usize) void {
// a view to move through is a body's; a tag or an answer is all shown
if (t.what != .body) return;
const w = t.pane() orelse return;
const n: i32 = @intCast(cnt - 1);
if (w.file != null) {
// In rows, as helix's goto_window: the row `margin + n` in from the
// body's top or its last row of text, inside the margins, the
// cursor on the first byte it shows (a wrapped line's later row).
const shown: i32 = File.shownRows(tab, w);
const held: i32 = w.context_rows;
const lines = File.textLineCount(t, text);
var last: i32 = shown - 1;
while (last > 0 and w.wrapAt(tab, held + last).line >= lines) last -= 1;
const margin: i32 = @min(config.scroll_off, @divTrunc(shown - 1, 2));
const vr = std.math.clamp(@min(@max(switch (which) {
.top => margin + n,
.bottom => last - (margin + n),
}, margin), last - margin), 0, last);
const at = w.wrapAt(tab, held + vr);
return pointMove(tab, t, text, range, File.textLineStart(t, text, @intCast(at.line)) + if (w.body_wrapped) @as(usize, @intCast(at.at)) else 0);
}
const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2));
const top = w.scroll();
const last_row: i32 = @intCast(File.textLineCount(t, text) - 1);
const last_vis: i32 = @min(@as(i32, w.rows) - 1, last_row - top);
var vline: i32 = switch (which) {
.top => top + margin + n,
.bottom => top + last_vis - (margin + n),
};
vline = @max(vline, top + margin);
vline = @min(vline, top + last_vis - margin);
const row: i32 = std.math.clamp(vline, 0, last_row);
pointMove(tab, t, text, range, File.textLineStart(t, text, @intCast(row)));
}
fn lineStartOrEof(text: []const u8, line: usize) usize {
if (line >= modal.cursorLineCount(text)) return text.len;
return modal.lineStartOffset(text, line);
}
/// helix `x` extend_line_below: full lines incl. the newline, cursor ON
/// the last one's '\n'; an already-line-bounded selection grows downward
fn lineSelect(tab: u16, t: *Text, text: []const u8, range: modal.Selection, cnt: usize) void {
const span = Text.rangeLineSpan(text, range);
const start = modal.lineStartOffset(text, span.start);
const end = lineStartOrEof(text, span.end + 1);
const full = @min(range.anchor, range.head) == start and @max(range.anchor, range.head) == end;
const head = lineStartOrEof(text, span.end + cnt + @intFromBool(full));
t.setRange(tab, text, 0, .{ .anchor = start, .head = head }, true);
}
/// helix `X` extend_to_line_bounds (direction kept)
fn lineBoundsSelect(tab: u16, t: *Text, text: []const u8, range: modal.Selection) void {
const span = Text.rangeLineSpan(text, range);
const start = modal.lineStartOffset(text, span.start);
const end = lineStartOrEof(text, span.end + 1);
const r: modal.Selection = if (range.head < range.anchor)
.{ .anchor = end, .head = start }
else
.{ .anchor = start, .head = end };
t.setRange(tab, text, 0, r, true);
}
/// helix `Alt-x` shrink_to_line_bounds (single-line selections untouched)
fn shrinkSelToLineBounds(tab: u16, t: *Text, text: []const u8, range: modal.Selection) void {
const span = Text.rangeLineSpan(text, range);
if (span.start == span.end) return;
const from = @min(range.anchor, range.head);
const to = @max(range.anchor, range.head);
var start = modal.lineStartOffset(text, span.start);
var end = lineStartOrEof(text, span.end + 1);
if (start != from) start = lineStartOrEof(text, span.start + 1);
if (end != to) end = modal.lineStartOffset(text, span.end);
const expl = t.vsel.active and t.vsel.explicit;
const r: modal.Selection = if (range.head < range.anchor)
.{ .anchor = end, .head = start }
else
.{ .anchor = start, .head = end };
t.setRange(tab, text, 0, r, expl);
}
/// Whether a normal-mode role is the text's alone (`textAction`), or
/// reaches past it: a view, a builtin, a prompt, a language server, the
/// look ring, the jump labels, a macro. The tree-sitter walks are the
/// text's with a parse at hand (`tree`, `nodeTree`): a pane's file has
/// one, the library's caller may hand one in.
pub fn textRole(role: modal.Normal.Role, tree: bool) bool {
return switch (role) {
.all_children, .all_siblings, .expand_node, .goto_class, .goto_comment, .goto_entry, .goto_function, .goto_parameter, .goto_test, .goto_xml_element, .next_sibling, .parent_node_end, .parent_node_start, .prev_sibling, .shrink_node => tree,
.append_output, .command_line, .format, .goto_callstack, .goto_change, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_implementation, .goto_references, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .page_down, .page_up, .pipe_selection, .pipe_selection_to, .remove_regex, .repeat_insert, .search, .search_back, .search_next, .search_prev, .select_regex, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false,
else => true,
};
}
/// A normal-mode action of the text's own (`textRole`): a motion, a
/// selection, an edit, an undo, a register.
pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void {
edit.pinPaneCursor(e, t);
const text = try edit.flatSurface(e, t);
const range = t.primaryRange(text, 0);
const cur = modal.selectionCursor(text, range);
switch (a.role) {
.escape => {
t.select = false;
if (comptime Editor.lib) return;
// typed again by a macro, Esc is only helix's
if (e.p.macro.replaying > 0) return;
// At rest a thing at a time (pick-ui SPEC ยง10.4): a search's
// tints (its word stays in the trail, dimmed: ยง7.3), then the
// warnings and errors, then the selections (the primary kept);
// with none of them left, the previous pane.
if (e.p.panes[e.p.view().active]) |pane| if (t == &pane.body and (pane.places.pattern.len > 0 or pane.places.hits.items.len > 0)) {
pane.places.clear(e.p.gpa);
e.p.needs_frame = true;
return;
};
if (e.p.messages.retire(&.{ .warn, .@"error" }) > 0) return;
if (t.nsel > 0) {
t.nsel = 0;
return;
}
tagline.exitHeader(e.p); // out of a header too, as Shift-Esc
return exec.runBuiltin(e.p, .Last, e.p.view().active, "", null);
},
// gg and G: a count names the line; bare G is no move (helix)
.goto_file_start, .goto_line => {
if (!a.explicit and a.role == .goto_line) return;
const to = if (a.explicit) @min(@as(usize, a.count) - 1, maxLine(text)) else 0;
return pointMove(e.tab, t, text, range, modal.lineStartOffset(text, to));
},
.goto_last_line => return pointMove(e.tab, t, text, range, modal.lineStartOffset(text, maxLine(text))),
.goto_line_start, .line_start => return pointMove(e.tab, t, text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))),
.goto_line_end, .line_end => {
const line = modal.lineAtOffset(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(e.tab, t, text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line))));
},
.goto_first_nonws, .line_first_nonws => {
const line = modal.lineAtOffset(text, cur);
const ls = modal.lineStartOffset(text, line);
const slice = text[ls..modal.lineEndOffset(text, line)];
const nw = modal.firstNonWs(slice);
if (nw == slice.len) return;
return pointMove(e.tab, t, text, range, ls + nw);
},
.goto_line_down => return verticalMove(e.tab, t, text, range, true, a.count, edit.paneWrapWidth(e, t)),
.goto_line_up => return verticalMove(e.tab, t, text, range, false, a.count, edit.paneWrapWidth(e, t)),
.goto_column => {
const line = modal.lineAtOffset(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(e.tab, t, text, range, ls + modal.graphemeAtColumn(text[ls..modal.lineEndOffset(text, line)], @as(usize, a.count) - 1));
},
.goto_last_modification => {
const at = t.last_edit orelse return;
return pointMove(e.tab, t, text, range, modal.offsetAt(text, .{ .row = @intCast(@max(0, at.row)), .col = @intCast(@max(0, at.col)) }));
},
.find_char_fwd, .find_char_back, .till_char_fwd, .till_char_back => {
t.find_op = switch (a.role) {
.find_char_fwd => .forward,
.find_char_back => .backward,
.till_char_fwd => .till_forward,
else => .till_backward,
};
t.find_ch = a.char;
return findMove(e.tab, t, text, range, a.char, t.find_op.?, a.count);
},
.replace_prefix => return edit.normalReplaceChar(e, t, a.char),
// `mm`
.match_prefix => {
const lines = try edit.paneCursorLines(e, t);
const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return;
return pointMove(e.tab, t, text, range, modal.offsetAt(text, mc));
},
.match_inside, .match_around => return edit.textobjectSelect(e, t, text, a.char, a.role == .match_around),
inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| {
const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]);
return objectJump(e, t, text, range, object, a.forward, a.count);
},
inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(e, t, text, @field(modal.Normal.NodeWalk, @tagName(role))),
.surround_add => return edit.surroundAdd(e, t, a.char),
.surround_delete => return edit.surroundDelete(e, t, a.char),
.surround_replace => return edit.surroundReplace(e, t, a.from, a.char),
.goto_paragraph => return t.setRange(e.tab, text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false),
.add_newline => return edit.addNewline(e, t, a.forward, a.count),
.move_left, .move_right => {
var target = cur;
for (0..a.count) |_| target = if (a.role == .move_left) modal.prevGrapheme(text, target) else modal.nextGrapheme(text, target);
return pointMove(e.tab, t, text, range, target);
},
.move_down => return verticalMove(e.tab, t, text, range, true, a.count, 0),
.move_up => return verticalMove(e.tab, t, text, range, false, a.count, 0),
inline .next_word_start, .prev_word_start, .next_word_end, .next_long_word_start, .prev_long_word_start, .next_long_word_end => |role| return wordMove(e.tab, t, text, range, a.count, @field(modal.WordTarget, @tagName(role))),
.repeat_find => {
const kind = t.find_op orelse return;
var repeated = range;
var moved = false;
for (0..a.count) |_| {
const cc = modal.selectionCursor(text, repeated);
const target = modal.findTarget(text, cc, t.find_ch, kind, 1) orelse break;
repeated = if (t.select)
modal.moveSelectionCursor(text, repeated, target, true)
else
modal.moveSelectionCursor(text, .{ .anchor = cc, .head = cc }, target, true);
moved = true;
}
if (!moved) return;
return t.setRange(e.tab, text, 0, repeated, false);
},
.insert, .append, .insert_line_start, .insert_line_end, .open_below, .open_above => {
const where: edit.InsertAt = switch (a.role) {
.insert => .at,
.append => .append,
.insert_line_start => .line_start,
.insert_line_end => .line_end,
.open_below => .open_below,
else => .open_above,
};
return edit.enterInsert(e, t, where, a.count);
},
.select_mode => {
if (t.select) {
t.select = false;
} else {
t.select = true;
if (!t.vsel.active) {
t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = true };
} else {
t.vsel.explicit = true;
}
}
t.cur_pinned = true;
},
.select_line => return lineSelect(e.tab, t, text, range, a.count),
.select_line_bounds => return lineBoundsSelect(e.tab, t, text, range),
.shrink_to_line_bounds => return shrinkSelToLineBounds(e.tab, t, text, range),
.collapse_selection => return t.setRange(e.tab, text, 0, .{ .anchor = cur, .head = cur }, false),
.flip_selection => {
const explicit = t.vsel.active and t.vsel.explicit;
return t.setRange(e.tab, text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit);
},
.select_all => return t.setRange(e.tab, text, 0, .{ .anchor = 0, .head = text.len }, false),
.keep_primary_sel => return t.dropSels(),
.copy_sel_below, .copy_sel_above, .remove_primary_sel, .rotate_sel_fwd, .rotate_sel_back, .split_sel_newline, .merge_sels, .merge_consecutive_sels, .trim_sels, .ensure_forward => return multiSelAction(e.tab, t, text, a.role, a.count),
.delete => return edit.normalDelete(e, t, true),
.delete_noyank => return edit.normalDelete(e, t, false),
.change => return edit.normalChange(e, t),
.yank => return edit.normalYank(e, t),
.replace_with_yank => return edit.pasteRegister(e, t, .replace, a.count),
.paste_after => return edit.pasteRegister(e, t, .after, a.count),
.paste_before => return edit.pasteRegister(e, t, .before, a.count),
.switch_case => return edit.normalCase(e, t, .toggle),
.to_lowercase => return edit.normalCase(e, t, .lower),
.to_uppercase => return edit.normalCase(e, t, .upper),
.join_lines => return edit.normalJoin(e, t, false),
.join_select_space => return edit.normalJoin(e, t, true),
.rotate_contents_fwd => return edit.normalRotateContents(e, t, true, a.count),
.rotate_contents_back => return edit.normalRotateContents(e, t, false, a.count),
.align_selections => return edit.normalAlign(e, t),
.indent => return edit.normalIndent(e, t, a.count, true),
.unindent => return edit.normalIndent(e, t, a.count, false),
.comment_toggle => return edit.normalToggleComment(e, t),
.undo => return edit.undoStep(e, t, true),
.redo => return edit.undoStep(e, t, false),
.increment => return edit.normalAdjustNumber(e, t, @intCast(a.count)),
.decrement => return edit.normalAdjustNumber(e, t, -@as(i64, @intCast(a.count))),
.search_selection, .search_selection_word => {
try searchSelection(e, t, text, a.role == .search_selection_word);
// The pattern lights its places and is the pane's search word,
// no prompt asked (Prompt.zig): n and N step them.
const pane = t.pane() orelse return;
if (t.what == .body and pane.file != null and pane.query == null) {
const name = if (e.register.* != 0) e.register.* else '/';
const pat = e.registers.value(name, 0) orelse return;
Prompt.star(e.p, pane, pat);
}
},
// prefix keys: what they begin is the command
.goto_prefix, .view_prefix, .next_prefix, .prev_prefix, .register_prefix, .view_prefix_sticky => {},
else => unreachable, // the core's (textRole)
}
}
fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void {
const v = p.view();
// What reaches past the text -- a builtin, a search, a language query --
// acts for the pane the text belongs to; a header's is the active one.
const pane = t.pane() orelse p.panes[v.active] orelse return;
const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null;
const before = .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode };
defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode })) {
pane.clearPointerSelection(sel_slot);
pane.sel[sel_slot].state = .none;
};
if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t);
if (textRole(a.role, true)) return textAction(p.editor(), t, a);
edit.pinPaneCursor(p.editor(), t);
const text = try edit.flatSurface(p.editor(), t);
const range = t.primaryRange(text, 0);
const cur = modal.selectionCursor(text, range);
switch (a.role) {
.goto_view_top => return gotoWindow(p.settings.tab, t, text, range, .top, a.count),
.goto_view_bottom => return gotoWindow(p.settings.tab, t, text, range, .bottom, a.count),
// helix align_view: the cursor's row goes `above` rows down the
// view, the middle of an odd one and the upper middle of an even one
.view_top, .view_center, .view_bottom => if (t.what == .body) {
// In rows: zt shows the cursor's line from its first row, a
// line taller than the body from the cursor's.
const tab = p.settings.tab;
if (pane.file == null) {
const above: i32 = switch (a.role) {
.view_top => 0,
.view_center => @divTrunc(@as(i32, pane.rows) - 1, 2),
else => @as(i32, pane.rows) - 1,
};
pane.scrollBy(tab, t.cur_row - (pane.scroll() + above));
} else {
const body: i64 = File.shownRows(tab, pane);
const line: usize = @intCast(@max(0, t.cur_row));
const row = File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col)));
const at: File.Top = .{ .line = line, .row = if (a.role == .view_top and row < body) 0 else row };
File.setTop(pane, File.walkRows(tab, pane, at, switch (a.role) {
.view_top => 0,
.view_center => -@divTrunc(body - 1, 2),
else => -(body - 1),
}).to);
}
pane.ensureCursorVisible(tab);
},
// helix align_view_middle: the cursor's column to the middle of an
// unwrapped view
.view_middle => if (t.what == .body) {
panes.File.geometry(p.settings.tab, pane);
if (pane.body_wrapped) return;
const line = modal.lineAtOffset(text, cur);
const slice = text[modal.lineStartOffset(text, line)..modal.lineEndOffset(text, line)];
const w: usize = @intCast(@max(1, @as(i32, pane.cols) - @as(i32, panes.File.gutterWidth(pane))));
const col = panes.File.rawDisplayCol(p.settings.tab, slice, @intCast(@max(0, t.cur_col)));
pane.hscroll = @intCast(panes.File.rawAtDisplay(p.settings.tab, slice, col -| w / 2));
},
.view_scroll_down => if (t.what == .body) return t.scrollViewMove(p.settings.tab, text, range, 1),
.view_scroll_up => if (t.what == .body) return t.scrollViewMove(p.settings.tab, text, range, -1),
// The next and the previous of the changes this view shows (jj.zig).
.goto_change => if (@import("jj.zig").nextChange(p, pane, @intCast(@max(0, t.cur_row)), a.forward, std.math.maxInt(usize))) |line|
return pointMove(p.settings.tab, t, text, range, modal.lineStartOffset(text, line)),
.goto_diagnostic, .goto_diagnostic_end => {
// Once a Diagnostics query fed them, the diagnostics are this
// text's places: ]d and [d step them as n and N do, ]D and [D
// go to the last and the first. Until then, asked for.
const set = &pane.places;
const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid|
(if (p.panes[qid].?.query) |q| q.source == .diagnostics else false)
else
false;
if (!fed) return p.lspRequest(v.active, .diagnostics, "");
if (a.role == .goto_diagnostic) return set.step(p, pane, a.forward, 1, false);
if (set.hits.items.len == 0) return;
set.goTo(p.settings.tab, pane, if (a.forward) set.hits.items.len - 1 else 0, false);
},
// These four move exactly one viewport unit, whatever the count.
.half_page_down => return halfPageMove(p.settings.tab, t, text, range, true),
.half_page_up => return halfPageMove(p.settings.tab, t, text, range, false),
.page_down => return t.scrollViewMove(p.settings.tab, text, range, @as(i32, pane.rows)),
.page_up => return t.scrollViewMove(p.settings.tab, text, range, -@as(i32, pane.rows)),
// s, S and | answer for the text they are pressed in; `/` searches
// the body wherever it is pressed, as acme's Look from a tag does.
inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| return startSelRegex(p, pane, t, @field(modal.Normal.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len])),
// Language shortcuts run the same builtins as tags and leader commands.
.goto_definition => return exec.runBuiltin(p, .Def, v.active, "", null),
.goto_references => return exec.runBuiltin(p, .Refs, v.active, "", null),
.goto_callstack => return exec.runBuiltin(p, .Callstack, v.active, "", null),
.goto_declaration => return p.lspRequest(v.active, .declaration, ""),
.goto_type_definition => return p.lspRequest(v.active, .type_definition, ""),
.goto_implementation => return p.lspRequest(v.active, .implementation, ""),
.format => return p.lspRequest(v.active, .format, ""),
.leader => if (p.macro.replaying == 0) {
v.prefix = .leader;
v.leader_n = 0;
},
// `:` is the one key a tag and a body do not share: it moves the
// keyboard between them.
.command_line => switch (t.what) {
.tag => pane.focus = .body,
.column, .workspace => tagline.exitHeader(p),
.body, .input => tagline.enterTag(p, pane),
},
inline .pipe_selection, .pipe_selection_to, .insert_output, .append_output, .keep_pipe => |role| {
const how: modal.Normal.PipeBehavior = switch (role) {
.pipe_selection => .replace,
.pipe_selection_to => .ignore,
.insert_output => .insert,
.append_output => .append,
else => .keep,
};
// A body's in its tag (Prompt.zig), else on the notice band.
if (t.what == .body) return Prompt.open(p, pane, Prompt.ofBehavior(how));
return panes.startPrompt(p, pane, t, .{ .pipe = how });
},
// `/` and `?` in a file's text search it in its tag (Prompt.zig),
// Alt-Enter keeping the places as its query pane's rows (Query.zig);
// a terminal's still asks on the notice band.
.search, .search_back => if (pane.file != null and t.what == .body)
return Prompt.open(p, pane, if (a.role == .search) .search else .search_back)
else
return panes.startPrompt(p, pane, &pane.body, .{ .search = config.search_marker }),
// In a file's text, n and N step its places while they answer for
// the register (Places.answersN); else helix's search of the register.
// A kind's pane walks its `/`'s +Search (look.zig runSearch): the
// places the rows hold, never the disk (a motion).
.search_next, .search_prev => if (t.what == .body and pane.addon != null)
return look.lookWalk(p, if (a.role == .search_next) 1 else -1, false)
else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) {
// The pane's search word says where it went (Prompt.zig).
const was = pane.places.current;
pane.places.step(p, pane, a.role == .search_next, a.count, t.select);
return Prompt.stepped(p, v.active, a.role == .search_next, was);
} else if (t.what == .body and panes.Pick.walkList(p, v.active, a.role == .search_next))
return
else
return searchStep(p.editor(), t, text, a.role == .search_next, a.count),
.goto_word => return startJump(p, pane, t),
.macro_record => {
const m = &p.macro;
if (m.recording == 0) {
m.recording = if (v.register != 0) v.register else '@';
m.recorded.clearRetainingCapacity();
return;
}
// the keys of this command (a count, `"<reg>`, the `Q`) are not
// the macro's
m.recorded.shrinkRetainingCapacity(m.recorded.items.len -| (m.command.items.len + 1));
const keys = try Macro.encode(p.gpa, m.recorded.items);
defer p.gpa.free(keys);
try p.registers.put(p.gpa, m.recording, keys, 0, 1, true);
m.recording = 0;
},
.macro_replay => {
const name: u21 = if (v.register != 0) v.register else '@';
const notation = p.registers.value(name, 0) orelse return;
const keys = try Macro.decode(p.scratch.allocator(), notation);
v.register = 0;
for (0..a.count) |_| keyboard.replayKeys(p, keys);
},
.repeat_insert => {
const m = &p.macro;
if (m.last_insert.items.len == 0 or m.repeating) return;
if (m.inserting) return; // the session is still open
const keys = try p.scratch.allocator().dupe(Macro.Stored, m.last_insert.items);
m.repeating = true;
defer m.repeating = false;
// helix repeat_last_insert: the command once, what was typed
// count times, and out of insert mode the way it was left
const typed = @min(m.typed_from, keys.len);
keyboard.replayKeys(p, keys[0..typed]);
if (keys.len == typed) return;
for (0..a.count) |_| keyboard.replayKeys(p, keys[typed .. keys.len - 1]);
keyboard.replayKeys(p, keys[keys.len - 1 ..]);
},
else => unreachable, // the text's (textAction)
}
}
test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const long = &@as([400]u8, @splat('a'));
const pane = try p.setTestFile(long ++ "\nsecond\n");
p.settings.wrap = true;
const width = panes.File.wrapWidth(pane, true);
try std.testing.expect(width > 4 and long.len > width * 3);
// gj holds the column INSIDE the row and lands on the next break; the line
// is one line the whole way down, which is the whole point.
pane.body.cur_row = 0;
pane.body.cur_col = 3;
pane.body.sticky_col = -1;
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col);
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.body.cur_col);
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col);
// A count is counted in rows, not lines.
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.body.cur_col);
// Plain j/k are untouched: one FILE line each, whatever the body drew.
pane.body.cur_col = 3;
pane.body.sticky_col = -1;
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
// The last row of a line steps into the next line's first row, and the
// first row steps back onto the previous line's LAST row.
pane.body.cur_row = 0;
pane.body.cur_col = @intCast(long.len - 1);
pane.body.sticky_col = -1;
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
pane.body.cur_col = 0;
pane.body.sticky_col = -1;
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
try std.testing.expect(pane.body.cur_col >= @as(i32, @intCast(long.len - long.len % width)));
// Wrap OFF: a line is one visual row, so gj/gk ARE j/k again.
p.settings.wrap = false;
pane.body.cur_row = 0;
pane.body.cur_col = 3;
pane.body.sticky_col = -1;
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
}
/// 10 short lines, line 10 of 200 numbered words (17 rows or more at 60
/// columns), 40 short lines after it; the view's top four rows into line
/// 10, the cursor on a row the body shows.
fn wrappedView(p: *Pardes) !*Pane {
p.settings.wrap = true;
var text: std.ArrayList(u8) = .empty;
defer text.deinit(p.gpa);
for (0..51) |i| if (i == 10) {
for (0..200) |w| try text.print(p.gpa, "w{d:0>3} ", .{w});
try text.append(p.gpa, '\n');
} else try text.print(p.gpa, "line {d:0>2}\n", .{i});
const pane = try p.setTestFile(text.items);
File.setTop(pane, .{ .line = 10, .row = 4 });
p.sync();
const at = pane.wrapAt(p.settings.tab, pane.context_rows + 6);
pane.body.cur_row = at.line;
pane.body.cur_col = at.at;
return pane;
}
test "gt and gb go to the row scroll_off rows in from the body's top and from its bottom, a wrapped line's later row as any, the cursor on its first byte; the view stays" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 });
defer p.deinit();
const tab = p.settings.tab;
const pane = try wrappedView(p);
const top = File.top(tab, pane);
try std.testing.expectEqual(@as(u32, 4), top.row);
for ("tb") |k| {
p.update(.{ .key = .{ .cp = 'g', .text = "g" } });
p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
try std.testing.expectEqual(top, File.top(tab, pane));
const row: i32 = if (k == 't') config.scroll_off else File.shownRows(tab, pane) - 1 - config.scroll_off;
const want = pane.wrapAt(tab, pane.context_rows + row);
try std.testing.expectEqual(want.line, pane.body.cur_row);
try std.testing.expectEqual(want.at, pane.body.cur_col);
}
}
test "gt after a step that moved the view off the place its geometry was made for: the row scroll_off in from the body's top under the context rows the view has now, as a core loaded from the session goes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n");
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/test.zig");
if (!File.supportsContext(pane)) return error.SkipZigTest;
pane.file.?.tree_context = true;
// The view inside the function, its two headers held over the body,
// drawn.
File.setTop(pane, .{ .line = 3 });
p.sync();
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
_ = try p.render(arena.allocator());
try std.testing.expectEqual(@as(u16, 2), pane.context_rows);
// Two notches up: the top on the function's header, one header held
// (the geometry the second notch read was the one before it).
const rect = p.view().rects[0];
for (0..2) |_| p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } });
try std.testing.expectEqual(@as(usize, 1), pane.file.?.scroll);
const bytes = try pardes.dump.dumpBytes(p);
defer gpa.free(bytes);
const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, bytes, null);
defer loaded.deinit();
for ([_]*Pardes{ p, loaded }) |core| for ("gt") |k| core.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
try std.testing.expectEqual(loaded.panes[0].?.body.cur_row, pane.body.cur_row);
try std.testing.expectEqual(@as(u16, 1), pane.context_rows);
try std.testing.expectEqual(pane.wrapAt(p.settings.tab, 1 + config.scroll_off).line, pane.body.cur_row);
}
test "gw labels the words the body shows and no others: none on a wrapped line's rows above the view's top" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 });
defer p.deinit();
const tab = p.settings.tab;
const pane = try wrappedView(p);
p.update(.{ .key = .{ .cp = 'g', .text = "g" } });
p.update(.{ .key = .{ .cp = 'w', .text = "w" } });
try std.testing.expect(pane.jump.items.len > 20);
const f = &pane.file.?;
const shown = File.shownRows(tab, pane);
// Rows with a label: the body's first and its last among them.
var labelled: [2]bool = .{ false, false };
for (pane.jump.items) |r| {
const at = @min(r.anchor, r.head);
const line = std.mem.count(u8, f.content[0..at], "\n");
const col = at - File.lineStart(p.gpa, f, line);
// The row that shows its first byte is in the body, at or after
// that row's start (no row above the top).
const row = pane.wrapRow(tab, @intCast(line), @intCast(col));
try std.testing.expect(row.row >= pane.context_rows and row.row < pane.context_rows + shown);
try std.testing.expect(col >= row.at);
if (row.row == pane.context_rows) labelled[0] = true;
if (row.row == pane.context_rows + shown - 1) labelled[1] = true;
}
try std.testing.expectEqual([2]bool{ true, true }, labelled);
}
test "flat text movement and selection replay need no scratch rows" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const row_text = "one (two) ฮป\r\n";
const text = try gpa.alloc(u8, 4096 * row_text.len);
defer gpa.free(text);
for (0..4096) |row| @memcpy(text[row * row_text.len ..][0..row_text.len], row_text);
const pane = try p.setTestFile(text);
_ = try panes.File.lineIndex(gpa, &pane.file.?);
var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
p.scratch.deinit();
p.scratch = .init(denied.allocator());
pane.body.cur_row = 4094;
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'j' });
try std.testing.expectEqual(@as(i32, 4095), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'h' });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' });
try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col);
pane.body.vsel.active = false;
pane.body.cur_row = 1024;
pane.body.cur_col = 0;
pane.body.nsel = 1;
_ = pane.body.reserveSels();
pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 };
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' });
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'j' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expectEqual(@as(i32, 1025), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 3073), pane.body.sels[0].row);
try std.testing.expectEqual(@as(i32, 1), pane.body.sels[0].col);
try std.testing.expect(!denied.has_induced_failure);
try std.testing.expectEqual(@as(usize, 0), p.scratch.queryCapacity());
pane.body.nsel = 0;
pane.body.cur_col = 4;
try std.testing.expectError(error.OutOfMemory, executeNormalAction(p, &pane.body, .{ .role = .match_prefix }));
try std.testing.expect(denied.has_induced_failure);
try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
denied.fail_index = std.math.maxInt(usize);
try executeNormalAction(p, &pane.body, .{ .role = .match_prefix });
try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col);
}
test "s and S search a multi-line selection as addr does: ^ and $ per line, . within one" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const text = "alpha x\nbeta alpha\nalphabet\n";
const pane = try p.setTestFile(text);
const Case = struct { pat: []const u8, mode: modal.Normal.RegexMode, want: []const [2]usize };
for ([_]Case{
// ^ at each line's start, not only the selection's
.{ .pat = "^alpha", .mode = .select, .want = &.{ .{ 0, 5 }, .{ 19, 24 } } },
// $ at each line's end
.{ .pat = "alpha$", .mode = .select, .want = &.{.{ 13, 18 }} },
// . stops at the newline: one selection per line, not one for all
.{ .pat = "a.*", .mode = .select, .want = &.{ .{ 0, 7 }, .{ 11, 18 }, .{ 19, 27 } } },
// S splits on a line's end
.{ .pat = "$", .mode = .split, .want = &.{ .{ 0, 7 }, .{ 7, 18 }, .{ 18, 27 }, .{ 27, 28 } } },
}) |c| {
pane.sel_snap[0] = .{ .anchor = 0, .head = text.len };
pane.nsel_snap = 1;
_ = applySelRegex(p, pane, &pane.body, c.pat, c.mode);
var out: [Text.max_selections]modal.Selection = undefined;
const got = pane.body.ranges(text, 0, &out);
try std.testing.expectEqual(c.want.len, got.n);
for (c.want, out[0..got.n]) |w, r| {
try std.testing.expectEqual(w[0], @min(r.anchor, r.head));
try std.testing.expectEqual(w[1], @max(r.anchor, r.head));
}
}
}
test "tree-sitter selection keys do in a JSON file what hx 25.07.1 does" {
if (!syntax.supportsPath("a.json")) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const text = "{\"a\": [1, 2, 3], \"b\": true}\n";
// each checked against the installed hx through a pty: the keys, then
// the text it saved
const Case = struct { keys: []const u8, want: []const u8 };
for ([_]Case{
.{ .keys = "10l\x1bo" ++ "d", .want = "{\"a\": , \"b\": true}\n" },
.{ .keys = "10l\x1bo\x1bod", .want = "{, \"b\": true}\n" },
.{ .keys = "10l\x1bo\x1bo\x1bod", .want = "\n" },
.{ .keys = "10l\x1bo\x1bIix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" },
.{ .keys = "10l\x1bo\x1bo\x1b>d", .want = "{\"a\": [1, 2, 3] \"b\": true}\n" },
.{ .keys = "10l\x1bpd", .want = "{\"a\": [1 2, 3], \"b\": true}\n" },
.{ .keys = "10l\x1baix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" },
.{ .keys = "10l\x1bo\x1bo\x1bid", .want = "{\"a\": , \"b\": true}\n" },
.{ .keys = "6lx\x1bid", .want = "\n" },
.{ .keys = "10l\x1beiX\x1b", .want = "{\"a\": [1, 2X, 3], \"b\": true}\n" },
.{ .keys = "10l\x1bb\x1bbiX\x1b", .want = "{X\"a\": [1, 2, 3], \"b\": true}\n" },
// insert Tab after text leaves the node (smart tab)
.{ .keys = "8li\tX\x1b", .want = "{\"a\": [1, 2, 3]X, \"b\": true}\n" },
}) |c| {
const pane = try p.setTestFile(text);
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/test.json");
// ESC before a key is Alt on it; a lone ESC is Esc; `>` is Alt-right
var i: usize = 0;
while (i < c.keys.len) : (i += 1) {
const ch = c.keys[i];
if (ch == 0x1b and i + 1 < c.keys.len) {
i += 1;
const k = c.keys[i];
p.update(.{ .key = if (k == '>') .{ .cp = Key.right, .alt = true } else .{ .cp = k, .alt = true } });
} else if (ch == 0x1b) {
p.update(.{ .key = .{ .cp = Key.escape } });
} else if (ch == '\t') {
p.update(.{ .key = .{ .cp = Key.tab } });
} else p.update(.{ .key = .{ .cp = ch, .text = c.keys[i..][0..1] } });
while (p.nextEffect()) |_| {}
}
std.testing.expectEqualStrings(c.want, pane.file.?.content) catch |err| {
std.debug.print("keys {s}\n", .{c.keys});
return err;
};
}
}
test "one cursor holds no room for other ranges; a second range makes it and one again gives it back" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("alpha beta\nalpha beta\n");
for ("wxe%;gg") |cp| _ = handleNormal(p.editor(), &pane.body, .{ .cp = cp });
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expect(pane.body.sels.len > 0);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); // replayed at both, still two
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = ',' });
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
_ = handleNormal(p.editor(), &pane.body, .{ .cp = ';' });
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'x' }); // x at both: still two lines
_ = handleNormal(p.editor(), &pane.body, .{ .cp = '_', .alt = true }); // merged to one
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
}
test "C and Alt-C on a long text of short lines walk its lines once, not each try from its start" {
// Work, not time: the instructions this thread runs, as pardes-perf's
// gate counts them. Each try walking from the text's start made C here
// cost billions (the bytes soak's hang, at row 41,775 of a flood).
if (@import("builtin").os.tag != .linux) return error.SkipZigTest;
const linux = std.os.linux;
var attr: linux.perf_event_attr = .{
.type = .HARDWARE,
.config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS),
.flags = .{ .exclude_kernel = true, .exclude_hv = true },
};
const opened = linux.perf_event_open(&attr, 0, -1, -1, linux.PERF.FLAG.FD_CLOEXEC);
if (linux.errno(opened) != .SUCCESS) return error.SkipZigTest; // no counter here (perf_event_paranoid 3)
const fd: linux.fd_t = @intCast(opened);
defer _ = linux.close(fd);
const Count = struct {
fn now(f: linux.fd_t) u64 {
var n: u64 = 0;
_ = linux.read(f, std.mem.asBytes(&n), @sizeOf(u64));
return n;
}
};
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
// only the first line and the last reach column 3
const lines = 50_000;
const text = try gpa.alloc(u8, 2 * 5 + (lines - 2) * 2);
defer gpa.free(text);
@memcpy(text[0..5], "abcd\n");
for (0..lines - 2) |k| @memcpy(text[5 + 2 * k ..][0..2], "x\n");
@memcpy(text[text.len - 5 ..], "abcd\n");
const pane = try p.setTestFile(text);
const body = &pane.body;
// C walked once costs 194 million here in Debug, about 4,000 a line;
// walked from the start at every try it cost 306 billion
const bound = 10_000 * lines;
for ("lll") |cp| _ = handleNormal(p.editor(), body, .{ .cp = cp });
var rs: [Text.max_selections]modal.Selection = undefined;
for ([_]Key{ .{ .cp = 'C' }, .{ .cp = 'C', .alt = true } }) |key| {
const t0 = Count.now(fd);
_ = handleNormal(p.editor(), body, key);
const cost = Count.now(fd) - t0;
const got = body.ranges(text, 0, &rs);
try std.testing.expectEqual(2, got.n);
try std.testing.expectEqual(3, @min(rs[0].anchor, rs[0].head));
try std.testing.expectEqual(text.len - 2, @min(rs[1].anchor, rs[1].head));
std.testing.expect(cost < bound) catch |err| {
std.debug.print("{u} (alt {}): {d} instructions, the bound {d}\n", .{ key.cp, key.alt, cost, bound });
return err;
};
// the new cursor alone, for the twin to walk back from
_ = handleNormal(p.editor(), body, .{ .cp = ',' });
}
}
test "cursors that land on one place are one: a key typed there is typed once, as helix merges them" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("ab\ncd\n");
// A cursor below, then both up: the second lands on the first.
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
_ = handleNormal(p.editor(), &pane.body, .{ .cp = 'k' });
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
p.update(.{ .key = .{ .cp = 'i', .text = "i" } });
p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
try std.testing.expectEqualStrings("xab\ncd\n", pane.file.?.content);
}
test "r and Delete take whole graphemes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("A" ++ "e\u{301}" ++ "๐ฉ๐ฝ\u{200d}๐" ++ "๐ง๐ท" ++ "็" ++ "Z\n");
// รฉ, the astronaut and the flag: three graphemes, three ็
for ("lv2lr") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c });
_ = handleNormal(p.editor(), &pane.body, .{ .cp = '็' });
try std.testing.expectEqualStrings("A็็็็Z\n", pane.file.?.content);
for ("u0li") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c });
p.update(.{ .key = .{ .cp = Key.delete } });
try std.testing.expectEqualStrings("A" ++ "๐ฉ๐ฝ\u{200d}๐" ++ "๐ง๐ท" ++ "็" ++ "Z\n", pane.file.?.content);
}
test "tree-sitter textobject keys do in Python, JSON and Zig what hx 25.07.1 does" {
if (!syntax.supportsPath("a.py") or !syntax.supportsPath("a.json") or !syntax.supportsPath("a.zig")) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
// each checked against the installed hx through a pty: the keys, then
// the text it saved
const Case = struct { path: []const u8, text: []const u8, keys: []const u8, want: []const u8 };
for ([_]Case{
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]fd", .want = "def alpha(a, b):\n return a + b\n\n\n\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]f]fd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "2]fd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "Gk[fd", .want = "ef alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "jmifd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "jmafd", .want = "\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "10lmiad", .want = "def alpha(, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "10lmaad", .want = "def alpha( b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]Td", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]cd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n \n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "v]fd", .want = "\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]td", .want = "ef alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]ad", .want = "def alpha( b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" },
.{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "]ed", .want = "{, \"b\": [1, 2]}\n" },
.{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "]e]ed", .want = "{\"a\": 1, }\n" },
.{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "8lmaed", .want = "{\"a\": 1,\"b\": [1, 2]}\n" },
// Zig: the query is helix's, ported to pardes's zig grammar. No case
// walks call arguments: the reference helix counts them as
// parameters and the installed 25.07.1's query does not.
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]fd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "5jmifd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 \n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "5jmafd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\n\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "9jmitd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "9jmatd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\n\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]Td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\n\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16jmiTd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" \n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "3j11lmiad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "3j11lmaad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add( b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]cd", .want = "const std = @import(\"std\");\n\n\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "4jmacd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16jf2[ad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, ) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16j[fd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
.{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]t]td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\n\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" },
}) |c| {
const pane = try p.setTestFile(c.text);
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, c.path);
for (c.keys, 0..) |ch, i| {
p.update(.{ .key = .{ .cp = ch, .text = c.keys[i..][0..1] } });
while (p.nextEffect()) |_| {}
}
std.testing.expectEqualStrings(c.want, pane.file.?.content) catch |err| {
std.debug.print("keys {s} on {s}\n", .{ c.keys, c.path });
return err;
};
}
}
test "SearchRegex: a pattern that does not compile leaves nothing allocated" {
// Places compiles with the pane's own allocator, not an arena: a typed
// pattern that is no expression yet must not leak its one branch.
var refused: usize = 0;
for ([_][]const u8{ "(", "[", "*a", "\\", "\\bfoo(" }) |bad| {
if (SearchRegex.compile(std.testing.allocator, bad)) |re| {
std.testing.allocator.free(re.branches);
} else |_| refused += 1;
}
try std.testing.expectEqual(5, refused);
}
|