1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
|
//! Editing a pane's text (acme's text.c): which text a pane edits and how
//! its lines and cursor map to the screen, insert mode, the d/c/y/p edit
//! operations, replace, case, join, indent, comments, numbers, textobjects
//! and surround, undo, yank and paste, and the pointer selections as text.
const pardes = @import("pardes.zig");
const tagline = @import("tagline.zig");
const mouse = @import("mouse.zig");
const normal = @import("normal.zig");
const std = @import("std");
const modal = @import("modal.zig");
const panes = @import("panes.zig");
const body_layer = @import("body_layer.zig");
const config = @import("config.zig");
const pdf_enabled = panes.Pdf.enabled;
const lsp = @import("lsp/lsp.zig");
const syntax = @import("syntax.zig");
const platform = pardes.platform;
const Pane = panes.Pane;
const Text = panes.Text;
const tag_layer = @import("tag_layer.zig");
const TagHit = pardes.TagHit;
const BOX_H = pardes.BOX_H;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
const Mouse = pardes.Mouse;
const Key = pardes.Key;
const hit = pardes.hit;
const sel_slot = pardes.sel_slot;
const Effect = pardes.Effect;
const Pardes = pardes.Pardes;
const Registers = pardes.Registers;
/// Write `text` as this range's value of the register the running command
/// names (`"<reg>`), the default one otherwise. `_` swallows it, and the
/// registers computed from the editor (`#`, `.`, `%`) cannot be written.
/// `+` and `*` are the system clipboard: the value is sent there too.
pub fn setYank(p: *Pardes, text: []const u8) void {
var name: u21 = if (p.register != 0) p.register else Registers.default;
switch (name) {
'_', '#', '.', '%' => return,
'*' => name = '+',
else => {},
}
const one = !p.multi_on;
p.registers.put(p.gpa, name, text, if (one) 0 else p.multi_index, if (one) 1 else p.multi_count, one or p.multi_first);
if (name == '+' and (one or p.multi_first)) p.emit(.{ .set_clipboard = {} });
}
pub fn setClipboard(p: *Pardes, text: []const u8) void {
const named = p.register;
p.register = '+';
defer p.register = named;
setYank(p, text);
}
/// Value `i` of register `name` as the command at range `i` reads it, the
/// computed registers included: `#` is the range's number from 1, `.` its
/// text, `%` the file's name, `_` nothing. Scratch- or register-owned.
pub fn registerValue(p: *Pardes, t: *Text, name: u21) ?[]const u8 {
const i = if (p.multi_on) p.multi_index else 0;
return switch (name) {
'_' => null,
'#' => std.fmt.allocPrint(p.scratch.allocator(), "{d}", .{i + 1}) catch null,
'.' => selText(p, t),
'%' => if (t.what == .body) if (t.pane()) |pane| (if (pane.file) |f| f.path else null) else null else null,
else => p.registers.value(name, i),
};
}
/// the text of the range under the cursor: the selection, or the cursor's
/// own character
fn selText(p: *Pardes, t: *Text) []const u8 {
if (t.msel.active) return yankRows(p, t, @min(t.msel.r0, t.msel.r1), @max(t.msel.r0, t.msel.r1));
const save = t.vsel;
defer t.vsel = save;
if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false };
return vselText(p, t);
}
/// `p` / `P` / `R` from the register the command names: this range's value
/// of it. The clipboard's is asked of the shell and pasted when it answers,
/// once, at the primary.
pub fn pasteRegister(p: *Pardes, t: *Text, how: enum { after, before, replace }, count: usize) void {
const name: u21 = if (p.register != 0) p.register else Registers.default;
if (name == '+' or name == '*') {
if (!normal.multiOnce(p)) return;
const pane = t.pane() orelse return;
return clipRequest(p, p.paneIdOf(pane) orelse return, switch (how) {
.after => .after,
.before => .before,
.replace => .replace,
});
}
const y = registerValue(p, t, name) orelse return;
switch (how) {
.after => pasteText(p, t, y, false, count),
.before => pasteText(p, t, y, true, count),
.replace => replaceWithText(p, t, y),
}
}
/// Where a `SPC p` / `SPC P` / `SPC R` goes once the shell answers.
pub const ClipRequest = struct {
pane: usize,
serial: u32,
mode: enum { after, before, replace },
};
pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) void {
const pane = p.panes[id] orelse return;
p.clip_pending = .{ .pane = id, .serial = pane.serial, .mode = mode };
p.emit(.read_clipboard);
}
pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void {
if (text.len == 0) return;
if (panes.Terminal.bracketedPaste(pane)) {
p.emitWrite(id, "\x1b[200~");
p.emitWrite(id, text);
p.emitWrite(id, "\x1b[201~");
return;
}
const cp = p.scratch.allocator().dupe(u8, text) catch return;
for (cp) |*ch| {
if (ch.* == '\n') ch.* = '\r';
}
p.emitWrite(id, cp);
}
pub fn applyPaste(p: *Pardes, bytes: []const u8) void {
// A prompt answering for a header takes the paste, as it takes keys.
const asking = if (p.panes[p.active]) |active| active.prompt != .none else false;
if (!asking) if (tagline.focusedHeader(p)) |t| {
p.clip_pending = null;
return pasteInto(p, t, bytes);
};
const req = p.clip_pending;
p.clip_pending = null;
if (bytes.len == 0) return;
const id = if (req) |r| r.pane else p.active;
const pane = p.panes[id] orelse return;
if (req) |r| if (pane.serial != r.serial) return;
p.active = id;
if (pane.prompt != .none and pane.prompt != .del_side and pane.prompt != .repl_choice) {
// an answer is one line: a newline in it would only be submitting it
const line = p.scratch.allocator().alloc(u8, bytes.len) catch return;
var n: usize = 0;
for (bytes) |byte| if (byte != '\n' and byte != '\r') {
line[n] = byte;
n += 1;
};
if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] });
if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode);
return;
}
if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes);
if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes);
switch (if (req) |r| r.mode else .after) {
.after => pasteText(p, &pane.body, bytes, false, 1),
.before => pasteText(p, &pane.body, bytes, true, 1),
.replace => replaceWithText(p, &pane.body, bytes),
}
}
/// A paste into a tag or a header: typed at the caret while it is typed
/// into, after the cursor's cell in normal mode, as a body's paste is.
fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void {
if (bytes.len == 0) return;
const typed: pardes.Key = .{ .cp = bytes[0], .text = bytes };
if (t.what == .tag and t.mode == .insert) if (t.pane()) |pane| if (tagline.typedIntoName(p, pane, typed)) return;
const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel };
var kept_sels: [Text.max_selections - 1]Text.SelRange = undefined;
const kept_n = t.nsel;
@memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]);
t.refused = false;
if (t.mode == .insert) insertKey(p, t, typed) else pasteText(p, t, bytes, false, 1);
if (t.refused) {
t.cur_row, t.cur_col, t.vsel, t.msel = kept;
t.restoreSels(kept_sels[0..kept_n]);
}
}
pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void {
if (comptime pdf_enabled) if (pane.pdf) |pv| {
if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text);
return;
};
// helix's `"+y`: the clipboard register, and only it
const named = p.register;
p.register = '+';
defer p.register = named;
if (pane.body.nsel > 0 and !main_only) {
normal.replaySels(p, &pane.body, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } });
} else {
const others = pane.body.nsel;
pane.body.nsel = 0;
normalYank(p, &pane.body);
pane.body.nsel = others;
}
}
/// tag + '\n' + body: the full selectable pane text, a row to a screen row
/// (the tag's lines first, the ones it shows)
pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 {
const arena = p.scratch.allocator();
const tag = try tagline.tagText(p, arena, pane);
const from = modal.lineStartOffset(tag, pane.tag_top);
const cut = modal.lineStartOffset(tag, pane.tag_top + pane.tag_rows);
const shown = if (cut < tag.len) tag[from .. cut - 1] else tag[from..];
return std.fmt.allocPrint(arena, "{s}\n{s}", .{ shown, try body_layer.bodyText(p, arena, pane) });
}
pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 {
if (row < 0) return "";
if (pane.file != null) return panes.File.sourceLine(pane, row);
const index: usize = @intCast(row);
return if (index < terminal_lines.len) terminal_lines[index] else "";
}
pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void {
var gesture = pane.sel[slot];
if (pane.hasPdf()) return;
if (gesture.state != .done or @min(gesture.r0, gesture.r1) < pane.tag_rows) return;
if (pane.pointerSelection(gesture) != null) return;
pane.clearPointerSelection(slot);
// Refresh the source map before translating the rendered rectangle.
const raw = pane.isTerminal() and pane.body.mode == .tty;
const body = try body_layer.bodyText(p, p.scratch.allocator(), pane);
const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{};
const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows);
const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows;
const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows);
if (first > last) return;
const rows = try p.gpa.alloc(Pane.PointerRow, @intCast(last - first + 1));
errdefer p.gpa.free(rows);
const raw_text = if (raw) try p.gpa.dupe(u8, try selectionText(p, pane, gesture)) else null;
const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0;
for (rows, 0..) |*row, index| {
const visible = first + @as(i32, @intCast(index));
// A stream: only the first row starts where the press was; the
// others start after the line numbers, and all but the last run on.
const cols = sweepCols(gesture, visible + @as(i32, pane.tag_rows)).?;
const left: i32 = if (cols.first) cols.lo else prefix;
const right: i32 = cols.hi orelse std.math.maxInt(i32) / 2;
var source = pane.wrapAt(visible);
if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 };
const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line);
var next = pane.wrapAt(visible + 1);
if (raw) next = .{ .line = source.line + 1, .at = 0 };
const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len;
const start: usize = @intCast(@max(0, source.at));
const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix))));
const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix))));
row.* = .{
.row = source.line,
.lo = lo,
.hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)),
.to_edge = cols.hi == null,
.raw_terminal = raw,
.prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0,
};
const rendered = modal.lineSlice(body, @intCast(visible));
const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1))));
const prefix_start = @min(prefix_end, @as(usize, @intCast(left)));
row.prefix_len = @intCast(prefix_end - prefix_start);
@memcpy(row.prefix[0..row.prefix_len], rendered[prefix_start..prefix_end]);
}
pane.next_pointer_selection += 1;
gesture.source_id = pane.next_pointer_selection;
pane.sel[slot] = gesture;
pane.pointer_selections[slot] = .{ .gesture = gesture, .rows = rows, .raw_text = raw_text };
}
/// block-selected text, newline-joined per row; reads the rendered screen
/// so typed text and shell output select identically. Scratch-owned.
pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 {
const arena = p.scratch.allocator();
if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text);
if (pane.pointerSelection(sl)) |rows| {
const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{};
var total: usize = rows.len -| 1;
for (rows) |row| {
const line = pointerSourceLine(pane, terminal_lines, row.row);
total += row.prefix_len + @min(row.hi, line.len) - @min(row.lo, line.len);
}
const result = try arena.alloc(u8, total);
var at: usize = 0;
for (rows, 0..) |row, index| {
if (index > 0) {
result[at] = '\n';
at += 1;
}
@memcpy(result[at..][0..row.prefix_len], row.prefix[0..row.prefix_len]);
at += row.prefix_len;
const line = pointerSourceLine(pane, terminal_lines, row.row);
const bytes = line[@min(row.lo, line.len)..@min(row.hi, line.len)];
@memcpy(result[at..][0..bytes.len], bytes);
at += bytes.len;
}
return result;
}
const text = try paneText(p, pane);
var out: std.ArrayList(u8) = .empty;
var it = std.mem.splitAny(u8, text, "\n");
var v: i32 = 0;
var first = true;
while (it.next()) |line| : (v += 1) {
const cols = sweepCols(sl, v) orelse continue;
if (!first) try out.append(arena, '\n');
first = false;
// Past the first row a body row starts after its line numbers.
const gutter: i32 = if (pane.file != null and v >= pane.tag_rows) panes.File.gutterWidth(pane) else 0;
const lo: usize = @intCast(if (cols.first) cols.lo else gutter);
const b0 = @min(panes.File.renderedLineByteCol(pane, v, line, lo), line.len);
const b1 = if (cols.hi) |hi|
@max(b0, modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, v, line, @intCast(hi)), line.len)))
else
line.len;
try out.appendSlice(arena, line[b0..b1]);
}
return out.items;
}
/// A sweep's columns on `row`, in its Sel space: acme's stream, not a
/// rectangle (libframe/frselect.c:115-140, frselectpaint): the first row
/// from the press to its end, the rows between whole, the last from its
/// start to the release. `hi` null runs to the end of the row.
pub const SweepCols = struct { lo: i32, hi: ?i32, first: bool };
pub fn sweepCols(sl: Pane.Sel, row: i32) ?SweepCols {
const start, const end = sweepEnds(sl);
if (row < start[0] or row > end[0]) return null;
return .{
.lo = if (row == start[0]) @max(0, start[1]) else 0,
.hi = if (row == end[0]) @max(0, end[1]) else null,
.first = row == start[0],
};
}
/// The sweep's two ends in reading order, each (row, col).
pub fn sweepEnds(sl: Pane.Sel) struct { [2]i32, [2]i32 } {
const fwd = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1);
return if (fwd) .{ .{ sl.r0, sl.c0 }, .{ sl.r1, sl.c1 } } else .{ .{ sl.r1, sl.c1 }, .{ sl.r0, sl.c0 } };
}
pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool {
const fwd = ar < br or (ar == br and ac <= bc);
const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc };
const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac };
return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec));
}
/// the active modal selection as text (v range or x lines), if any
pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 {
if (comptime pdf_enabled) if (p.native_images) if (pane.pdf) |pv|
if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text;
if (pane.body.vsel.active) return vselText(p, &pane.body);
if (!pane.body.msel.active) return null;
return yankRows(p, &pane.body, @min(pane.body.msel.r0, pane.body.msel.r1), @max(pane.body.msel.r0, pane.body.msel.r1));
}
pub fn exitInsert(p: *Pardes, t: *Text) void {
t.mode = .normal;
t.reg_wait = false;
t.msel.active = false;
t.normal.clear();
if (!t.restore_cursor) return;
t.restore_cursor = false;
// helix enter_normal_mode: every range, from its start to the char
// before its end when it points forward, else to its end
const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active;
const text = flatSurface(p, t) catch return;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &rs);
for (rs[0..got.n]) |*r| {
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
const head = if (r.head > r.anchor) @max(from, modal.prevGrapheme(text, to)) else to;
r.* = .{ .anchor = from, .head = head };
}
t.setRanges(text, rs[0..got.n], &.{}, got.pri, expl);
}
pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 {
const arena = p.scratch.allocator();
if (t.what != .body) {
const text = try flatSurface(p, t);
const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1);
var it = std.mem.splitScalar(u8, text, '\n');
for (lines) |*line| line.* = it.next().?;
return lines;
}
const pane = t.pane() orelse return &.{};
if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f);
if (pane.hasPdf()) {
if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena);
unreachable;
}
return panes.Terminal.cursorLines(p, pane);
}
pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 {
if (t.what == .body) if (t.pane()) |pane| if (pane.file != null)
return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col);
const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col);
const local = row;
if (local < 0 or @as(usize, @intCast(local)) >= lines.len)
return @max(0, from_raw + display_col);
return @intCast(panes.File.byteAtDisplayFrom(
lines[@intCast(local)],
@intCast(@max(0, from_raw)),
@intCast(@max(0, display_col)),
));
}
/// Freeze the live terminal cursor into the modal coordinate space. The
/// emulator reports screen cells; editing state stores UTF-8 byte offsets.
pub fn pinPaneCursor(p: *Pardes, t: *Text) void {
if (t.cur_pinned) return;
// Only a body has a live cursor of someone else's to freeze.
if (t.what != .body) {
t.cur_pinned = true;
return;
}
const pane = t.pane() orelse return;
pane.pinCursor();
if (pane.file == null and !pane.hasPdf())
t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col);
}
pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 {
switch (t.what) {
.body => {},
// the tag as it is shown: the keyboard reaches its prefix too
.tag => return if (t.pane()) |pane| try tagline.tagText(p, p.scratch.allocator(), pane) else "",
.input => return t.own orelse "",
.column, .workspace => return t.own orelse tagline.headerDefault(p, t.what),
}
const pane = t.pane() orelse return "";
if (pane.file) |f| return f.content;
if (pane.hasPdf()) {
if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa);
unreachable;
}
const lines = try panes.Terminal.cursorLines(p, pane);
return panes.Terminal.flatSurface(p, pane, lines);
}
pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize {
if (t.what != .body) return 0;
const pane = t.pane() orelse return 0;
if (pane.file == null) return 0;
return panes.File.wrapWidth(pane, p.settings.wrap);
}
/// Route shared edit operations to the characters `t` edits: its own, or
/// for a body its file's content or its terminal's overlay.
fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText {
// A tag or header nobody has changed shows its default; the first edit
// makes that default its own text.
if (t.what == .tag) {
const pane = t.pane() orelse return null;
return .{ .text = tagline.tagText(p, p.scratch.allocator(), pane) catch return null, .row0 = 0 };
}
if (t.what != .body and t.what != .input and t.own == null)
t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null;
if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 };
const pane = t.pane() orelse return null;
if (pane.file) |f| return .{ .text = f.content, .row0 = 0 };
if (pane.image != null or pane.hasPdf()) return null;
return panes.Terminal.editText(p, pane, lo, hi, col);
}
fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText {
const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null;
const r: usize = @intCast(@max(0, b.hi_row - eb.row0));
if (r + 1 < modal.lineCount(eb.text)) return eb;
if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb;
return editText(p, t, b.lo_row, b.hi_row + 1, -1);
}
/// install a rewritten editable text (frees the old one)
pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void {
if (t.what == .tag) {
// A tag is edited as it is shown, but only what follows its
// prefix is its own: an edit that changed the prefix is refused.
// The shown text stays alive until the next such edit, since every
// caller reads the new text back, as a body's is kept.
defer retireEditText(p, new);
const pane = t.pane() orelse return;
const prefix = tagline.pathPrefix(p.scratch.allocator(), pane) catch return;
if (!std.mem.startsWith(u8, new, prefix)) {
t.refused = true;
return;
}
const tail = p.gpa.dupe(u8, new[prefix.len..]) catch return;
if (t.own) |old| p.gpa.free(old);
t.own = tail;
return;
}
if (t.what != .body) {
if (t.own) |old| p.gpa.free(old);
t.own = new;
return;
}
const pane = t.pane() orelse return retireEditText(p, new);
// what changed ended where the texts agree again from their ends
const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 };
const front = std.mem.indexOfDiff(u8, old, new) orelse @min(old.len, new.len);
var back: usize = 0;
while (back < @min(old.len, new.len) - front and old[old.len - 1 - back] == new[new.len - 1 - back]) back += 1;
const end = modal.positionAt(new, new.len - back);
t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) };
if (pane.file) |*f| return panes.File.setContent(p, f, new);
panes.Terminal.setEditText(p, pane, new);
}
/// Take a text an edit made that nothing keeps, holding it until the next
/// one: the edit's caller still reads it to place the cursor.
pub fn retireEditText(p: *Pardes, new: []u8) void {
if (p.retired_edit) |old| p.gpa.free(old);
p.retired_edit = new;
}
pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_above };
/// Files insert only inside existing rows and at grapheme boundaries.
/// Terminal overlays can materialize virtual rows/columns, so keep those.
pub fn clampFileCursor(t: *Text) bool {
if (t.what != .body) return false;
const pane = t.pane() orelse return false;
const file = if (pane.file) |*file| file else return false;
const old_row = t.cur_row;
const old_col = t.cur_col;
const last = panes.File.nlines(pane.gpa, file) -| 1;
t.cur_row = @intCast(@min(last, @as(usize, @intCast(@max(0, t.cur_row)))));
const line = panes.File.sourceLine(pane, t.cur_row);
t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col))))));
return old_row != t.cur_row or old_col != t.cur_col;
}
pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void {
if (t.what == .body) if (t.pane()) |pane| if (pane.hasPdf()) return;
pinPaneCursor(p, t);
_ = clampFileCursor(t);
// snapshot once per insert session (WITH the pre-insert selection) so
// `u` undoes the whole session and restores what was selected
pushUndo(p, t);
t.select = false;
t.restore_cursor = false;
t.sticky_col = -1;
const text = flatSurface(p, t) catch {
t.mode = .insert;
t.msel.active = false;
t.vsel.active = false;
t.normal.clear();
return;
};
const cur = t.toModalCursor();
const line = panes.File.textLine(t, text, cur.row);
const b: ?Bounds = if (t.vsel.active) vselBounds(t) else null;
switch (where) {
.at => {
if (b) |bb| {
t.cur_row = bb.lo_row;
t.cur_col = bb.lo_col;
t.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false };
t.cur_pinned = true;
}
},
.append => {
const lo_row = if (b) |bb| bb.lo_row else t.cur_row;
const lo_col = if (b) |bb| bb.lo_col else t.cur_col;
const hi_row = if (b) |bb| bb.hi_row else t.cur_row;
const hi_col = if (b) |bb| bb.hi_col else t.cur_col;
t.restore_cursor = true;
const hi = modal.offsetAt(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) });
const gap = modal.nextGrapheme(text, hi);
// helix append_mode: a range that reaches the end of the text
// gets a newline after it to append before (a terminal's text
// is not the editor's to grow)
const terminal = t.what == .body and if (t.pane()) |pane| pane.isTerminal() else false;
var now = text;
if (hi < text.len and gap >= text.len and !terminal) {
const grown = std.mem.concat(p.gpa, u8, &.{ text, "\n" }) catch return;
setEditText(p, t, grown);
now = grown; // what setEditText keeps; `text` may be gone
}
const gc = modal.positionAt(now, gap);
t.cur_row = @intCast(gc.row);
t.cur_col = @intCast(gc.col);
// helix append_mode: the range reaches one past its end, which
// is where typing goes; a bare cursor becomes a range too
t.vsel = .{ .active = true, .row = lo_row, .col = lo_col, .explicit = false };
t.cur_pinned = true;
},
.line_start => {
t.fromModalCursor(.{ .row = cur.row, .col = modal.firstNonWs(line) });
t.vsel.active = false;
},
.line_end => {
t.cur_col = @intCast(line.len);
t.cur_pinned = true;
t.vsel.active = false;
},
.open_below, .open_above => {
t.vsel.active = false;
const below = where == .open_below;
const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else t.cur_row;
const eb = editText(p, t, abs, abs, -1) orelse return;
const row: usize = @intCast(@max(0, abs - eb.row0));
const ind = modal.indentText(modal.lineSlice(eb.text, row));
const arena = p.scratch.allocator();
const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return;
const block = arena.alloc(u8, block_len) catch return;
var block_at: usize = 0;
for (0..cnt) |_| {
if (below) {
block[block_at] = '\n';
block_at += 1;
}
@memcpy(block[block_at..][0..ind.len], ind);
block_at += ind.len;
if (!below) {
block[block_at] = '\n';
block_at += 1;
}
}
const at: modal.Cursor = if (below)
.{ .row = row, .col = modal.lineSlice(eb.text, row).len }
else
.{ .row = row, .col = 0 };
const new = modal.insertAt(p.gpa, eb.text, at, block) catch return;
setEditText(p, t, new);
t.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0;
t.cur_col = @intCast(ind.len);
t.cur_pinned = true;
if (cnt > 1 and !p.multi_on) opened: {
const t2 = flatSurface(p, t) catch break :opened;
var rs: [Text.max_selections]modal.Selection = undefined;
const m = @min(cnt, Text.max_selections);
for (0..m) |k| {
const o = modal.offsetAt(t2, .{ .row = @intCast(@max(0, t.cur_row) + @as(i32, @intCast(k))), .col = ind.len });
rs[k] = .{ .anchor = o, .head = o };
}
t.setRanges(t2, rs[0..m], &.{}, 0, false);
}
},
}
t.mode = .insert;
t.msel.active = false;
t.normal.clear();
t.show();
}
pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void {
if (t.nsel == 0) return insertKey(p, t, key);
normal.replaySels(p, t, .{ .insert = key });
}
pub fn insertKey(p: *Pardes, t: *Text, key: Key) void {
// helix aliases: normalize to the base key and re-dispatch
if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace });
if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter });
if (hit(key, config.insert_delete_alias)) return insertKey(p, t, .{ .cp = Key.delete });
// Ctrl-r <reg>: type this range's value of the register (helix
// insert_register)
if (t.reg_wait) {
t.reg_wait = false;
if (key.ctrl or key.alt or key.cp >= 0xF0000) return;
const y = registerValue(p, t, key.cp) orelse return;
if (y.len > 0) insertKey(p, t, .{ .cp = key.cp, .text = y });
return;
}
if (hit(key, config.insert_register)) {
t.reg_wait = true;
return;
}
// helix commit_undo_checkpoint: `u` after the session goes back to here
if (hit(key, config.insert_checkpoint)) return pushUndo(p, t);
// helix maps every range through each insert-mode edit (Range::map):
// the edits below work on the bare cursor, and the range the cursor
// heads is carried through what they did to the text afterwards
if (!t.vsel.active) return insertEdit(p, t, key);
const old = flatSurface(p, t) catch return insertEdit(p, t, key);
const r = t.primaryRange(old, 0);
const c = modal.selectionCursor(old, r);
const old_len = old.len;
const explicit = t.vsel.explicit;
t.vsel.active = false;
insertEdit(p, t, key);
if (t.mode != .insert) return;
const new = flatSurface(p, t) catch return;
const c2 = modal.offsetAt(new, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
// every insert-mode edit happens at the cursor: an insertion there, or
// a deletion that ends there (backward) or starts there (forward)
if (key.cp == Key.enter) {
// helix insert_newline: an appending range stretches by what the
// cursor moved, any other slides by it
const d = @as(isize, @intCast(c2)) - @as(isize, @intCast(c));
const head: usize = @intCast(@as(isize, @intCast(r.head)) + d);
const anchor: usize = if (c > r.anchor) r.anchor else @intCast(@as(isize, @intCast(r.anchor)) + d);
return setInsertRange(t, new, .{ .anchor = anchor, .head = head }, explicit);
}
var at: usize = c;
var del: usize = 0;
var ins: usize = 0;
if (new.len > old_len and c2 == c + (new.len - old_len)) {
ins = new.len - old_len;
} else if (new.len < old_len and c2 + (old_len - new.len) == c) {
at = c2;
del = old_len - new.len;
} else if (new.len < old_len and c2 == c) {
del = old_len - new.len;
} else if (new.len != old_len or c2 != c) {
return; // a motion: the range collapses onto the cursor (helix)
}
// helix Assoc: the head sticks after an insertion at it when the range
// points backward or is empty, the anchor when it points forward
const fwd = r.anchor < r.head;
setInsertRange(t, new, .{
.anchor = mapThroughEdit(r.anchor, at, del, ins, !fwd and r.anchor != r.head),
.head = mapThroughEdit(r.head, at, del, ins, fwd),
}, explicit);
}
fn setInsertRange(t: *Text, new: []const u8, mapped: modal.Selection, explicit: bool) void {
const cells = Text.rangeCells(new, mapped);
const cc = modal.positionAt(new, cells.cur);
const ac = modal.positionAt(new, cells.anc);
t.cur_row = @intCast(cc.row);
t.cur_col = @intCast(cc.col);
t.vsel = .{ .active = cells.anc != cells.cur, .row = @intCast(ac.row), .col = @intCast(ac.col), .explicit = explicit };
}
/// A position through one edit at `at` that deleted `del` bytes and put
/// `ins` in (one of the two is 0). A position exactly at an insertion stays
/// before it when `before` is set, else moves past it.
fn mapThroughEdit(pos: usize, at: usize, del: usize, ins: usize, before: bool) usize {
if (pos < at) return pos;
if (del > 0) return if (pos < at + del) at else pos - del;
if (pos == at and before) return pos;
return pos + ins;
}
fn insertEdit(p: *Pardes, t: *Text, key: Key) void {
t.vsel.active = false;
if (!t.cur_pinned) pinPaneCursor(p, t);
_ = clampFileCursor(t);
switch (key.cp) {
Key.left, Key.right, Key.up, Key.down => {
const lines = paneCursorLines(p, t) catch return;
const cur0 = t.toModalCursor();
const nc = switch (key.cp) {
Key.left => modal.charLeft(lines, cur0),
Key.right => modal.charRight(lines, cur0),
Key.up => Text.insertVerticalCursor(lines, cur0, false),
Key.down => Text.insertVerticalCursor(lines, cur0, true),
else => cur0,
};
t.fromModalCursor(nc);
t.show();
return;
},
Key.page_up, Key.page_down => {
// helix binds insert pageup/pagedown to the same view
// scroll + cursor snap as normal mode
const flat = flatSurface(p, t) catch return;
const range = t.primaryRange(flat, 0);
if (t.what != .body) return;
const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows));
t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step);
return;
},
Key.home => {
t.cur_col = 0;
t.cur_pinned = true;
t.show();
return;
},
Key.end => {
// helix insert End: past the last char (goto_line_end_newline)
const text = flatSurface(p, t) catch return;
const cur0 = t.toModalCursor();
t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len);
t.cur_pinned = true;
t.show();
return;
},
else => {},
}
const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return;
const text = eb.text;
const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) };
if (key.text.len > 0 and !key.ctrl and !key.alt) {
const new = modal.insertAt(p.gpa, text, c, key.text) catch return;
setEditText(p, t, new);
for (key.text) |ch| {
if (ch == '\n') {
t.cur_row += 1;
t.cur_col = 0;
} else t.cur_col += 1;
}
t.cur_pinned = true;
t.show();
return;
}
// helix insert-mode kills (word/line; deleteSpan is exclusive)
if (hit(key, config.delete_word_backward)) {
const e2 = if (c.row == 0 and c.col == 0)
(editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col };
const g = modal.offsetAt(e2.text, c2);
if (g == 0) return;
const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start);
const from = @min(wr.anchor, wr.head);
const fc = modal.positionAt(e2.text, from);
const new = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return;
setEditText(p, t, new);
t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0;
t.cur_col = @intCast(fc.col);
t.cur_pinned = true;
t.show();
return;
}
if (hit(key, config.delete_word_forward)) {
const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text))
(editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col };
const g = modal.offsetAt(e2.text, c2);
const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end);
const to = @max(wr.anchor, wr.head);
if (to <= g) return;
const new = modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)) catch return;
setEditText(p, t, new);
t.cur_pinned = true;
return;
}
if (hit(key, config.kill_to_line_start)) {
const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return;
setEditText(p, t, new);
t.cur_col = 0;
t.cur_pinned = true;
t.show();
return;
}
if (hit(key, config.kill_to_line_end)) {
const llen = modal.lineSlice(text, c.row).len;
const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return;
setEditText(p, t, new);
t.cur_pinned = true;
return;
}
switch (key.cp) {
Key.enter => {
const line = modal.lineSlice(text, c.row);
const before = line[0..@min(c.col, line.len)];
// helix insert_newline: after nothing but blanks, the line
// itself moves down, blanks and all; else the blanks before the
// cursor go and the new line takes the indent
if (std.mem.indexOfNone(u8, before, " \t") == null) {
const new = modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n") catch return;
setEditText(p, t, new);
t.cur_row += 1;
t.cur_pinned = true;
t.show();
return;
}
const indent = modal.newlineIndentWidth(line, c.col);
const arena = p.scratch.allocator();
const block = arena.alloc(u8, 1 + indent) catch return;
block[0] = '\n';
@memset(block[1..], ' ');
// a tag keeps its blanks: they part its words, and the last
// may be its read-only prefix's
const kept = if (t.what == .body) std.mem.trimEnd(u8, before, " \t").len else c.col;
const cut = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c) catch return;
defer p.gpa.free(cut);
const new = modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block) catch return;
setEditText(p, t, new);
t.cur_row += 1;
t.cur_col = @intCast(indent);
t.cur_pinned = true;
t.show();
},
Key.backspace => {
if (t.cur_col > 0) {
const line = modal.lineSlice(text, c.row);
var prev = modal.prevGrapheme(line, c.col);
// in leading blanks, back to the previous indent stop (helix
// dedent): a whole unit when on one, else the part past it
const lead = line[0..@min(c.col, line.len)];
if (std.mem.indexOfNone(u8, lead, " \t") == null and prev < line.len and line[prev] != '\t') {
var width: usize = 0;
for (lead) |ch| width += if (ch == '\t') modal.INDENT_W else 1;
var drop = width % modal.INDENT_W;
if (drop == 0) drop = modal.INDENT_W;
prev = c.col;
while (drop > 0 and prev > 0 and line[prev - 1] == ' ') : (drop -= 1) prev -= 1;
}
const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = prev }, c) catch return;
setEditText(p, t, new);
t.cur_col = @intCast(prev);
t.cur_pinned = true;
t.show();
return;
}
// at col 0: eat the newline above (join up) — a terminal grows
// its buffer over the row it is joining with
if (t.cur_row <= 0) return;
const e2 = editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return;
const row: usize = @intCast(@max(0, t.cur_row - e2.row0));
if (row == 0) return;
const prevlen = modal.lineSlice(e2.text, row - 1).len;
const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return;
setEditText(p, t, new);
t.cur_row -= 1;
t.cur_col = @intCast(prevlen);
t.cur_pinned = true;
t.show();
},
Key.delete => {
// delete forward; at line end eat the newline (join), which on
// a terminal means the buffer swallowing the row below
const line = modal.lineSlice(text, c.row);
if (c.col < line.len) {
const new = modal.deleteChar(p.gpa, text, c) catch return;
setEditText(p, t, new);
} else {
const e2 = editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return;
const row: usize = @intCast(@max(0, t.cur_row - e2.row0));
if (row + 1 >= modal.lineCount(e2.text)) return;
const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return;
setEditText(p, t, new);
}
t.cur_pinned = true;
},
Key.tab => {
const ln = modal.lineSlice(text, c.row);
if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: {
if (t.what != .body) break :dot;
const f = (t.pane() orelse break :dot).file orelse break :dot;
if (f.output != null or !lsp.speaks(f.path)) break :dot;
const seq = p.lsp_seq;
p.lspRequest(p.active, .completion, "");
if (p.lsp_seq != seq) return;
}
// helix smart_tab: after text, Tab leaves the syntax node the
// cursor is in; only where the file has a grammar, since the
// reference pins smart tab off, which a file without one agrees
// with. Shift-Tab always types the tab.
const after_text = std.mem.indexOfNone(u8, ln[0..@min(c.col, ln.len)], " \t") != null;
if (!key.shift and after_text and t.what == .body) smart: {
const pane = t.pane() orelse break :smart;
const f = pane.file orelse break :smart;
if (!syntax.supportsPath(f.path)) break :smart;
return normal.nodeSelect(p, pane, t, .parent_end);
}
insertTab(p, t);
},
else => {},
}
}
pub fn insertTab(p: *Pardes, t: *Text) void {
const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return;
const c: modal.Cursor = .{
.row = @intCast(@max(0, t.cur_row - eb.row0)),
.col = @intCast(@max(0, t.cur_col)),
};
const pad = modal.INDENT_W - (c.col % modal.INDENT_W);
const new = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch return;
setEditText(p, t, new);
t.cur_col += @intCast(pad);
t.cur_pinned = true;
t.show();
}
const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 };
/// a range's two cells, normalized to document order
pub fn cellBounds(s: Text.SelRange) Bounds {
if (s.row < s.arow or (s.row == s.arow and s.col < s.acol))
return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol };
return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col };
}
/// the char selection [anchor, cursor] normalized to document order
fn vselBounds(t: *Text) Bounds {
return cellBounds(.{ .row = t.cur_row, .col = t.cur_col, .arow = t.vsel.row, .acol = t.vsel.col });
}
fn vselText(p: *Pardes, t: *Text) []const u8 {
const arena = p.scratch.allocator();
const b = vselBounds(t);
const text = flatSurface(p, t) catch return "";
return modal.rangeText(arena, text, .{ .row = @intCast(@max(0, b.lo_row)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row)), .col = @intCast(@max(0, b.hi_col)) }) catch "";
}
/// join surface rows [r0, r1] (absolute) with '\n'; scratch-owned
fn yankRows(p: *Pardes, t: *Text, r0: i32, r1: i32) []const u8 {
const arena = p.scratch.allocator();
const lines = paneCursorLines(p, t) catch return "";
const rows_count: usize = @intCast(@max(0, r1 - r0 + 1));
var total: usize = rows_count -| 1;
var i = r0;
while (i <= r1) : (i += 1) {
if (i >= 0 and @as(usize, @intCast(i)) < lines.len)
total += lines[@intCast(i)].len;
}
const out = arena.alloc(u8, total) catch return "";
var at: usize = 0;
i = r0;
while (i <= r1) : (i += 1) {
if (i > r0) {
out[at] = '\n';
at += 1;
}
if (i >= 0 and @as(usize, @intCast(i)) < lines.len) {
const line = lines[@intCast(i)];
@memcpy(out[at..][0..line.len], line);
at += line.len;
}
}
return out;
}
pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void {
t.select = false; // helix delete exits select mode
t.sticky_col = -1;
if (t.vsel.active) {
const b = vselBounds(t);
if (yank) setYank(p, vselText(p, t)); // read the range before the move
pushUndo(p, t);
const eb = editTextEol(p, t, b) orelse {
t.vsel.active = false;
return;
};
const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch {
t.vsel.active = false;
return;
};
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
t.cur_row = b.lo_row;
t.cur_col = b.lo_col;
t.clampCursor(d.content, eb.row0);
return;
}
if (t.msel.active) {
const r0 = @min(t.msel.r0, t.msel.r1);
const r1 = @max(t.msel.r0, t.msel.r1);
pushUndo(p, t);
// linewise: a line's newline lives on the row below it
const eb = editText(p, t, r0, r1 + 1, -1) orelse {
t.msel.active = false;
return;
};
const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, r0 - eb.row0)), @intCast(@max(0, r1 - eb.row0))) catch {
t.msel.active = false;
return;
};
setEditText(p, t, d.content);
if (yank) setYank(p, d.deleted);
p.gpa.free(d.deleted);
const n = modal.lineCount(d.content);
t.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0;
t.cur_col = 0;
t.msel.active = false;
t.cur_pinned = true;
t.show();
} else {
pushUndo(p, t);
const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return;
const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) };
if (yank) {
const arena = p.scratch.allocator();
setYank(p, modal.rangeText(arena, eb.text, c, c) catch return);
}
// deleteRange (not deleteChar): the cursor may sit ON a '\n'
// cell, where a delete joins the lines (helix 1-wide selection)
const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return;
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
const llen = modal.lineSlice(d.content, c.row).len;
t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen)));
}
}
pub fn normalYank(p: *Pardes, t: *Text) void {
t.select = false;
if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| {
setYank(p, text);
return;
};
if (t.vsel.active) {
setYank(p, vselText(p, t));
return;
}
if (t.msel.active) {
setYank(p, yankRows(p, t, @min(t.msel.r0, t.msel.r1), @max(t.msel.r0, t.msel.r1)));
} else {
const save = t.vsel;
t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false };
setYank(p, vselText(p, t));
t.vsel = save;
}
}
pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) void {
if (y0.len == 0) return;
pushUndo(p, t);
t.select = false;
t.sticky_col = -1;
const arena = p.scratch.allocator();
var y: []const u8 = y0;
if (count > 1) {
const total = std.math.mul(usize, count, y0.len) catch return;
const buf = arena.alloc(u8, total) catch return;
for (0..count) |i| @memcpy(buf[i * y0.len ..][0..y0.len], y0);
y = buf;
}
const b: Bounds = if (t.vsel.active)
vselBounds(t)
else
.{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col };
const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return;
const row0 = eb.row0;
if (y[y.len - 1] == '\n') {
const block_text = y[0 .. y.len - 1];
const n = @max(1, modal.lineCount(block_text));
var out: []u8 = undefined;
if (before) {
const row: usize = @intCast(@max(0, b.lo_row - row0));
const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return;
out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return;
t.cur_row = @as(i32, @intCast(row + n - 1)) + row0;
} else {
const row: usize = @intCast(@max(0, b.hi_row - row0));
out = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return;
t.cur_row = @as(i32, @intCast(row + n)) + row0;
}
setEditText(p, t, out);
t.vsel = .{ .active = true, .row = t.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false };
// cursor ON the last pasted line's '\n' (helix)
const llen = modal.lineSlice(out, @intCast(@max(0, t.cur_row - row0))).len;
t.cur_col = @intCast(llen);
} else {
const at: modal.Cursor = if (before)
.{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) }
else blk: {
const hrow: usize = @intCast(@max(0, b.hi_row - row0));
const hi_col: usize = @intCast(@max(0, b.hi_col));
const high_line = modal.lineSlice(eb.text, hrow);
if (hi_col >= high_line.len) break :blk .{ .row = hrow + 1, .col = 0 };
const gcol = modal.nextGrapheme(high_line, hi_col);
break :blk .{ .row = hrow, .col = gcol };
};
const out = modal.insertAt(p.gpa, eb.text, at, y) catch return;
setEditText(p, t, out);
t.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false };
const end = modal.advanceBy(at, y);
if (end.col > 0) {
t.cur_row = @as(i32, @intCast(end.row)) + row0;
t.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(out, end.row), end.col));
} else {
t.cur_row = @as(i32, @intCast(end.row -| 1)) + row0;
t.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len);
}
}
t.msel.active = false;
t.cur_pinned = true;
t.show();
}
pub fn normalChange(p: *Pardes, t: *Text) void {
t.select = false;
t.sticky_col = -1;
if (t.vsel.active) {
const b = vselBounds(t);
const eb = editTextEol(p, t, b) orelse return;
const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len;
if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) {
setYank(p, vselText(p, t));
pushUndo(p, t);
const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return;
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
const n = modal.lineCount(d.content);
const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1);
const ind = modal.indentText(modal.lineSlice(d.content, row));
const arena = p.scratch.allocator();
const block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return;
const new = modal.insertAt(p.gpa, d.content, .{ .row = row, .col = 0 }, block) catch return;
setEditText(p, t, new);
t.cur_row = @as(i32, @intCast(row)) + eb.row0;
t.cur_col = @intCast(ind.len);
t.vsel.active = false;
t.msel.active = false;
t.cur_pinned = true;
t.mode = .insert;
t.normal.clear();
t.show();
return;
}
setYank(p, vselText(p, t));
pushUndo(p, t);
const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch {
t.vsel.active = false;
return;
};
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
t.cur_row = b.lo_row;
t.cur_col = b.lo_col;
t.clampCursor(d.content, eb.row0);
t.mode = .insert;
t.normal.clear();
return;
}
if (t.msel.active) {
const r0 = @min(t.msel.r0, t.msel.r1);
const r1 = @max(t.msel.r0, t.msel.r1);
pushUndo(p, t);
const eb = editText(p, t, r0, r1 + 1, -1) orelse return;
const arena = p.scratch.allocator();
const lo: usize = @intCast(@max(0, r0 - eb.row0));
const hi: usize = @intCast(@max(0, r1 - eb.row0));
var total: usize = hi - lo;
for (lo..hi + 1) |r| total += modal.lineSlice(eb.text, r).len;
const buf = arena.alloc(u8, total) catch return;
var at: usize = 0;
for (lo..hi + 1) |r| {
if (r > lo) {
buf[at] = '\n';
at += 1;
}
const line = modal.lineSlice(eb.text, r);
@memcpy(buf[at..][0..line.len], line);
at += line.len;
}
setYank(p, buf);
var body: []u8 = eb.text;
if (hi > lo) {
const d = modal.deleteLines(p.gpa, body, lo + 1, hi) catch {
t.msel.active = false;
return;
};
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
body = d.content;
}
const cl = modal.clearLine(p.gpa, body, lo) catch {
t.msel.active = false;
return;
};
setEditText(p, t, cl);
t.cur_row = r0;
t.cur_col = 0;
t.msel.active = false;
t.cur_pinned = true;
t.mode = .insert;
t.normal.clear();
t.show();
} else {
pushUndo(p, t);
const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return;
const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) };
const arena = p.scratch.allocator();
setYank(p, modal.rangeText(arena, eb.text, c, c) catch return);
const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return;
setEditText(p, t, d.content);
p.gpa.free(d.deleted);
const llen = modal.lineSlice(d.content, c.row).len;
t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen)));
t.mode = .insert;
t.normal.clear();
}
}
fn selRange(t: *Text, content: []const u8, row0: i32) modal.Range {
if (t.vsel.active) {
const b = vselBounds(t);
return .{
.a = .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) },
.b = .{ .row = @intCast(@max(0, b.hi_row - row0)), .col = @intCast(@max(0, b.hi_col)) },
};
}
if (t.msel.active) {
const r0: usize = @intCast(@max(0, @min(t.msel.r0, t.msel.r1) - row0));
const r1: usize = @intCast(@max(0, @max(t.msel.r0, t.msel.r1) - row0));
const llen = modal.lineSlice(content, r1).len;
return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = if (llen == 0) 0 else modal.prevGrapheme(modal.lineSlice(content, r1), llen) } };
}
const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - row0)), .col = @intCast(@max(0, t.cur_col)) };
return .{ .a = c, .b = c };
}
/// the rows an op's selection spans, absolute (what editText must cover)
fn selRows(t: *Text) Bounds {
if (t.vsel.active) return vselBounds(t);
if (t.msel.active) return .{
.lo_row = @min(t.msel.r0, t.msel.r1),
.lo_col = 0,
.hi_row = @max(t.msel.r0, t.msel.r1),
.hi_col = 0,
};
return .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col };
}
/// `r<ch>`: overwrite the selection (or the cursor char) with ch —
/// newlines included (helix), so `xrz` joins the selected lines
pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) void {
t.select = false;
const eb = editTextEol(p, t, selRows(t)) orelse return;
const before = t.primaryRange(eb.text, eb.row0);
const lo = @min(before.anchor, before.head);
const hi = @max(before.anchor, before.head);
var graphemes: usize = 0;
var at = lo;
while (at < hi) : (graphemes += 1) at = modal.nextGrapheme(eb.text, at);
var encoded: [4]u8 = undefined;
const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return;
const r = selRange(t, eb.text, eb.row0);
pushUndo(p, t);
const new = modal.replaceChars(p.gpa, eb.text, r.a, r.b, ch) catch return;
setEditText(p, t, new);
const end = lo + graphemes * encoded_len;
const mapped: modal.Selection = if (before.head < before.anchor)
.{ .anchor = end, .head = lo }
else
.{ .anchor = lo, .head = end };
t.setRange(new, eb.row0, mapped, t.vsel.explicit);
}
/// `R`: replace the selection (or the cursor char) with the DEFAULT
/// register. `SPC R` is the same verb over the system clipboard.
/// The acme chords' replace: the default register as one text.
pub fn chordReplace(p: *Pardes, t: *Text) void {
replaceWithText(p, t, p.registers.text(p.gpa, Registers.default) orelse return);
}
/// The pasted text becomes the selection, in the direction the replaced one
/// had: a forward head lands on its last char (which for a trailing-newline
/// `y` is the '\n' cell of the last full line), a backward one on its first.
fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) void {
if (y.len == 0) return;
t.select = false;
const eb = editTextEol(p, t, selRows(t)) orelse return;
const r = selRange(t, eb.text, eb.row0);
const back = t.vsel.active and (t.cur_row < t.vsel.row or (t.cur_row == t.vsel.row and t.cur_col < t.vsel.col));
pushUndo(p, t);
const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, y) catch return;
setEditText(p, t, new);
t.msel.active = false;
const end = modal.advanceBy(r.a, y);
var last_row: i32 = undefined;
var last_col: i32 = undefined;
if (end.col > 0) {
last_row = @as(i32, @intCast(end.row)) + eb.row0;
last_col = @intCast(modal.prevGrapheme(modal.lineSlice(new, end.row), end.col));
} else {
// the yank ended in '\n': its last cell is that newline
last_row = @as(i32, @intCast(end.row -| 1)) + eb.row0;
last_col = @intCast(modal.lineSlice(new, end.row -| 1).len);
}
const first_row = @as(i32, @intCast(r.a.row)) + eb.row0;
const first_col: i32 = @intCast(r.a.col);
t.vsel = .{
.active = modal.nextGrapheme(y, 0) < y.len,
.row = if (back) last_row else first_row,
.col = if (back) last_col else first_col,
.explicit = false,
};
t.cur_row = if (back) first_row else last_row;
t.cur_col = if (back) first_col else last_col;
t.cur_pinned = true;
t.sticky_col = -1;
t.show();
}
/// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char),
/// keeping the selection (helix)
pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) void {
t.select = false;
const eb = editTextEol(p, t, selRows(t)) orelse return;
const r = selRange(t, eb.text, eb.row0);
pushUndo(p, t);
const new = modal.changeCase(p.gpa, eb.text, r.a, r.b, op) catch return;
setEditText(p, t, new);
}
/// a change to apply to file content: delete [from, to), insert `ins` at
/// `from`. Ascending and disjoint.
const TextChange = struct { from: usize, to: usize, ins: []const u8 };
fn mapThroughChanges(chs: []const TextChange, pos: usize) usize {
var delta: i64 = 0;
for (chs) |ch| {
if (pos < ch.from) break;
if (ch.from == ch.to) {
delta += @intCast(ch.ins.len);
continue;
}
if (pos == ch.from) break;
if (pos < ch.to) return @intCast(@as(i64, @intCast(ch.from)) + delta);
delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from));
}
return @intCast(@as(i64, @intCast(pos)) + delta);
}
/// apply a change list. gpa-owned result.
fn applyChanges(p: *Pardes, text: []const u8, chs: []const TextChange) ![]u8 {
var total = text.len;
for (chs) |ch| total = total - (ch.to - ch.from) + ch.ins.len;
const out = try p.gpa.alloc(u8, total);
errdefer p.gpa.free(out);
var copied: usize = 0;
var at: usize = 0;
for (chs) |ch| {
const unchanged = text[copied..ch.from];
@memcpy(out[at..][0..unchanged.len], unchanged);
at += unchanged.len;
@memcpy(out[at..][0..ch.ins.len], ch.ins);
at += ch.ins.len;
copied = ch.to;
}
@memcpy(out[at..], text[copied..]);
return out;
}
/// `J` / `Alt-J`: join every range's lines with the next, in ONE edit
/// (helix join_selections): the newline and the next line's leading blanks
/// become one space, or nothing when that line is blank, and a line two
/// ranges share is joined once. `Alt-J` then selects the spaces it put in.
pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void {
const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active;
// a join always eats the newline of its last line, so the buffer has
// to reach one row PAST every range
var b = selRows(t);
for (t.sels[0..t.nsel]) |s| {
b.lo_row = @min(b.lo_row, @min(s.row, s.arow));
b.hi_row = @max(b.hi_row, @max(s.row, s.arow));
}
const eb = editText(p, t, b.lo_row, b.hi_row + 1, -1) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
const nlines = modal.cursorLineCount(text);
const arena = p.scratch.allocator();
const chs = arena.alloc(TextChange, nlines) catch return;
var chs_len: usize = 0;
var next: usize = 0; // lines below this one are joined already
for (rs[0..got.n]) |r| {
const span = Text.rangeLineSpan(text, r);
var end = span.end;
if (span.start == end) end = @min(end + 1, nlines - 1);
var l = @max(span.start, next);
while (l < end) : (l += 1) {
const from = modal.lineEndOffset(text, l);
var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1);
while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1;
const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " ";
chs[chs_len] = .{ .from = from, .to = to, .ins = sep };
chs_len += 1;
}
next = @max(next, end);
}
if (chs_len == 0) return;
pushUndo(p, t);
const new = applyChanges(p, text, chs[0..chs_len]) catch return;
// every range's cells ride through the edit; Alt-J replaces them with
// the spaces, when it put any in
var cells: [Text.max_selections]Text.SelRange = undefined;
var n: usize = 0;
var pri = got.pri;
if (select_space) {
var delta: i64 = 0;
for (chs[0..chs_len]) |ch| {
const at: usize = @intCast(@as(i64, @intCast(ch.from)) + delta);
delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from));
if (ch.ins.len == 0 or n == cells.len) continue;
const pos = modal.positionAt(new, at);
cells[n] = .{ .row = @as(i32, @intCast(pos.row)) + eb.row0, .col = @intCast(pos.col), .arow = @as(i32, @intCast(pos.row)) + eb.row0, .acol = @intCast(pos.col) };
n += 1;
}
pri = 0;
}
if (n == 0) {
for (rs[0..got.n]) |r| {
const c = Text.rangeCells(text, r);
const cc = modal.positionAt(new, mapThroughChanges(chs[0..chs_len], c.cur));
const ac = modal.positionAt(new, mapThroughChanges(chs[0..chs_len], c.anc));
cells[n] = .{
.row = @as(i32, @intCast(cc.row)) + eb.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + eb.row0,
.acol = @intCast(ac.col),
};
n += 1;
}
pri = got.pri;
}
setEditText(p, t, new);
const t2 = flatSurface(p, t) catch return;
for (cells[0..n], 0..) |s, i| rs[i] = Text.cellRange(t2, s.arow, s.acol, s.row, s.col);
t.setRanges(t2, rs[0..n], &.{}, pri, expl);
}
/// `Alt-)` / `Alt-(`: rotate the TEXT of the selections forward / back by
/// one range (count ranges), in one edit (helix reorder_selection_contents).
/// Each range comes back over the text it now holds, in its own direction,
/// and the primary moves with the text it had.
pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) void {
const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active;
var b = selRows(t);
for (t.sels[0..t.nsel]) |s| {
b.lo_row = @min(b.lo_row, @min(s.row, s.arow));
b.hi_row = @max(b.hi_row, @max(s.row, s.arow));
}
const eb = editTextEol(p, t, b) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
const n = got.n;
if (n < 2) return;
const by = @min(cnt, n);
var chs: [Text.max_selections]TextChange = undefined;
for (rs[0..n], 0..) |r, i| {
const src = rs[if (forward) (i + n - by) % n else (i + by) % n];
chs[i] = .{
.from = @min(r.anchor, r.head),
.to = @max(r.anchor, r.head),
.ins = text[@min(src.anchor, src.head)..@max(src.anchor, src.head)],
};
}
pushUndo(p, t);
const new = applyChanges(p, text, chs[0..n]) catch return;
var cells: [Text.max_selections]Text.SelRange = undefined;
var delta: i64 = 0;
for (chs[0..n], rs[0..n], 0..) |ch, r, i| {
const from: usize = @intCast(@as(i64, @intCast(ch.from)) + delta);
delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from));
const to = from + ch.ins.len;
const c = Text.rangeCells(new, if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to });
const cc = modal.positionAt(new, c.cur);
const ac = modal.positionAt(new, c.anc);
cells[i] = .{
.row = @as(i32, @intCast(cc.row)) + eb.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + eb.row0,
.acol = @intCast(ac.col),
};
}
setEditText(p, t, new);
const t2 = flatSurface(p, t) catch return;
for (cells[0..n], 0..) |s, i| rs[i] = Text.cellRange(t2, s.arow, s.acol, s.row, s.col);
t.setRanges(t2, rs[0..n], &.{}, if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl);
}
/// `&`: pad the selections into columns, in one edit (helix
/// align_selections). The k-th range of every line is a column; spaces go in
/// before each range so its head lands on the column's widest head, measured
/// in display cells. A range over several lines aligns nothing.
pub fn normalAlign(p: *Pardes, t: *Text) void {
const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active;
var b = selRows(t);
for (t.sels[0..t.nsel]) |s| {
b.lo_row = @min(b.lo_row, @min(s.row, s.arow));
b.hi_row = @max(b.hi_row, @max(s.row, s.arow));
}
const eb = editTextEol(p, t, b) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
const n = got.n;
var row: [Text.max_selections]usize = undefined;
var col: [Text.max_selections]usize = undefined;
var widths: [Text.max_selections]usize = @splat(0);
var line: usize = std.math.maxInt(usize);
var k: usize = 0;
var run: usize = 0;
for (rs[0..n], 0..) |r, i| {
row[i] = modal.lineAtOffset(text, r.head);
if (modal.lineAtOffset(text, r.anchor) != row[i]) return;
const ls = modal.lineStartOffset(text, row[i]);
col[i] = panes.File.rawDisplayCol(text[ls..modal.lineEndOffset(text, row[i])], r.head - ls);
if (row[i] != line) {
line = row[i];
k = 0;
run = 0;
}
widths[k] = @max(widths[k], col[i] - run);
run = col[i];
k += 1;
}
t.select = false; // helix exit_select_mode
// each column's head position, left to right
for (1..n) |i| widths[i] += widths[i - 1];
const arena = p.scratch.allocator();
var chs: [Text.max_selections]TextChange = undefined;
var m: usize = 0;
line = std.math.maxInt(usize);
for (rs[0..n], 0..) |r, i| {
if (row[i] != line) {
line = row[i];
k = 0;
run = 0;
}
const pad = widths[k] - col[i] - run;
k += 1;
run += pad;
if (pad == 0) continue;
const spaces = arena.alloc(u8, pad) catch return;
@memset(spaces, ' ');
const at = @min(r.anchor, r.head);
chs[m] = .{ .from = at, .to = at, .ins = spaces };
m += 1;
}
if (m == 0) return;
pushUndo(p, t);
const new = applyChanges(p, text, chs[0..m]) catch return;
var cells: [Text.max_selections]Text.SelRange = undefined;
for (rs[0..n], 0..) |r, i| {
const c = Text.rangeCells(text, r);
const cc = modal.positionAt(new, mapThroughChanges(chs[0..m], c.cur));
const ac = modal.positionAt(new, mapThroughChanges(chs[0..m], c.anc));
cells[i] = .{
.row = @as(i32, @intCast(cc.row)) + eb.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + eb.row0,
.acol = @intCast(ac.col),
};
}
setEditText(p, t, new);
const t2 = flatSurface(p, t) catch return;
for (cells[0..n], 0..) |s, i| rs[i] = Text.cellRange(t2, s.arow, s.acol, s.row, s.col);
t.setRanges(t2, rs[0..n], &.{}, got.pri, expl);
}
pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void {
t.select = false;
const sr = selRows(t);
const eb = editText(p, t, sr.lo_row, sr.hi_row, -1) orelse return;
const text = eb.text;
const range = t.primaryRange(text, eb.row0);
const span = Text.rangeLineSpan(text, range);
const arena = p.scratch.allocator();
// one run of spaces, sliced per line: `>` never inserts more than this
const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return;
@memset(pad, ' ');
const chs = arena.alloc(TextChange, span.end - span.start + 1) catch return;
var chs_len: usize = 0;
var l = span.start;
while (l <= span.end) : (l += 1) {
const ls = modal.lineStartOffset(text, l);
const le = modal.lineEndOffset(text, l);
const line = text[ls..le];
const nw = modal.firstNonWs(line);
if (nw == line.len) continue; // blank lines stay blank (helix)
if (add) {
const ins = modal.INDENT_W * cnt - (nw % modal.INDENT_W);
chs[chs_len] = .{ .from = ls, .to = ls, .ins = pad[0..ins] };
chs_len += 1;
} else {
const want = modal.INDENT_W * cnt;
var w: usize = 0;
var pos: usize = 0;
while (pos < line.len) {
if (line[pos] == ' ') {
w += 1;
} else if (line[pos] == '\t') {
w = (w / modal.INDENT_W + 1) * modal.INDENT_W;
} else break;
pos += 1;
if (w >= want) break;
}
if (pos > 0) {
chs[chs_len] = .{ .from = ls, .to = ls + pos, .ins = "" };
chs_len += 1;
}
}
}
if (chs_len == 0) return;
pushUndo(p, t);
const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) });
const anc_off = if (t.vsel.active)
modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row - eb.row0)), .col = @intCast(@max(0, t.vsel.col)) })
else
cur_off;
const new = applyChanges(p, text, chs[0..chs_len]) catch return;
const nc = mapThroughChanges(chs[0..chs_len], cur_off);
const na = mapThroughChanges(chs[0..chs_len], anc_off);
setEditText(p, t, new);
const cc = modal.positionAt(new, nc);
const ac = modal.positionAt(new, na);
t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
t.cur_col = @intCast(cc.col);
if (t.vsel.active) {
t.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0;
t.vsel.col = @intCast(ac.col);
}
t.msel.active = false;
t.cur_pinned = true;
t.sticky_col = -1;
t.show();
}
pub fn normalToggleComment(p: *Pardes, t: *Text) void {
const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active;
t.select = false; // helix exit_select_mode
// the buffer must cover every cursor's rows, not just the primary's
var b = selRows(t);
for (t.sels[0..t.nsel]) |s| {
b.lo_row = @min(b.lo_row, @min(s.row, s.arow));
b.hi_row = @max(b.hi_row, @max(s.row, s.arow));
}
const surface = flatSurface(p, t) catch return;
const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1;
const eb = editText(p, t, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
const nlines = modal.cursorLineCount(text);
const arena = p.scratch.allocator();
// the lines the ranges cover, each ONE ONCE and in order (helix's
// min_next_line: two cursors on one line comment it once)
const lines = arena.alloc(usize, nlines) catch return;
var lines_len: usize = 0;
var next: usize = 0;
for (rs[0..got.n]) |r| {
const span = Text.rangeLineSpan(text, r);
var l = @max(span.start, next);
const end = @min(span.end + 1, nlines);
while (l < end) : (l += 1) {
lines[lines_len] = l;
lines_len += 1;
}
next = @max(next, end);
}
const file = if (t.what != .body) null else if (t.pane()) |pane| pane.file else null;
const ext = if (file) |f| std.fs.path.extension(f.path) else "";
var token: []const u8 = config.comment_token_default;
lang: for (config.comment_tokens) |row| {
for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) {
token = row.token;
break :lang;
};
}
var commented = true;
var indent: usize = std.math.maxInt(usize);
var margin: usize = 1;
var live: usize = 0;
for (lines[0..lines_len]) |l| {
const line = text[modal.lineStartOffset(text, l)..modal.lineEndOffset(text, l)];
const nw = modal.firstNonWs(line);
if (nw == line.len) continue;
indent = @min(indent, nw);
if (!std.mem.startsWith(u8, line[nw..], token)) commented = false;
if (nw + token.len >= line.len or line[nw + token.len] != ' ') margin = 0;
live += 1;
}
if (live == 0) return; // nothing but blank lines
const ins = std.fmt.allocPrint(arena, "{s} ", .{token}) catch return;
const chs = arena.alloc(TextChange, lines_len) catch return;
var chs_len: usize = 0;
for (lines[0..lines_len]) |l| {
const ls = modal.lineStartOffset(text, l);
const le = modal.lineEndOffset(text, l);
const line = text[ls..le];
if (modal.firstNonWs(line) == line.len) continue; // blank lines untouched
const at = ls + indent;
// the @min can never bind: margin is 1 only when every line has a
// space after its own token, which is a byte past `at + token.len`
chs[chs_len] = if (commented)
.{ .from = at, .to = @min(at + token.len + margin, le), .ins = "" }
else
.{ .from = at, .to = at, .ins = ins };
chs_len += 1;
}
pushUndo(p, t);
// one edit, and the WHOLE selection rides through it (helix maps the
// selection with the transaction)
var cells: [Text.max_selections]Text.SelRange = undefined;
const new = applyChanges(p, text, chs[0..chs_len]) catch return;
for (rs[0..got.n], 0..) |r, i| {
const c = Text.rangeCells(new, .{
.anchor = mapThroughChanges(chs[0..chs_len], r.anchor),
.head = mapThroughChanges(chs[0..chs_len], r.head),
});
const cc = modal.positionAt(new, c.cur);
const ac = modal.positionAt(new, c.anc);
cells[i] = .{
.row = @as(i32, @intCast(cc.row)) + eb.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + eb.row0,
.acol = @intCast(ac.col),
};
}
setEditText(p, t, new);
const t2 = flatSurface(p, t) catch return;
for (cells[0..got.n], 0..) |s, i| rs[i] = Text.cellRange(t2, s.arow, s.acol, s.row, s.col);
t.setRanges(t2, rs[0..got.n], &.{}, got.pri, expl);
}
pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) void {
const eb = editTextEol(p, t, selRows(t)) orelse return;
const r = selRange(t, eb.text, eb.row0);
const arena = p.scratch.allocator();
const frag = modal.rangeText(arena, eb.text, r.a, r.b) catch return;
const rep = (modal.incrementDecimal(arena, frag, delta) catch null) orelse return;
pushUndo(p, t);
t.select = false;
const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, rep) catch return;
setEditText(p, t, new);
const start = modal.lineStartOffset(new, r.a.row) + r.a.col;
const cc = modal.positionAt(new, modal.prevGrapheme(new, start + rep.len));
t.vsel = .{ .active = modal.nextGrapheme(rep, 0) < rep.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false };
t.msel.active = false;
t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
t.cur_col = @intCast(cc.col);
t.cur_pinned = true;
t.sticky_col = -1;
t.show();
}
/// `]Space` / `[Space`: add blank lines below/above, the cursor staying
/// on its text line (the selection rides along)
pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) void {
// above the selection's first line, below its last (helix line_range)
const sr = selRows(t);
const at = if (below) sr.hi_row else sr.lo_row;
const eb = editText(p, t, at, at, -1) orelse return;
pushUndo(p, t);
const row: usize = @intCast(@max(0, at - eb.row0));
const arena = p.scratch.allocator();
const nl = arena.alloc(u8, cnt) catch return;
@memset(nl, '\n');
const llen = modal.lineSlice(eb.text, row).len;
const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return;
setEditText(p, t, new);
if (!below) {
// the whole selection moved down; stay on it
const n: i32 = @intCast(cnt);
t.cur_row += n;
if (t.vsel.active) t.vsel.row += n;
if (t.msel.active) {
t.msel.r0 += n;
t.msel.r1 += n;
}
}
t.cur_pinned = true;
t.show();
}
/// pair mapping for m-mode: either bracket names the pair; anything else
/// surrounds with itself (quotes)
fn pairFor(ch: u21) ?struct { o: u8, c: u8 } {
return switch (ch) {
'(', ')' => .{ .o = '(', .c = ')' },
'[', ']' => .{ .o = '[', .c = ']' },
'{', '}' => .{ .o = '{', .c = '}' },
'<', '>' => .{ .o = '<', .c = '>' },
else => if (ch <= 0x7f) .{ .o = @intCast(ch), .c = @intCast(ch) } else null,
};
}
pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around: bool) void {
const range = t.primaryRange(text, 0);
// helix's tree-sitter objects, from the grammar's textobjects query
const object: ?modal.Normal.Object = switch (obj) {
'f' => .function,
't' => .class,
'a' => .parameter,
'c' => .comment,
'T' => .@"test",
'e' => .entry,
'x' => .xml_element,
else => null,
};
if (object) |o| {
if (t.what != .body) return;
const pane = t.pane() orelse return;
const f = if (pane.file) |*file| file else return;
const tree = normal.fileTree(p, f) orelse return;
const s = syntax.objectAt(f.path, tree, text, o, around, modal.selectionCursor(text, range)) orelse return;
return t.setRange(text, 0, .{ .anchor = s.from, .head = s.to }, false);
}
switch (obj) {
'w', 'W' => {
const r = modal.selectWord(text, range, around, obj == 'W');
return t.setRange(text, 0, r, false);
},
'p' => {
const r = modal.selectParagraph(text, range, around, 1);
return t.setRange(text, 0, r, false);
},
else => {},
}
const lines = paneCursorLines(p, t) catch return;
const cur = modal.positionAt(text, modal.selectionCursor(text, range));
const pair: ?modal.Range = switch (obj) {
'\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)),
'(', ')' => modal.enclosingPair(lines, cur, '(', ')'),
'[', ']' => modal.enclosingPair(lines, cur, '[', ']'),
'{', '}' => modal.enclosingPair(lines, cur, '{', '}'),
'<', '>' => modal.enclosingPair(lines, cur, '<', '>'),
else => null,
};
const pr = pair orelse return;
var a = modal.offsetAt(text, pr.a);
var head = modal.nextGrapheme(text, modal.offsetAt(text, pr.b));
if (!around) {
// inside: shrink off the delimiters; an EMPTY pair collapses to
// a 1-wide cursor on the closing char (helix)
a = modal.nextGrapheme(text, a);
head = modal.prevGrapheme(text, head);
}
t.setRange(text, 0, .{ .anchor = a, .head = head }, false);
}
/// `ms<ch>`: wrap the selection (or the cursor char) in a pair; the wrap
/// including the pair becomes the selection
pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) void {
const pr = pairFor(ch) orelse return;
t.select = false;
const eb = editTextEol(p, t, selRows(t)) orelse return;
const r = selRange(t, eb.text, eb.row0);
// the wrapped range keeps the direction it had (helix with_direction)
const back = t.vsel.active and (t.cur_row < t.vsel.row or (t.cur_row == t.vsel.row and t.cur_col < t.vsel.col));
pushUndo(p, t);
const close_col = modal.nextGrapheme(modal.lineSlice(eb.text, r.b.row), r.b.col);
var new = modal.insertAt(p.gpa, eb.text, .{ .row = r.b.row, .col = close_col }, &[1]u8{pr.c}) catch return;
setEditText(p, t, new);
new = modal.insertAt(p.gpa, new, .{ .row = r.a.row, .col = r.a.col }, &[1]u8{pr.o}) catch return;
setEditText(p, t, new);
const open_row = @as(i32, @intCast(r.a.row)) + eb.row0;
const open_col: i32 = @intCast(r.a.col);
const close_row = @as(i32, @intCast(r.b.row)) + eb.row0;
const close_at: i32 = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0));
t.msel.active = false;
t.vsel = .{ .active = true, .row = if (back) close_row else open_row, .col = if (back) close_at else open_col, .explicit = false };
t.cur_row = if (back) open_row else close_row;
t.cur_col = if (back) open_col else close_at;
t.cur_pinned = true;
t.sticky_col = -1;
t.show();
}
/// `md<ch>`: delete the enclosing pair's chars; the cursor maps through
pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) void {
const pr = pairFor(ch) orelse return;
const lines = paneCursorLines(p, t) catch return;
const cur = t.toModalCursor();
const r = (if (pr.o == pr.c)
modal.enclosingQuote(lines, cur, pr.o)
else
modal.enclosingPair(lines, cur, pr.o, pr.c)) orelse return;
const lo: i32 = @intCast(@min(r.a.row, cur.row));
const hi: i32 = @intCast(@max(r.b.row, cur.row));
const eb = editText(p, t, lo, hi, -1) orelse return;
const text = eb.text;
const drow = -eb.row0; // surface row -> buffer row
const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col };
const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col };
pushUndo(p, t);
const a_off = modal.offsetAt(text, ra);
const b_off = modal.offsetAt(text, rb);
const cur_off = modal.offsetAt(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col });
// the close first, so the open's position stays valid
var new = modal.deleteChar(p.gpa, text, rb) catch return;
setEditText(p, t, new);
new = modal.deleteChar(p.gpa, new, ra) catch return;
setEditText(p, t, new);
var nc = cur_off;
if (nc > b_off) nc -= 1;
if (nc > a_off) nc -= 1;
const cc = modal.positionAt(new, nc);
t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
t.cur_col = @intCast(cc.col);
t.vsel.active = false;
t.msel.active = false;
t.cur_pinned = true;
t.show();
}
/// `mr<from><to>`: swap the enclosing <from> pair's chars for <to>'s
pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void {
const fp = pairFor(from) orelse return;
const tp = pairFor(to) orelse return;
const lines = paneCursorLines(p, t) catch return;
const cur = t.toModalCursor();
const r = (if (fp.o == fp.c)
modal.enclosingQuote(lines, cur, fp.o)
else
modal.enclosingPair(lines, cur, fp.o, fp.c)) orelse return;
const eb = editText(p, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return;
const drow = -eb.row0; // surface row -> buffer row
const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow);
const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow);
pushUndo(p, t);
const out = p.gpa.dupe(u8, eb.text) catch return;
out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o;
out[modal.lineStartOffset(out, br) + r.b.col] = tp.c;
setEditText(p, t, out);
}
pub fn pushUndo(p: *Pardes, t: *Text) void {
// one keystroke, one undo step — even when it edited at ten cursors.
if (p.multi_on and !p.multi_first) return;
switch (t.what) {
// A B1 chord took its one undo point when it began (mouse.zig).
.body => if (p.chord_hold) return,
.tag, .column, .workspace => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null),
// a prompt's answer is typed once and gone; it keeps no history
.input => return,
}
const pane = t.pane() orelse return;
if (pane.file != null) return panes.File.pushUndo(p, pane);
panes.Terminal.pushUndo(p, pane);
}
pub fn doUndo(p: *Pardes, t: *Text) void {
if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, true);
if (t.what != .body) return;
const pane = t.pane() orelse return;
if (pane.file != null) return panes.File.undo(p, pane);
panes.Terminal.undo(p, pane);
}
pub fn doRedo(p: *Pardes, t: *Text) void {
if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, false);
if (t.what != .body) return;
const pane = t.pane() orelse return;
if (pane.file != null) return panes.File.redo(p, pane);
panes.Terminal.redo(p, pane);
}
/// Undo or redo an edit of a text's own characters; stepping back past its
/// first edit gives a tag its default again.
fn stepOwn(p: *Pardes, t: *Text, back: bool) void {
const to = t.step(p.gpa, if (t.own) |own| .{ .text = own } else null, back) orelse return;
if (t.own) |own| p.gpa.free(own);
t.own = if (to.ovl) |buffer| buffer.text else null;
}
const PointerTextSelection = struct {
sel: Pane.Sel,
on_tag: bool,
};
pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_hit: ?TagHit) ?PointerTextSelection {
const pane = p.panes[id] orelse return null;
const r = p.rects[id];
if (col < r.x + config.GUTTER or col >= r.x + r.w or row < r.y or row >= r.y + r.h) return null;
const tag_y = p.tagTop(pane, r);
const body_y = p.bodyTop(pane, r);
const on_tag = row >= tag_y and row < tag_y + pane.tag_rows;
if (on_tag and col < r.x + TAG_TEXT_INSET) return null;
// A notice chip is chrome: it sits OVER the body's top rows, so a
// click inside one belongs to nobody. The rest of those rows is
// ordinary body text and still answers normally.
if (!on_tag and row >= body_y and row - body_y < pane.notices.span() and
pane.notices.covers(row - body_y, col)) return null;
if (!on_tag) if (body_hit) |supplied| {
const mapped_hit = mouse.bodyHitForPane(p, id, supplied, false) orelse return null;
const c = @as(i32, mapped_hit.col) - config.GUTTER;
const v = @as(i32, mapped_hit.row) + pane.tag_rows;
return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false };
};
const tag_col = if (on_tag) tag_layer.columnAt(p, .pane, id, tag_hit, false, row - tag_y) else null;
const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) +
(if (on_tag) @as(i32, pane.tag_scroll) else 0);
const v: i32 = if (on_tag) @as(i32, row) - @as(i32, tag_y) else @as(i32, row) - @as(i32, body_y) + @as(i32, pane.tag_rows);
return .{
.sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v },
.on_tag = on_tag,
};
}
/// Drain the queue and say whether the shell was asked to do `want`.
fn drainedEffect(p: *Pardes, want: std.meta.Tag(Effect)) bool {
var seen = false;
while (p.nextEffect()) |effect| {
if (std.meta.activeTag(effect) == want) seen = true;
}
return seen;
}
test "insert newline adds one indent level after a closing call" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile(" callback({})\n");
pane.body.mode = .insert;
pane.body.cur_col = 16;
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqualSlices(u8, " callback({})\n \n", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col);
}
test "insert and normal modes edit complete Unicode graphemes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("a" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "界" ++ "z");
pane.body.mode = .insert;
pane.body.cur_col = 22; // on z, after the CJK grapheme
insertKey(p, &pane.body, .{ .cp = Key.left });
try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col);
insertKey(p, &pane.body, .{ .cp = Key.left });
try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
insertKey(p, &pane.body, .{ .cp = Key.right });
try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col);
insertKey(p, &pane.body, .{ .cp = Key.backspace });
try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
pane.body.mode = .normal;
pane.body.cur_col = 1;
normalDelete(p, &pane.body, false);
try std.testing.expectEqualStrings("a界z", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
normalReplaceChar(p, &pane.body, 'λ');
try std.testing.expectEqualStrings("aλz", pane.file.?.content);
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a"));
pane.body.cur_col = 3;
pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
normalReplaceChar(p, &pane.body, 'λ');
try std.testing.expectEqualStrings("λλ", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col);
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a"));
pane.body.cur_col = 0;
pane.body.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true };
normalReplaceChar(p, &pane.body, 'λ');
try std.testing.expectEqualStrings("λλ", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col);
}
test "flat text replacement preserves a terminal fragment origin and direction" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
p.update(.{ .output = .{ .pane = 0, .bytes = "first\r\nsecond\r\nthird\r\n界a\r\n" } });
const pane = p.panes[0].?;
pane.body.mode = .normal;
pane.body.cur_pinned = true;
pane.body.cur_row = 3;
pane.body.cur_col = 0;
pane.body.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true };
normalReplaceChar(p, &pane.body, 'λ');
try std.testing.expectEqual(@as(i32, 3), pane.ovl.?.row);
try std.testing.expectEqualStrings("λλ", pane.ovl.?.text);
try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 3), pane.body.vsel.row);
try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col);
try std.testing.expect(pane.body.vsel.active and pane.body.vsel.explicit);
const lines = try paneCursorLines(p, &pane.body);
try std.testing.expectEqualStrings("first", lines[0]);
try std.testing.expectEqualStrings("λλ", lines[3]);
const flat = try flatSurface(p, &pane.body);
try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n"));
}
test "only the SPC clipboard commands cross to the system clipboard" {
if (platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const pane = p.panes[0].?;
_ = drainedEffect(p, .set_clipboard);
p.update(.{ .key = .{ .cp = 'y' } });
const plain = p.registers.text(gpa, Registers.default) orelse return error.MissingYank;
try std.testing.expect(plain.len > 0);
try std.testing.expect(!drainedEffect(p, .set_clipboard));
p.update(.{ .key = .{ .cp = 'd' } });
try std.testing.expect(!drainedEffect(p, .set_clipboard));
// `SPC y` is the one that does: helix's `"+y`, the ordinary yank into
// the clipboard register instead of the default one.
p.update(.{ .key = .{ .cp = ' ' } });
p.update(.{ .key = .{ .cp = 'y' } });
const yanked = try gpa.dupe(u8, p.registers.text(gpa, Registers.default) orelse "");
defer gpa.free(yanked);
const clip: []const u8 = p.registers.text(gpa, '+') orelse "";
try std.testing.expect(clip.len > 0);
try std.testing.expect(drainedEffect(p, .set_clipboard));
const before = pane.file.?.content.len;
p.update(.{ .key = .{ .cp = ' ' } });
p.update(.{ .key = .{ .cp = 'p' } });
try std.testing.expect(p.clip_pending != null);
try std.testing.expect(drainedEffect(p, .read_clipboard));
try std.testing.expectEqual(before, pane.file.?.content.len); // nothing yet
p.update(.{ .paste = "PASTED" });
try std.testing.expect(p.clip_pending == null);
try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "PASTED") != null);
// ...and it did NOT land in the register on its way past, nor echo back
// out to the clipboard it came from.
try std.testing.expectEqualStrings(yanked, p.registers.text(gpa, Registers.default) orelse "");
try std.testing.expect(!drainedEffect(p, .set_clipboard));
// An UNSOLICITED paste — the outer terminal's bracketed paste, a Cmd-V —
// is the same event with no request behind it, and means paste after.
p.update(.{ .paste = "UNASKED" });
try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "UNASKED") != null);
try std.testing.expectEqualStrings(yanked, p.registers.text(gpa, Registers.default) orelse "");
// A request the shell never answers dies at the next keystroke rather
// than firing late into whatever pane is focused by then.
p.update(.{ .key = .{ .cp = ' ' } });
p.update(.{ .key = .{ .cp = 'P' } });
try std.testing.expect(p.clip_pending != null);
p.update(.{ .key = .{ .cp = 'l' } });
try std.testing.expect(p.clip_pending == null);
}
/// acme's double-click (plan9port acme text.c:1407, textdoubleclick): from
/// the point `q` (before the character clicked), the text up to the match
/// of a bracket just before it or just after it (text.c:1386, `{[(<«` and
/// their closers), the whole line at a line's start or end, the quoted text
/// next to `' " \``, else the word, acme's isalnum (util.c:328) run.
pub fn doubleClickRange(text: []const u8, q_in: usize) [2]usize {
const sets = [_][2][]const u21{
.{ &.{ '{', '[', '(', '<', 0xab }, &.{ '}', ']', ')', '>', 0xbb } },
.{ &.{'\n'}, &.{'\n'} },
.{ &.{ '\'', '"', '`' }, &.{ '\'', '"', '`' } },
};
const q = @min(q_in, text.len);
for (sets) |set| {
const left, const right = set;
// the character to the left, looking right
const before = if (q == 0) .{ @as(u21, '\n'), @as(usize, 0) } else runeBefore(text, q);
if (std.mem.indexOfScalar(u21, left, before[0])) |k| {
var at = q;
if (clickMatch(text, before[0], right[k], true, &at)) {
const closer = if (before[0] == '\n') 0 else runeLen(right[k]);
return .{ q, at - closer };
}
return .{ q, q };
}
// the character to the right, looking left
const after = if (q == text.len) @as(u21, '\n') else runeAt(text, q);
if (std.mem.indexOfScalar(u21, right, after)) |k| {
var at = q;
if (clickMatch(text, after, left[k], false, &at)) {
const q1 = q + @as(usize, @intFromBool(q < text.len and after == '\n'));
var q0 = at;
if (after != '\n' or at != 0 or (text.len > 0 and text[0] == '\n')) q0 += runeLen(left[k]);
return .{ @min(q0, q1), q1 };
}
return .{ q, q };
}
}
var lo = q;
var hi = q;
while (hi < text.len and isAlnum(runeAt(text, hi))) hi += std.unicode.utf8ByteSequenceLength(text[hi]) catch 1;
while (lo > 0 and isAlnum(runeBefore(text, lo)[0])) lo = runeBefore(text, lo)[1];
return .{ lo, hi };
}
/// acme's textclickmatch (text.c:1457): the nesting match of `cl` by `cr`
/// from `q`, leaving `q` just past it (forward) or on it (back).
fn clickMatch(text: []const u8, cl: u21, cr: u21, forward: bool, q: *usize) bool {
var nest: usize = 1;
while (true) {
var c: u21 = undefined;
if (forward) {
if (q.* >= text.len) break;
c = runeAt(text, q.*);
q.* += std.unicode.utf8ByteSequenceLength(text[q.*]) catch 1;
} else {
if (q.* == 0) break;
const b = runeBefore(text, q.*);
q.* = b[1];
c = b[0];
}
if (c == cr) {
nest -= 1;
if (nest == 0) return true;
} else if (c == cl) nest += 1;
}
return cl == '\n' and nest == 1;
}
fn runeLen(c: u21) usize {
return std.unicode.utf8CodepointSequenceLength(c) catch 1;
}
fn runeAt(text: []const u8, at: usize) u21 {
const n = std.unicode.utf8ByteSequenceLength(text[at]) catch return text[at];
if (at + n > text.len) return text[at];
return std.unicode.utf8Decode(text[at..][0..n]) catch text[at];
}
/// The rune ending at `at`, and where it starts.
fn runeBefore(text: []const u8, at: usize) struct { u21, usize } {
var s = at - 1;
while (s > 0 and text[s] & 0xC0 == 0x80 and at - s < 4) s -= 1;
return .{ runeAt(text, s), s };
}
fn isAlnum(c: u21) bool {
if (c <= ' ') return false;
if (c >= 0x7F and c <= 0xA0) return false;
if (c < 0x80 and std.mem.indexOfScalar(u8, "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~", @intCast(c)) != null) return false;
return true;
}
test "double-click selects as acme's does" {
const t = "fn foo_bar(a, b) {\n x\n}\n";
const Case = struct { q: usize, want: []const u8 };
for ([_]Case{
.{ .q = 4, .want = "foo_bar" }, // in a word
.{ .q = 11, .want = "a, b" }, // just after (
.{ .q = 15, .want = "a, b" }, // just before )
.{ .q = 18, .want = "\n x\n" }, // just after {
.{ .q = 0, .want = "fn foo_bar(a, b) {\n" }, // a line's start
}) |c| {
const r = doubleClickRange(t, c.q);
try std.testing.expectEqualStrings(c.want, t[r[0]..r[1]]);
}
const quoted = "say \"hello there\" now";
const r = doubleClickRange(quoted, 5);
try std.testing.expectEqualStrings("hello there", quoted[r[0]..r[1]]);
const french = "«oui»";
const f = doubleClickRange(french, 2);
try std.testing.expectEqualStrings("oui", french[f[0]..f[1]]);
// a line's end: the whole line, its newline included
const lines = "one\ntwo\n";
const e = doubleClickRange(lines, 7);
try std.testing.expectEqualStrings("two\n", lines[e[0]..e[1]]);
}
|