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
|
//! A text prompt in a pane's tag (walk UI, pick-ui SPEC.md §7): `/ ?`
//! search the body, `s S K A-K` select by a pattern, `| A-| ! A-! $` pipe
//! through a command, typed in
//! the head's field after the prompt's key cell, the plain word it stands
//! for and its count beside it (`s self = Exec Edit x/self/ 4 selections in
//! 6 lines`), its effect drawn live in the body on every key; Enter applies
//! it and keeps the line in its history, Esc puts the body back.
//!
//! A sam prompt (`s S K A-K | A-|`, sam's `x y g v | >`) right after
//! another of the same pane's, no key between, extends one recipe word in
//! the pane's trail, the Edit line it is (`Edit x/self/ |tr a-z A-Z`): Look
//! on it puts back the selections it made, Exec runs it as Edit (SPEC §7.5).
//!
//! A view's own (TagState.prompt, the coordinator's R4): its field the
//! head's (TagState.field); its histories the session's, three of them
//! (`/ ? s S K A-K` share one, the pipes another, `:` its own). A prompt for
//! a tag's text or a header's still asks on the notice band (panes.zig
//! startPrompt), as does Save's.
const Prompt = @This();
const std = @import("std");
const pardes = @import("root.zig");
const config = @import("config.zig");
const modal = @import("modal.zig");
const panes = @import("panes.zig");
const normal = @import("normal.zig");
const edit = @import("edit.zig");
const regexp = @import("regexp.zig");
const tagline = @import("tagline.zig");
const Pipe = @import("Pipe.zig");
const Field = @import("Field.zig");
const Band = @import("Band.zig");
const TagState = @import("TagState.zig");
const Kind = @import("Kind.zig");
const Places = @import("Places.zig");
const Trail = @import("Trail.zig");
const Command = @import("Command.zig");
const colors = @import("colors.zig");
const Surface = @import("surface.zig").Surface;
const Cell = @import("surface.zig").Cell;
const File = panes.File;
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const Text = panes.Text;
const Key = pardes.Key;
const hit = pardes.hit;
pub const Op = enum(u8) { search, search_back, select, split, keep, remove, pipe, pipe_to, insert, append, keep_pipe, command };
op: Op = .select,
/// The line of its history the keys are on: 0 the field as typed, n the
/// n-th newest line, in the field when Up or Down brought it, under the
/// cursor of the history unrolled (`historyAt`).
recall: u8 = 0,
/// Ctrl-r: its history unrolled under the tag, filtered by the field.
history: bool = false,
/// The field is no regex: the body keeps the last result, dimmed, and the
/// count says why.
bad: bool = false,
/// The ranges the last pattern found (0: none, the selections it started
/// from back), and the lines those it started from cover.
found: u16 = 0,
scope: u32 = 0,
/// `?` waits for its place: the last before where it began, once the text
/// between them is searched.
seeking: bool = false,
/// The lines a search's places are on, counted once they are all found, at
/// the places' `hits_gen` `counted`.
lines: u32 = 0,
counted: u32 = std.math.maxInt(u32),
/// The pane, by serial, whose sam prompt Enter took last with no key since:
/// the next one extends its recipe (0: none).
chain: u32 = 0,
/// A pipe's: Ctrl-p ran a command that is no known filter live; Enter was
/// refused once over runs that failed.
forced: bool = false,
refused: bool = false,
/// `:`'s (Command.zig): what its rows are of, and where Tab writes.
command: Command = .{},
/// The session's prompt histories: the lines Enter took, newest last; and
/// each picker source's queries, as its picker landed or was left typed
/// (Pick.zig, UX L2).
pub const History = struct {
search: Ring = .{},
pipe: Ring = .{},
command: Ring = .{},
pick: std.EnumArray(pardes.Pick.Source, Ring) = .initFill(.{}),
};
pub const Ring = struct {
pub const replica = .{ .len = .{.{ "lines", "n" }} };
/// The lines a history keeps; past it the oldest goes.
pub const max = 16;
/// Empty, not undefined: a damaged image's count past the lines it
/// holds reads empty lines, never undefined bytes.
lines: [max]Kind.Buf(Field.max) = @splat(.{}),
n: u8 = 0,
/// `line` the newest, an older copy of it gone.
pub fn add(r: *Ring, line: []const u8) void {
if (line.len == 0) return;
var w: u8 = 0;
for (r.lines[0..r.n]) |l| if (!std.mem.eql(u8, l.slice(), line)) {
r.lines[w] = l;
w += 1;
};
r.n = w;
if (r.n == max) {
std.mem.copyForwards(Kind.Buf(Field.max), r.lines[0 .. max - 1], r.lines[1..]);
r.n -= 1;
}
r.lines[r.n].set(line);
r.n += 1;
}
/// The `back`-th newest line, 1 the newest.
pub fn get(r: *const Ring, back: u8) ?[]const u8 {
if (back == 0 or back > r.n) return null;
return r.lines[r.n - back].slice();
}
};
const Info = struct {
/// Its key cell.
cell: []const u8,
hint: []const u8,
};
const info = std.EnumArray(Op, Info).init(.{
.search = .{ .cell = "/", .hint = "⏎ land · M-⏎ as a list · C-r history · esc" },
.search_back = .{ .cell = "?", .hint = "⏎ land · M-⏎ as a list · C-r history · esc" },
.select = .{ .cell = "s", .hint = "⏎ select · M-⏎ as a list · C-r history · esc" },
.split = .{ .cell = "S", .hint = "⏎ select · M-⏎ as a list · C-r history · esc" },
.keep = .{ .cell = "K", .hint = "⏎ keep · M-⏎ as a list · C-r history · esc" },
.remove = .{ .cell = "A-K", .hint = "⏎ keep · M-⏎ as a list · C-r history · esc" },
.pipe = .{ .cell = "|", .hint = "⏎ replace · C-r history · esc" },
.pipe_to = .{ .cell = "A-|", .hint = "⏎ run · C-r history · esc" },
.insert = .{ .cell = "!", .hint = "⏎ insert · C-r history · esc" },
.append = .{ .cell = "A-!", .hint = "⏎ append · C-r history · esc" },
.keep_pipe = .{ .cell = "$", .hint = "⏎ keep · C-r history · esc" },
.command = .{ .cell = ":", .hint = "Tab complete · ⏎ run · C-r history · esc" },
});
/// The history `op` reads and Enter adds to.
fn ring(p: *Pardes, op: Op) *Ring {
return switch (op) {
.search, .search_back, .select, .split, .keep, .remove => &p.prompt_history.search,
.pipe, .pipe_to, .insert, .append, .keep_pipe => &p.prompt_history.pipe,
.command => &p.prompt_history.command,
};
}
pub fn ofMode(m: modal.Normal.RegexMode) Op {
return switch (m) {
.select => .select,
.split => .split,
.keep => .keep,
.remove => .remove,
};
}
fn mode(op: Op) ?modal.Normal.RegexMode {
return switch (op) {
.select => .select,
.split => .split,
.keep => .keep,
.remove => .remove,
else => null,
};
}
pub fn ofBehavior(how: modal.Normal.PipeBehavior) Op {
return switch (how) {
.replace => .pipe,
.ignore => .pipe_to,
.insert => .insert,
.append => .append,
.keep => .keep_pipe,
};
}
fn searches(op: Op) bool {
return op == .search or op == .search_back;
}
fn behavior(op: Op) ?modal.Normal.PipeBehavior {
return switch (op) {
.pipe => .replace,
.pipe_to => .ignore,
.insert => .insert,
.append => .append,
.keep_pipe => .keep,
else => null,
};
}
/// Prompt `op` in the tag of `pane`, the pane with the keyboard, for its
/// body: its field empty, the body's selections as they are (`s S K A-K`
/// select inside them, `/ ?` search from the primary one; Esc puts them
/// back). `/ ?` search a file's body only.
pub fn open(p: *Pardes, pane: *Pane, op: Op) void {
// Nobody is at the keyboard to answer a command a script wrote to a
// ctl file: the write fails instead (core/ninep/ctl.zig).
if (p.fs.no_prompt) {
p.fs.refused = true;
p.fs.failures +%= 1;
return;
}
const t = &pane.body;
// A body is piped only when it is a file that saves.
if (behavior(op) != null) {
const f = pane.file orelse return;
if (!panes.Output.fileTraits(f.output).saves) return;
}
var scope: u32 = 0;
if (mode(op) != null) {
const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(p.view().active), "prompt", err);
const got = t.ranges(text, 0, &pane.sel_snap);
pane.nsel_snap = @intCast(got.n);
pane.sel_snap_pri = @intCast(got.pri);
pane.sel_snap_expl = t.vsel.active and t.vsel.explicit;
for (pane.sel_snap[0..got.n]) |r| {
const lo = @min(r.anchor, r.head, text.len);
const hi = @min(@max(r.anchor, r.head), text.len);
scope += @intCast(std.mem.count(u8, text[lo..hi -| @intFromBool(hi > lo and text[hi - 1] == '\n')], "\n") + 1);
}
}
if (searches(op)) pane.places.remember(p, pane);
pane.focus = .body;
tagline.exitHeader(p);
t.mode = .normal;
t.normal.clear();
TagState.toRest(p);
const s = &p.view().tag_state;
s.kind = .prompt;
s.host = pane.serial;
s.field.clear();
s.rows = .{};
s.prompt = .{ .op = op, .scope = scope, .chain = s.prompt.chain };
if (behavior(op) != null) Pipe.dropLive(p);
}
/// A key the tag at rest takes (keys.handleKey): any but one that opens a
/// sam prompt ends the recipe Enter left open (a motion, an edit).
pub fn keyAtRest(p: *Pardes, k: Key) void {
const s = &p.view().tag_state;
if (s.prompt.chain == 0) return;
if (hit(k, config.select_regex) or hit(k, config.split_regex) or hit(k, config.keep_regex) or
hit(k, config.remove_regex) or hit(k, config.pipe_selection) or hit(k, config.pipe_selection_to)) return;
s.prompt.chain = 0;
}
/// A key in the prompt of the live view's tag: the field's editing keys,
/// and the prompt's own.
pub fn key(p: *Pardes, k: Key) void {
const v = p.view();
const s = &v.tag_state;
const id = TagState.hostOf(p) orelse return TagState.toRest(p);
const pane = p.panes[id].?;
const plain = !k.ctrl and !k.alt;
const ctrl = k.ctrl and !k.alt;
if (hit(k, config.escape)) return cancel(p, pane);
// Its history unrolled is a list like any other (UX D5): Down and C-n,
// Up and C-p move its cursor to the next line it shows, older or newer,
// the field kept as typed; Enter takes the line under it.
if (s.prompt.history) {
const r = ring(p, s.prompt.op);
if (historyKey(r, s.field.text(), &s.prompt.recall, k)) return;
const at = historyAt(r, s.field.text(), s.prompt.recall);
if (plain and k.cp == Key.enter and at != 0) {
s.field.set(r.get(at).?);
live(p, pane);
}
}
if (s.prompt.op == .command and Command.key(p, id, pane, k)) return;
if (plain and k.cp == Key.enter) return commit(p, id, pane);
if (k.alt and !k.ctrl and k.cp == Key.enter) return asList(p, id, pane);
// Backspace on an empty field: the prompt goes, as Esc.
if (plain and k.cp == Key.backspace and s.field.len == 0) return cancel(p, pane);
// Up and Down bring its history's lines into the field, the newest first.
if (plain and (k.cp == Key.up or k.cp == Key.down)) {
const r = ring(p, s.prompt.op);
const to: u8 = if (k.cp == Key.up) @min(r.n, s.prompt.recall + 1) else s.prompt.recall -| 1;
if (to == s.prompt.recall) return;
s.prompt.recall = to;
s.field.set(r.get(to) orelse "");
return live(p, pane);
}
if (ctrl and k.cp == 'r') {
s.prompt.history = !s.prompt.history;
return;
}
// A command no known filter: Ctrl-p runs it live all the same.
if (ctrl and k.cp == 'p' and behavior(s.prompt.op) != null) {
s.prompt.forced = true;
return live(p, pane);
}
if (!s.field.key(k)) return;
s.prompt.recall = 0;
s.prompt.forced = false;
live(p, pane);
}
/// What the field says now, done to the body: the selections a pattern
/// finds inside the ones the prompt began with; none, or no pattern, those
/// it began with. A pattern that is no regex changes nothing, and the
/// prompt says why.
fn live(p: *Pardes, pane: *Pane) void {
const s = &p.view().tag_state;
const pat = s.field.text();
if (s.prompt.op == .command) return Command.filter(p, pane);
if (behavior(s.prompt.op)) |how| {
// A pipe: run live per selection when it is a known filter (or
// Ctrl-p said so), off the loop; Enter is asked again.
s.prompt.refused = false;
if (pat.len == 0 or !(s.prompt.forced or pure(pat))) return Pipe.dropLive(p);
return Pipe.live(p, p.view().active, &pane.body, how, pat);
}
if (mode(s.prompt.op) == null and !searches(s.prompt.op)) return;
s.prompt.bad = pat.len > 0 and if (regexp.Regex.compile(pat)) |_| false else |_| true;
if (s.prompt.bad) return;
if (mode(s.prompt.op)) |m| {
s.prompt.found = @intCast(normal.applySelRegex(p, pane, &pane.body, pat, m));
return;
}
// A search: its places found from where it began, the view's first,
// the rest a frame's budget a tick (Places.zig); `/` selects the first
// at or after the caret as soon as it is found, `?` the last before it.
const set = &pane.places;
s.prompt.counted = std.math.maxInt(u32);
if (pat.len == 0) {
if (set.from == 0) set.clear(p.gpa);
set.restore(p.settings.tab, pane);
return;
}
const back = s.prompt.op == .search_back;
set.search(p, pane, .typed, 0, pat, false, if (back) null else set.origin(pane), !back);
s.prompt.seeking = back;
if (back) seekBack(p, pane);
}
/// `?`'s place: the last before where it began once the text between is
/// searched, past the top the last of all once every place is found;
/// none, the body as it was.
fn seekBack(p: *Pardes, pane: *Pane) void {
const s = &p.view().tag_state;
const set = &pane.places;
if (!set.started) return;
const origin = set.origin(pane);
const hits = set.hits.items;
const i = Places.firstFrom(hits, origin);
const whole = set.head_to >= set.lo;
const to: ?usize = if (i > 0 and origin <= set.hi and (whole or hits[i - 1].start >= set.lo))
i - 1
else if (set.complete() and hits.len > 0)
hits.len - 1
else
null;
if (to) |at| {
s.prompt.seeking = false;
return set.goTo(p.settings.tab, pane, at, false);
}
if (!set.complete()) return;
s.prompt.seeking = false;
set.restore(p.settings.tab, pane);
}
/// Enter: what the field says, applied, and the line kept in its history
/// and its register (`/` a pattern's, `|` a command's).
fn commit(p: *Pardes, id: usize, pane: *Pane) void {
const s = &p.view().tag_state;
const op = s.prompt.op;
if (behavior(op) != null and refuses(p, id, pane)) return;
const line = s.field.text();
// The field is the view's: what is kept of it is copied before rest.
var kept: [Field.max]u8 = undefined;
@memcpy(kept[0..line.len], line);
const typed = kept[0..line.len];
const bad = s.prompt.bad;
s.kind = .rest;
TagState.toRest(p);
if (typed.len == 0) return undo(p, pane, op);
ring(p, op).add(typed);
if (searches(op)) return land(p, id, pane, op, typed, bad);
if (mode(op) != null) {
// No regex: the selections it began with, and why.
if (bad) {
undo(p, pane, op);
return p.setMessage(.at(id), regexMessage(typed));
}
// helix keeps the pattern in `/`
p.registers.put(p.gpa, '/', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err);
p.registers.last_search = '/';
// Nothing found: nothing changed, no link.
if (s.prompt.found == 0) return;
link(p, pane, op, typed);
keepSelections(p, pane);
return;
}
if (behavior(op)) |how| {
p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err);
// `! A-! $` apply, and end the recipe: no Edit line says them.
if (op == .pipe or op == .pipe_to) link(p, pane, op, typed) else s.prompt.chain = 0;
// What the live run made, applied (the runs that failed leaving
// their selections); else, or `A-|` (its point is what it does),
// the command run now.
if (op != .pipe_to and Pipe.applyLive(p, pane.serial, typed)) return;
Pipe.dropLive(p);
return Pipe.submit(p, id, &pane.body, how, typed);
}
}
/// Enter in `/` or `?`: the place found current, its places tinted from
/// now on for n and N, the pattern in `/`, and the pane's search word
/// `/re/ 3/7` in its trail (SPEC §7.3).
fn land(p: *Pardes, id: usize, pane: *Pane, op: Op, pat: []const u8, bad: bool) void {
const set = &pane.places;
// A search moves the selection: the recipe ends.
p.view().tag_state.prompt.chain = 0;
if (bad) {
undo(p, pane, op);
return p.setMessage(.at(id), regexMessage(pat));
}
set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget);
if (op == .search_back) seekBack(p, pane);
if (set.hits.items.len == 0) {
undo(p, pane, op);
var said: [Field.max + 16]u8 = undefined;
return p.setMessage(.at(id), std.fmt.bufPrint(&said, "/{s}/: no match", .{pat}) catch "no match");
}
p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err);
p.registers.last_search = '/';
set.provenance = .search;
const from = set.origin(pane);
set.forget(p.gpa);
word(p, pane, if (op == .search_back) '?' else '/', pat, from);
Trail.sayBack(p, id);
}
/// Alt-Enter in `/ ?` or `s S K A-K` (SPEC §7.2): the result kept as a
/// list, a row a place, the body as it was before the prompt. Where jumps
/// walk, a picker of those rows (Pick.zig's `list`, titled by the plain
/// word, `/dirty/`) in the tag of the pane its Enter lands in; else `/`'s
/// query pane (Query.zig) and the selections as a +Search list.
fn asList(p: *Pardes, id: usize, pane: *Pane) void {
const s = &p.view().tag_state;
const op = s.prompt.op;
if (!searches(op) and mode(op) == null) return;
if (s.prompt.bad) return;
var kept: [Field.max]u8 = undefined;
const typed = kept[0..s.field.len];
@memcpy(typed, s.field.text());
var said: [Trail.max_text]u8 = undefined;
var sw: std.Io.Writer = .fixed(&said);
_ = plainWord(&sw, op, typed) catch {};
// The word cut at a character's start to a picker's word's room.
const plain = sw.buffered();
const title = plain[0..modal.graphemeStart(plain, @min(plain.len, 24))];
var rows: std.Io.Writer.Allocating = .init(p.gpa);
defer rows.deinit();
const total = listRows(p, pane, op, &rows.writer) catch |err| return p.reportError(.at(id), "prompt", err);
s.kind = .rest;
TagState.toRest(p);
undo(p, pane, op);
if (total > panes.Query.max_rows) {
var cut: [96]u8 = undefined;
p.setMessage(.at(id), std.fmt.bufPrint(&cut, "{s}: the first {d} of {d} places", .{ title, panes.Query.max_rows, total }) catch "");
}
if (pardes.Pick.asked(p)) return pardes.Pick.open(p, id, .list, title, "", rows.written());
if (searches(op)) return panes.Query.open(p, id, .text, typed, true);
const content = rows.toOwnedSlice() catch |err| return p.reportError(.at(id), "prompt", err);
panes.Output.fillResults(p, id, panes.paneDir(pane), .search, title, content, null) catch |err| return p.reportError(.at(id), "prompt", err);
}
/// The live result of prompt `op` in `pane` as a list's rows,
/// `path:line:col text` each, the first `Query.max_rows`: a search's
/// places (every one found within a search's budget) or a sam prompt's
/// selections. How many there were.
fn listRows(p: *Pardes, pane: *Pane, op: Op, w: *std.Io.Writer) !usize {
const f = &pane.file.?;
const index = try File.lineIndex(p.gpa, f);
if (searches(op)) {
const set = &pane.places;
set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget);
const hits = set.hits.items;
for (hits[0..@min(hits.len, panes.Query.max_rows)]) |h| try placeRow(w, f, index, h.start);
return hits.len;
}
var sels: [Text.max_selections]modal.Selection = undefined;
const got = pane.body.ranges(f.content, 0, &sels);
for (sels[0..@min(got.n, panes.Query.max_rows)]) |r| try placeRow(w, f, index, @min(r.anchor, r.head));
return got.n;
}
/// Byte `at` of file `f` as a list's row: its place (`path:line:col:`,
/// look.parsePathLine's) and its line's text, the blanks it starts with
/// off, cut to `row_text` bytes.
fn placeRow(w: *std.Io.Writer, f: *const File.State, index: []const usize, at: usize) !void {
const row_text = 160;
const line = Places.lineOf(index, at);
const start = index[line];
const end = std.mem.indexOfScalarPos(u8, f.content, start, '\n') orelse f.content.len;
const text = std.mem.trimStart(u8, f.content[start..end], " \t");
try w.print("{s}:{d}:{d}: {s}\n", .{ f.path, line + 1, at - start + 1, text[0..modal.graphemeStart(text, @min(text.len, row_text))] });
}
/// The filters a pipe prompt runs live as it is typed: commands that
/// only read their input and write their output (SPEC §7.4).
const filters = [_][]const u8{ "sort", "uniq", "tr", "cut", "sed", "awk", "jq", "column", "fmt", "fold", "rev", "head", "tail", "wc", "grep", "nl", "tac", "cat" };
fn pure(line: []const u8) bool {
const name = commandName(line);
for (filters) |f| if (std.mem.eql(u8, f, name)) return true;
return false;
}
fn commandName(line: []const u8) []const u8 {
var words = std.mem.tokenizeAny(u8, line, " \t");
return words.next() orelse "";
}
/// The pipe prompt's live run, answered, for its field and `pane`'s text
/// as they are.
fn answered(p: *const Pardes, pane: *const Pane, line: []const u8) ?*const Pipe.PendingPipe {
const live_run = if (p.pipe.preview) |*l| l else return null;
if (live_run.serial != pane.serial or live_run.codes.len == 0 or !std.mem.eql(u8, live_run.typed, line)) return null;
if (pane.file == null or pane.file.?.revision != live_run.revision) return null;
return live_run;
}
/// Enter over runs that failed: refused once, the count saying what a
/// second Enter applies; refused for good when every run failed.
fn refuses(p: *Pardes, id: usize, pane: *Pane) bool {
const s = &p.view().tag_state;
if (s.prompt.op == .keep_pipe or s.prompt.op == .pipe_to) return false;
const live_run = answered(p, pane, s.field.text()) orelse return false;
var failed: usize = 0;
for (live_run.codes) |c| failed += @intFromBool(c != 0);
if (failed == 0) return false;
if (failed == live_run.codes.len) {
p.setMessage(.at(id), "every run failed: nothing to apply");
return true;
}
if (s.prompt.refused) return false;
s.prompt.refused = true;
return true;
}
/// Esc: the prompt goes and the body is as it was before it.
fn cancel(p: *Pardes, pane: *Pane) void {
const op = p.view().tag_state.prompt.op;
p.view().tag_state.kind = .rest;
TagState.toRest(p);
undo(p, pane, op);
}
/// The live effect of prompt `op` on `pane`'s body taken back.
fn undo(p: *Pardes, pane: *Pane, op: Op) void {
if (behavior(op) != null) Pipe.dropLive(p);
if (mode(op)) |m| _ = normal.applySelRegex(p, pane, &pane.body, "", m);
pane.nsel_snap = 0;
if (!searches(op)) return;
const set = &pane.places;
if (set.from == 0 and set.provenance == .typed) set.clear(p.gpa);
set.restore(p.settings.tab, pane);
set.forget(p.gpa);
}
/// The prompt left by something else than its keys (TagState.toRest: a
/// click, a word run from the band): its effect taken back, as Esc's.
pub fn leave(p: *Pardes) void {
const s = &p.view().tag_state;
const pane = p.panes[TagState.hostOf(p) orelse return] orelse return;
s.kind = .rest;
undo(p, pane, s.prompt.op);
}
/// A paste into the field: its first line.
pub fn paste(p: *Pardes, bytes: []const u8) void {
const s = &p.view().tag_state;
const pane = p.panes[TagState.hostOf(p) orelse return] orelse return;
const line = bytes[0 .. std.mem.indexOfAny(u8, bytes, "\r\n") orelse bytes.len];
s.field.insert(line[0..modal.graphemeStart(line, @min(line.len, Field.max - s.field.len))]);
s.prompt.recall = 0;
live(p, pane);
}
/// Whether `pane`'s body shows a selecting prompt's live result: its
/// selections drawn as a preview (body_layer), dimmed while the field is
/// no regex.
pub fn selecting(p: *const Pardes, pane: *const Pane) ?struct { dim: bool } {
const s = &p.view().tag_state;
if (s.kind != .prompt or mode(s.prompt.op) == null or s.host != pane.serial) return null;
return .{ .dim = s.prompt.bad };
}
/// Whether `pane`'s places are a search prompt's last good ones, its field
/// no regex now: tinted dimmed (Places.paint).
pub fn dims(p: *const Pardes, pane: *const Pane) bool {
const s = &p.view().tag_state;
return s.kind == .prompt and searches(s.prompt.op) and s.host == pane.serial and s.prompt.bad;
}
// ---- the recipe word (SPEC §7.5) ----
fn recipeOf(pane: *Pane) ?*Trail.Word {
for (pane.trail.steps[0..pane.trail.n]) |*step| if (step.* == .recipe) return &step.recipe;
return null;
}
/// Sam prompt `op`'s `line` as a link of `pane`'s recipe: after the one
/// its last sam prompt left open, else a recipe of its own in place of the
/// pane's one. One past the trail's room starts none.
fn link(p: *Pardes, pane: *Pane, op: Op, line: []const u8) void {
const s = &p.view().tag_state;
var buf: [Trail.max_text]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
const open_recipe = if (s.prompt.chain == pane.serial) recipeOf(pane) else null;
s.prompt.chain = 0;
(if (open_recipe) |r| w.writeAll(r.text.slice()) else w.writeAll("Edit")) catch return;
w.writeByte(' ') catch return;
const said = switch (op) {
.select => samWord(&w, 'x', line),
.split => samWord(&w, 'y', line),
.keep => samWord(&w, 'g', line),
.remove => samWord(&w, 'v', line),
.pipe => w.print("|{s}", .{line}),
.pipe_to => w.print(">{s}", .{line}),
else => return,
};
said catch return;
var word_: Trail.Word = .{};
word_.text.set(w.buffered());
pane.trail.setWord(.{ .recipe = word_ });
s.prompt.chain = pane.serial;
}
/// The selections a recipe's sam prompts made, kept for Look on its word.
fn keepSelections(p: *Pardes, pane: *Pane) void {
const text = edit.flatSurface(p.editor(), &pane.body) catch return;
var ranges: [Text.max_selections]modal.Selection = undefined;
const got = pane.body.ranges(text, 0, &ranges);
const kept = p.gpa.dupe(modal.Selection, ranges[0..got.n]) catch return;
p.gpa.free(pane.recipe_sels);
pane.recipe_sels = kept;
pane.recipe_pri = @intCast(got.pri);
}
/// Look on pane `id`'s recipe word: the selections it made, again.
pub fn lookRecipe(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
p.view().active = id;
if (pane.recipe_sels.len == 0) return;
const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(.at(id), "recipe", err);
for (pane.recipe_sels) |*r| {
r.anchor = @min(r.anchor, text.len);
r.head = @min(r.head, text.len);
}
pane.body.setRanges(p.settings.tab, text, pane.recipe_sels, &.{}, @min(pane.recipe_pri, pane.recipe_sels.len - 1), true);
pane.body.show(p.settings.tab);
}
/// Exec on it: the Edit line it is, run on what is selected now
/// (edit_cmd.zig, sam's dot the primary selection).
pub fn execRecipe(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const r = recipeOf(pane) orelse return;
var line: [Trail.max_text]u8 = undefined;
const text = r.text.slice();
@memcpy(line[0..text.len], text);
p.view().active = id;
pardes.edit_cmd.run(p, id, line["Edit ".len..text.len]);
}
// ---- the search word (SPEC §7.3) ----
/// Pane `pane`'s search word, `/re/ 3/7`: one a pane, its `index` the
/// length of its `/re/` with bit 16 set after n or N went round an end.
fn wordOf(pane: *Pane) ?*Trail.Search {
for (pane.trail.steps[0..pane.trail.n]) |*step| if (step.* == .search) return &step.search;
return null;
}
fn patternOf(w: *const Trail.Search) []const u8 {
const end = patternEnd(w);
return if (end < 2) "" else w.text.slice()[1 .. end - 1];
}
/// Where a search word's `/re/` ends: held to its text (a damaged image's
/// says anything).
fn patternEnd(w: *const Trail.Search) u16 {
return std.math.clamp(@as(u16, @truncate(w.index)), @min(2, w.text.len), w.text.len);
}
/// Whether the places the pane's body shows are its search word's.
fn lights(pane: *const Pane, w: *const Trail.Search) bool {
const set = &pane.places;
return set.shows(pane) and set.provenance == .search and !set.literal and std.mem.eql(u8, set.pattern, patternOf(w));
}
/// `pat`, delimited by `delim`, as pane `pane`'s one search word, in place
/// of the one it had, written for where its places stand, its start the
/// byte `from` of its text (UX L'1: a walk back onto it puts the caret
/// there).
fn word(p: *Pardes, pane: *Pane, delim: u8, pat: []const u8, from: usize) void {
// Its pattern and its place in the trail's room, else none.
if (pat.len + 2 + 32 > Trail.max_text) return;
const f = &pane.file.?;
var w: Trail.Search = .{};
_ = w.text.print("{c}{s}{c}", .{ delim, pat, delim });
w.index = w.text.len;
if (f.path.len <= Trail.max_text) if (File.lineIndex(p.gpa, f)) |index| {
const line = Places.lineOf(index, @min(from, f.content.len));
w.from = .{ .line = @intCast(line + 1), .col = @intCast(@min(from, f.content.len) - File.lineStart(p.gpa, f, line) + 1) };
w.from.path.set(f.path);
} else |_| {};
pane.trail.setWord(.{ .search = w });
refresh(pane, false);
}
/// The search word's place among its places written after its pattern:
/// `3/7`, `–/7` with the selection off them, `⋯` for the count while they
/// are found, ` ↻` after n or N went round an end (`wrapped`; null keeps
/// what it said).
fn refresh(pane: *Pane, wrapped: ?bool) void {
const w = wordOf(pane) orelse return;
if (!lights(pane, w)) return;
const set = &pane.places;
const f = &pane.file.?;
const end = patternEnd(w);
const round = wrapped orelse (w.index >> 16 != 0);
const hits = set.hits.items;
const sel = pane.body.primaryRange(f.content, 0);
const on: ?usize = if (set.current) |c| (if (c < hits.len and hits[c].start == @min(sel.anchor, sel.head) and hits[c].end == @max(sel.anchor, sel.head)) c else null) else null;
var buf: [48]u8 = undefined;
var out: std.Io.Writer = .fixed(&buf);
out.writeByte(' ') catch return;
if (on) |c| out.print("{d}", .{c + 1}) catch return else out.writeAll("–") catch return;
if (set.complete()) out.print("/{d}", .{hits.len}) catch return else out.writeAll("/⋯") catch return;
if (round) out.writeAll(" ↻") catch return;
const now = w.text.slice();
if (std.mem.eql(u8, now[end..], out.buffered()) and (w.index >> 16 != 0) == round) return;
var text: [Trail.max_text]u8 = undefined;
@memcpy(text[0..end], now[0..end]);
@memcpy(text[end..][0..out.buffered().len], out.buffered());
w.text.set(text[0 .. end + out.buffered().len]);
w.index = end | @as(u32, @intFromBool(round)) << 16;
}
/// After each step (Core.zig, beside the places'): every search word says
/// where its places stand; the live view's search prompt finds `?`'s place
/// and counts the lines its places are on once they are all found; its
/// `:theme ` previews its current row (Command.preview).
pub fn settle(p: *Pardes) void {
for (p.panes) |slot| if (slot) |pane| refresh(pane, null);
const s = &p.view().tag_state;
if (s.kind == .prompt and s.prompt.op == .command) Command.preview(p);
if (s.kind != .prompt or !searches(s.prompt.op)) return;
const pane = p.panes[TagState.hostOf(p) orelse return].?;
if (s.prompt.seeking) seekBack(p, pane);
const set = &pane.places;
if (!set.shows(pane) or !set.complete() or s.prompt.counted == set.hits_gen) return;
// A line holds the next place unless a newline lies between them: a
// pass over the text to the last place, once.
const text = pane.file.?.content;
var lines: u32 = 0;
var prev: ?usize = null;
for (set.hits.items) |h| {
if (prev == null or std.mem.indexOfScalarPos(u8, text[0..h.start], prev.?, '\n') != null) lines += 1;
prev = h.start;
}
s.prompt.lines = lines;
s.prompt.counted = set.hits_gen;
}
/// n or N stepped pane `id`'s places from place `before`: its search word
/// says where they stand, ` ↻` when the step went round an end, and the
/// message row echoes it with the line: `/dirty/ 4/7 · line 112`.
pub fn stepped(p: *Pardes, id: usize, forward: bool, before: ?usize) void {
const pane = p.panes[id] orelse return;
const w = wordOf(pane) orelse return;
const set = &pane.places;
if (!lights(pane, w)) return;
const after = set.current orelse return;
if (after >= set.hits.items.len) return;
refresh(pane, if (before) |b| (if (forward) after <= b else after >= b) else false);
const index = File.lineIndex(p.gpa, &pane.file.?) catch return;
var said: [Trail.max_text + 32]u8 = undefined;
p.setMessage(.at(id), std.fmt.bufPrint(&said, "{s} · line {d}", .{ w.text.slice(), Places.lineOf(index, set.hits.items[after].start) + 1 }) catch return);
}
/// `*`: pattern `pat`, the selection's (in `/` already), lights its places
/// in `pane`'s body and is its search word, no prompt asked (SPEC §7.3).
pub fn star(p: *Pardes, pane: *Pane, pat: []const u8) void {
const sel = pane.body.primaryRange(pane.file.?.content, 0);
pane.places.search(p, pane, .search, 0, pat, false, null, false);
word(p, pane, '/', pat, @min(sel.anchor, sel.head));
}
/// Look on pane `id`'s search word (SPEC §6.3): its places lit again and
/// the one it was on selected.
pub fn lookWord(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const w = wordOf(pane) orelse return;
const set = &pane.places;
light(p, id);
const rest = w.text.slice()[patternEnd(w)..];
const n = std.fmt.parseInt(usize, std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '/') orelse rest.len], " "), 10) catch return;
if (n > 0 and n <= set.hits.items.len) set.goTo(p.settings.tab, pane, n - 1, false);
}
/// Pane `id`'s search word's places lit again, `/` its pattern, the caret
/// where it is: a Look on the word, a walk onto it (Trail.walkFrom, the
/// caret where the search started, UX L'1).
pub fn light(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const w = wordOf(pane) orelse return;
const set = &pane.places;
const pat = patternOf(w);
p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err);
p.registers.last_search = '/';
set.search(p, pane, .search, 0, pat, false, null, false);
set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget);
p.view().active = id;
}
/// Exec on it: searched again from the caret, as its prompt and Enter
/// would, the next place when they are lit already (n).
pub fn execWord(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const w = wordOf(pane) orelse return;
const set = &pane.places;
const pat = patternOf(w);
p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err);
p.registers.last_search = '/';
p.view().active = id;
if (lights(pane, w)) {
const before = set.current;
set.step(p, pane, true, 1, false);
return stepped(p, id, true, before);
}
set.search(p, pane, .search, 0, pat, false, set.origin(pane), true);
}
/// The span of pane `pane`'s tag its search word takes while its places no
/// longer light it (the first Esc cleared them): drawn dimmed (draw.zig).
pub fn unlit(p: *const Pardes, pane: *Pane) ?[2]usize {
const t = &pane.trail;
const whole = pardes.tagline.folded(p, pane).whole;
for (t.steps[0..t.backs()], 0..) |*step, i| if (step.* == .search) {
if (lights(pane, &step.search) or t.isFolded(i, whole)) return null;
return t.spanOf(i, whole);
};
return null;
}
/// The gutter's marks while a prompt is typed (SPEC §7.1): `▸` on the
/// current place's line alone (`/
/// ?`); `┃` on each line the selections a sam prompt began with cover (`s
/// S K A-K`), its scope. In the blank after a row's line number, on a
/// line's first row.
pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void {
const ts = &p.view().tag_state;
if (ts.kind != .prompt or ts.host != pane.serial) return;
const f = &(pane.file orelse return);
if (mode(ts.prompt.op) != null) return fence(p, s, pane, r, body_h);
if (!searches(ts.prompt.op)) return;
const set = &pane.places;
if (!set.shows(pane)) return;
const hits = set.hits.items;
if (hits.len == 0) return;
const tab = p.settings.tab;
const x = gutterX(pane, r);
const y = p.bodyTop(pane, r);
const ink = p.chrome().page.key;
const nlines = File.nlines(p.gpa, f);
// `▸` on the current place's line alone: the lines with places are the
// rail's ticks (Places.addTicks), never glyphs of their own (UX D14).
const c = set.current orelse return;
if (c >= hits.len) return;
var last: i32 = -1;
var vr: u16 = 0;
while (vr < body_h) : (vr += 1) {
const line = pane.wrapAt(tab, vr).line;
if (line == last or line < 0) continue;
if (line >= nlines) break;
last = line;
const ls = File.lineStart(p.gpa, f, @intCast(line));
const next = File.lineStart(p.gpa, f, @intCast(line + 1));
if (hits[c].start < ls or hits[c].start >= @max(next, ls + 1)) continue;
var style = s.at(x, y + vr).style;
style.fg = .{ .rgb = ink };
s.set(x, y + vr, "▸", style);
return;
}
}
fn regexMessage(pat: []const u8) []const u8 {
return if (regexp.Regex.compile(pat)) |_| "" else |err| regexp.Regex.message(err);
}
/// The sam command a pattern prompt is (`s S K A-K` are sam's `x y g v`),
/// its `/` written `\/`.
fn samWord(w: *std.Io.Writer, c: u8, pat: []const u8) !void {
try w.print("{c}/", .{c});
for (pat) |b| if (b == '/') try w.writeAll("\\/") else try w.writeByte(b);
try w.writeByte('/');
}
/// The plain word prompt `op` with field `line` stands for: what Look or
/// Exec would do typed in a tag. None for `! A-! $`, which sam cannot say.
fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 {
switch (op) {
.search => try w.print("/{s}/", .{line}),
.search_back => try w.print("?{s}?", .{line}),
.select, .split, .keep, .remove => {
try w.writeAll("Edit ");
try samWord(w, switch (op) {
.select => 'x',
.split => 'y',
.keep => 'g',
else => 'v',
}, line);
},
.pipe => try w.print("Edit |{s}", .{line}),
.pipe_to => try w.print("Edit >{s}", .{line}),
.insert, .append, .keep_pipe => return null,
.command => return null, // Command.plainWord, which reads the rows
}
return if (op == .search or op == .search_back) "Look" else "Exec";
}
/// A pipe prompt's live run in pane `pane`'s body, its rows painted in `s`
/// (joinBody's): each replaced selection's lines on the diff's deleted
/// ground, its run's output after them as ghost lines on the added ground
/// (`!` before them, `A-!` after, the text kept), the rows below pushed
/// down and the last ones off the view. Drawn, never written (the
/// coordinator's R3); a run that failed shows nothing.
pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: pardes.Rect, body_h: u16) !void {
const ts = &p.view().tag_state;
if (ts.kind != .prompt or ts.host != pane.serial) return;
const how = behavior(ts.prompt.op) orelse return;
if (how == .ignore or how == .keep) return;
const live_run = answered(p, pane, ts.field.text()) orelse return;
const f = &pane.file.?;
const tab = p.settings.tab;
const index = try File.lineIndex(p.gpa, f);
const y0 = p.bodyTop(pane, r);
const rows: usize = @min(body_h, s.rows -| y0);
const first: usize = pane.context_rows;
if (rows <= first) return;
const w: usize = s.cols;
const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]);
const chrome = p.chrome();
const ink = chrome.page.text;
const x0 = r.x + config.GUTTER + File.gutterWidth(pane);
const width = r.w -| (x0 - r.x);
const ranges = live_run.ranges[0..live_run.nranges];
var out: usize = first;
var k: usize = 0;
var vr: usize = first;
while (vr < rows and out < rows) : (vr += 1) {
const line: usize = @intCast(@max(0, pane.wrapAt(tab, @intCast(vr)).line));
const opens = vr == first or pane.wrapAt(tab, @intCast(vr - 1)).line != line;
const closes = vr + 1 >= rows or pane.wrapAt(tab, @intCast(vr + 1)).line != line;
while (k < ranges.len and lineAt(index, @max(ranges[k].anchor, ranges[k].head) -| 1) < line) k += 1;
// `!`: its output before the selection's first line.
var j = k;
if (how == .insert and opens) while (j < ranges.len and lineAt(index, @min(ranges[j].anchor, ranges[j].head)) == line) : (j += 1) {
out = ghostRows(s, live_run, j, out, rows, y0, x0, width, chrome.add.row, ink);
};
if (out >= rows) break;
@memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]);
j = k;
while (j < ranges.len and lineAt(index, @min(ranges[j].anchor, ranges[j].head)) <= line) : (j += 1) {
if (how == .replace and outcome(live_run, j) == 0) s.tint(x0, @intCast(y0 + out), width, chrome.del.row, null);
}
out += 1;
// `|` and `A-!`: after the selection's last line.
if (how != .insert and closes) while (k < ranges.len and lineAt(index, @max(ranges[k].anchor, ranges[k].head) -| 1) == line) : (k += 1) {
out = ghostRows(s, live_run, k, out, rows, y0, x0, width, chrome.add.row, ink);
};
}
// What was pushed past the view leaves blank rows behind it, none.
}
fn lineAt(index: []const usize, at: usize) usize {
return Places.lineOf(index, at);
}
/// Run `i`'s exit status (`!` and `A-!` run once for them all).
fn outcome(live_run: *const Pipe.PendingPipe, i: usize) u8 {
return live_run.codes[if (live_run.how.pipes()) i else 0];
}
/// Range `i`'s output as ghost rows from body row `out`, the rows it
/// reaches; none for a run that failed.
fn ghostRows(s: *Surface, live_run: *const Pipe.PendingPipe, i: usize, out_: usize, rows: usize, y0: usize, x0: u16, width: u16, ground: [3]u8, ink: [3]u8) usize {
if (outcome(live_run, i) != 0) return out_;
var out = out_;
const text = live_run.outs[if (live_run.how.pipes()) i else 0];
var lines = std.mem.splitScalar(u8, if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text, '\n');
while (lines.next()) |l| {
if (out >= rows) break;
const y: u16 = @intCast(y0 + out);
s.fill(0, y, @intCast(s.cols), 1, .{});
s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = ground } });
_ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = ground } });
out += 1;
}
return out;
}
/// The x of the blank after pane `pane`'s line numbers.
fn gutterX(pane: *const Pane, r: pardes.Rect) u16 {
return r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1);
}
/// `┃` on the lines the selections a sam prompt began with cover, and
/// the ones `K` or `A-K` would drop dimmed and struck through.
fn fence(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void {
const f = &pane.file.?;
const tab = p.settings.tab;
const snap = pane.sel_snap[0..pane.nsel_snap];
if (snap.len == 0) return;
const x = gutterX(pane, r);
const y = p.bodyTop(pane, r);
const ink = p.chrome().page.key;
const nlines = File.nlines(p.gpa, f);
const op = p.view().tag_state.prompt.op;
var kept: [Text.max_selections]modal.Selection = undefined;
const now = if (op == .keep or op == .remove) pane.body.ranges(f.content, 0, &kept).n else 0;
var last: i32 = -1;
var vr: u16 = 0;
while (vr < body_h) : (vr += 1) {
const line = pane.wrapAt(tab, vr).line;
if (line == last or line < 0) continue;
if (line >= nlines) break;
last = line;
const ls = File.lineStart(p.gpa, f, @intCast(line));
const le = File.lineStart(p.gpa, f, @intCast(line + 1));
// The ranges are in the text's order: the first ending past the
// line's start, on while they start before its end.
var i = endingPast(snap, ls);
if (i < snap.len and @min(snap[i].anchor, snap[i].head) < @max(le, ls + 1)) {
var style = s.at(x, y + vr).style;
style.fg = .{ .rgb = ink };
s.set(x, y + vr, "┃", style);
}
// K and A-K: the selections that would go, on this line.
if (op != .keep and op != .remove) continue;
while (i < snap.len and @min(snap[i].anchor, snap[i].head) < le) : (i += 1) {
const lo = @min(snap[i].anchor, snap[i].head);
const hi = @max(snap[i].anchor, snap[i].head);
const k = endingPast(kept[0..now], lo);
const stays = k < now and @min(kept[k].anchor, kept[k].head) == lo and @max(kept[k].anchor, kept[k].head) == hi;
if (!stays) strike(p, s, pane, r, line, @intCast(@max(lo, ls) - ls), @intCast(@min(hi, le) - ls));
}
}
}
/// The first of `ranges` (in the text's order) ending past byte `at`.
fn endingPast(ranges: []const modal.Selection, at: usize) usize {
return std.sort.partitionPoint(modal.Selection, ranges, at, struct {
fn before(byte: usize, r: modal.Selection) bool {
return @max(r.anchor, r.head) <= byte;
}
}.before);
}
/// Bytes [lo, hi) of `line`, as many of its rows as show them, dimmed and
/// struck through (File.paintWordSelection's walk).
fn strike(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, line: i32, lo_: i32, hi_: i32) void {
const tab = p.settings.tab;
const tw = r.w - config.GUTTER;
const prefix: i32 = File.gutterWidth(pane);
const body_y = p.bodyTop(pane, r);
var vr: i32 = 0;
while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) {
const here = pane.wrapAt(tab, vr);
if (here.line != line) continue;
var hi = hi_;
const next = pane.wrapAt(tab, vr + 1);
if (next.line == line) hi = @min(hi, next.at);
const lo = @max(lo_, here.at);
if (hi <= lo) continue;
const c0 = prefix + here.pad + File.displayOffset(tab, pane, line, here.at, lo);
const c1 = prefix + here.pad + File.displayEndOffset(tab, pane, line, here.at, hi - 1);
var col = @max(prefix, c0);
while (col <= c1 and col < tw) : (col += 1) {
const style = &s.at(r.x + config.GUTTER + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))).style;
style.dim = true;
style.strikethrough = true;
}
}
}
/// The head of the prompt's tag: `s self▌ = Exec Edit x/self/ 4
/// selections in 6 lines ⏎ select · M-⏎ as a list · C-r history · esc`.
pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !TagState.Head {
const s = &p.view().tag_state;
const pr = &s.prompt;
var b = try TagState.Builder.of(p, arena, pane);
const text = &b.text;
const spans = &b.spans;
try styled(arena, text, spans, info.get(pr.op).cell, .key);
try text.append(arena, ' ');
const caret: u32 = @intCast(text.items.len + s.field.caret);
const line = s.field.text();
try text.appendSlice(arena, line);
if (line.len > 0) {
var buf: [Field.max + 16]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
const said = if (pr.op == .command) Command.plainWord(p, &w, line) else plainWord(&w, pr.op, line) catch null;
if (said) |verb| {
try styled(arena, text, spans, try std.fmt.allocPrint(arena, " = {s}", .{verb}), .dim);
try text.print(arena, " {s}", .{w.buffered()});
}
}
// The count and the hints at the row's right end (UX D3).
const left = b.col();
const at = text.items.len;
// Where a search's ` · N lines` starts after its count: dim, and gone
// with the hints (UX E7).
var tail: ?usize = null;
if (line.len > 0) {
// A pattern that is no regex: why, in the err ink, in place of the
// hints (UX D14), what is shown meanwhile dim; in the count's place,
// which never drops.
if (pr.bad) {
try styled(arena, text, spans, regexMessage(line), .err);
try styled(arena, text, spans, try std.fmt.allocPrint(arena, " · the {d} from before shown, dimmed", .{@as(usize, pane.body.nsel) + 1}), .dim);
try b.right(at, text.items.len);
return .{ .text = text.items, .spans = spans.items, .cells = 1, .caret = caret };
} else if (behavior(pr.op) != null) {
try pipeCount(p, arena, text, spans, pane, pr, line);
} else tail = try count(arena, text, pane, pr);
}
if (pr.op == .command) try Command.count(p, arena, text);
const hints = text.items.len;
const hint = info.get(pr.op).hint;
if (tail) |t| {
// Both beside the count, or neither: as much room as the right
// block asks for its two gaps (Builder.right drops the hints alone).
const cells = File.displayWidth(p.settings.tab, std.mem.trimStart(u8, text.items[at..], " ")) + File.displayWidth(p.settings.tab, hint);
if (left + 2 + cells + 2 > b.width) {
text.shrinkRetainingCapacity(t);
try b.right(at, t);
return .{ .text = text.items, .spans = spans.items, .cells = 1, .caret = caret };
}
try spans.append(arena, .{ .lo = @intCast(t), .hi = @intCast(hints), .style = .dim });
}
try styled(arena, text, spans, hint, .dim);
try b.right(at, hints);
return .{ .text = text.items, .spans = spans.items, .cells = 1, .caret = caret };
}
fn styled(arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayList(TagState.Span), s: []const u8, style: TagState.Style) !void {
const lo: u32 = @intCast(text.items.len);
try text.appendSlice(arena, s);
try spans.append(arena, .{ .lo = lo, .hi = @intCast(text.items.len), .style = style });
}
/// The prompt's count after its field: what it found (`4 selections in 6
/// lines`, `keeps 3 of 9`, `3/7 · 5 lines`, `1/7 ↻ · 5 lines`, `3/⋯` while
/// its places are found, `0`); where a search's ` · N lines` starts.
fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *Pane, pr: *const Prompt) !?usize {
switch (pr.op) {
.search, .search_back => {
const set = &pane.places;
if (!set.shows(pane)) return null;
const hits = set.hits.items;
if (set.complete() and hits.len == 0) {
try text.appendSlice(arena, " 0");
return null;
}
try text.appendSlice(arena, " ");
const at = if (set.current) |c| (if (c < hits.len) c else null) else null;
if (at) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–");
if (!set.complete()) {
try text.appendSlice(arena, "/⋯");
return null;
}
try text.print(arena, "/{d}", .{hits.len});
// Round the end from where it began.
if (at) |c| {
const origin = set.origin(pane);
if (if (pr.op == .search) hits[c].start < origin else hits[c].start > origin) try text.appendSlice(arena, " ↻");
}
const tail = text.items.len;
try text.print(arena, " · {d} line{s}", .{ pr.lines, plural(pr.lines) });
return tail;
},
.select, .split => if (pr.found == 0)
try text.appendSlice(arena, " 0")
else
try text.print(arena, " {d} selection{s} in {d} line{s}", .{ pr.found, plural(pr.found), pr.scope, plural(pr.scope) }),
.keep, .remove => try text.print(arena, " keeps {d} of {d}", .{ pr.found, pane.nsel_snap }),
else => {},
}
return null;
}
/// A pipe prompt's count: `6 lines → 5 · exit 0`, `6 runs · 5 ok · 1 exit 2
/// <its stderr's first line>`, `keeps 4 of 6`, `⋯` while it runs, or why
/// it does not run live.
fn pipeCount(p: *const Pardes, arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayList(TagState.Span), pane: *const Pane, pr: *const Prompt, line: []const u8) !void {
if (!pr.forced and !pure(line)) {
try text.appendSlice(arena, " ");
try styled(arena, text, spans, commandName(line), .err);
return text.appendSlice(arena, " isn't a known filter · C-p runs it");
}
const live_run = answered(p, pane, line) orelse return text.appendSlice(arena, " ⋯");
const n = live_run.codes.len;
var ok: usize = 0;
var bad: ?usize = null;
for (live_run.codes, 0..) |c, i| {
if (c == 0) ok += 1 else if (bad == null) bad = i;
}
if (pr.op == .keep_pipe) return text.print(arena, " keeps {d} of {d}", .{ ok, n });
if (bad) |i| {
const err = live_run.errs[i];
try text.print(arena, " {d} run{s} · {d} ok · {d} exit {d} ", .{ n, plural(n), ok, n - ok, live_run.codes[i] });
try styled(arena, text, spans, err[0 .. std.mem.indexOfScalar(u8, err, '\n') orelse err.len], .err);
if (pr.refused and ok > 0) try text.print(arena, " — ⏎ again applies the {d} that worked", .{ok});
return;
}
if (pr.op == .pipe_to) return text.print(arena, " {d} run{s} · output below, the text stays", .{ n, plural(n) });
var in: usize = 0;
for (live_run.inputs) |input| in += lineCount(input);
var out: usize = 0;
for (live_run.outs) |o| out += lineCount(o);
try text.print(arena, " {d} line{s} → {d} · exit 0", .{ in, plural(in), out });
}
fn lineCount(s: []const u8) usize {
if (s.len == 0) return 0;
return std.mem.count(u8, s, "\n") + @intFromBool(s[s.len - 1] != '\n');
}
fn plural(n: usize) []const u8 {
return if (n == 1) "" else "s";
}
/// The rows the prompt's band takes: its history unrolled (Ctrl-r), the
/// lines the field is in, eleven at most.
pub fn takes(p: *Pardes) u16 {
const s = &p.view().tag_state;
const rows = historyRows(ring(p, s.prompt.op), s.field.text());
if (s.prompt.op == .command) return @max(Command.takes(p), if (s.prompt.history) rows else 0);
if (s.prompt.op == .pipe_to) if (p.panes[TagState.hostOf(p) orelse return 0]) |pane| if (answered(p, pane, s.field.text())) |l|
return @max(runRows(l), if (s.prompt.history) rows else 0);
if (!s.prompt.history) return 0;
return rows;
}
/// `A-|`'s runs as rows: each `#1 exit 0`, then its output's lines.
fn runRows(l: *const Pipe.PendingPipe) u16 {
var n: usize = 0;
for (l.outs) |o| n += 1 + lineCount(o);
return @intCast(@min(Band.Cursor.shown, n));
}
/// The rows history `r` unrolled takes: its lines holding `q`, one at
/// least, eleven at most.
pub fn historyRows(r: *const Ring, q: []const u8) u16 {
var n: u16 = 0;
for (r.lines[0..r.n]) |l| {
if (std.mem.indexOf(u8, l.slice(), q) != null) n += 1;
}
return @max(1, @min(Band.Cursor.shown, n));
}
/// The prompt's steps in its band: its history, newest first, the lines
/// holding the field, its cursor on one.
pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: *[Band.max_steps]Band.Step) ![]Band.Step {
const s = &p.view().tag_state;
var made: usize = 0;
// `:`'s history before its rows and their doc, which takes the width
// left after the others.
const r = ring(p, s.prompt.op);
if (s.prompt.op == .command) {
if (s.prompt.history) made = try historyStep(arena, r, s.field.text(), s.prompt.recall, &out[0]);
return out[0 .. made + try Command.steps(p, arena, out[made..])];
}
if (s.prompt.op == .pipe_to) if (p.panes[TagState.hostOf(p) orelse return out[0..0]]) |pane| if (answered(p, pane, s.field.text())) |l| {
var rows: std.ArrayList(Band.Row) = .empty;
for (l.outs, l.codes, 0..) |o, c, i| {
if (rows.items.len >= Band.Cursor.shown) break;
const said = try std.fmt.allocPrint(arena, "#{d} exit {d}", .{ i + 1, c });
try rows.append(arena, .{ .text = said, .key = @intCast(said.len) });
var lines = std.mem.splitScalar(u8, if (c == 0) o else l.errs[i], '\n');
while (lines.next()) |line| {
if (rows.items.len >= Band.Cursor.shown) break;
if (line.len > 0) try rows.append(arena, .{ .text = line });
}
}
out[made] = .{ .rows = rows.items, .doc = true };
made += 1;
};
if (!s.prompt.history) return out[0..made];
return out[0 .. made + try historyStep(arena, r, s.field.text(), s.prompt.recall, &out[made])];
}
/// The line of history `r` the cursor of it unrolled is on: the one the
/// keys moved to (`recall`), else the newest holding the field `q`; 0
/// with none.
pub fn historyAt(r: *const Ring, q: []const u8, recall: u8) u8 {
if (recall != 0) return recall;
var back: u8 = 1;
while (back <= r.n) : (back += 1) {
if (std.mem.indexOf(u8, r.get(back).?, q) != null) return back;
}
return 0;
}
/// Down and Ctrl-n, Up and Ctrl-p in history `r` unrolled (UX D5: a list
/// like any other): its cursor `recall` to the next line it shows, older
/// or newer, the field `q` kept as typed; true when the key was one.
pub fn historyKey(r: *const Ring, q: []const u8, recall: *u8, k: Key) bool {
const plain = !k.ctrl and !k.alt;
const ctrl = k.ctrl and !k.alt;
const down = (plain and k.cp == Key.down) or (ctrl and k.cp == 'n');
const up = (plain and k.cp == Key.up) or (ctrl and k.cp == 'p');
if (!down and !up) return false;
const at = historyAt(r, q, recall.*);
var newer: u8 = 0;
var older: u8 = 0;
var rows: usize = 0;
var back: u8 = 1;
while (back <= r.n and rows < Band.Cursor.shown) : (back += 1) {
if (std.mem.indexOf(u8, r.get(back).?, q) == null) continue;
rows += 1;
if (back < at) newer = back;
if (back > at and older == 0) older = back;
}
const to = if (down) older else newer;
if (to != 0) recall.* = to;
return true;
}
/// A history step's row's index: its line's place in the ring with this
/// bit, which a click tells from the other steps' rows (Command.point).
pub const history_row: u16 = 0x8000;
/// History `r`'s step (Ctrl-r): its lines newest first, those holding the
/// field `q`, its cursor on one.
pub fn historyStep(arena: std.mem.Allocator, r: *const Ring, q: []const u8, recall: u8, out: *Band.Step) !usize {
var rows: std.ArrayList(Band.Row) = .empty;
const at = historyAt(r, q, recall);
var back: u8 = 1;
while (back <= r.n and rows.items.len < Band.Cursor.shown) : (back += 1) {
const l = r.get(back).?;
if (std.mem.indexOf(u8, l, q) == null) continue;
try rows.append(arena, .{ .text = l, .on = back == at, .index = history_row | back });
}
if (rows.items.len == 0) try rows.append(arena, .{ .text = if (r.n == 0) "no history yet" else "no line holds it", .dim = true });
out.* = .{ .rows = rows.items };
return 1;
}
fn typeKeys(p: *Pardes, keys: []const u8) void {
for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
}
fn tagOf(p: *Pardes) ![]const u8 {
return tagline.tagText(p, p.scratch.allocator(), p.panes[p.view().active].?);
}
/// The head under the active pane's tag (UX DESIGN M2); none at rest.
fn headOf(p: *Pardes) ![]const u8 {
const h = try TagState.head(p, p.scratch.allocator(), p.panes[p.view().active].?);
return if (h) |made| made.text else "";
}
/// Whether `needle` is in `hay`, a run of two spaces or more in either read
/// as two: a right block's padding is its row's (UX D3).
fn has(hay: []const u8, needle: []const u8) bool {
var in: [8192]u8 = undefined;
var of: [1024]u8 = undefined;
return std.mem.indexOf(u8, squeezed(hay, &in), squeezed(needle, &of)) != null;
}
fn squeezed(s: []const u8, buf: []u8) []const u8 {
var n: usize = 0;
for (s, 0..) |c, i| {
if (c == ' ' and i >= 2 and s[i - 1] == ' ' and s[i - 2] == ' ') continue;
buf[n] = c;
n += 1;
}
return buf[0..n];
}
test "s asks in the tag's head: its key cell, the field, the plain word and the count, the selections live in the body; no match is 0, a pattern that is no regex keeps the last result dimmed and says why, Esc puts them back" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n");
const rest = try std.testing.allocator.dupe(u8, try tagOf(p));
defer std.testing.allocator.free(rest);
typeKeys(p, "%s");
try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind);
// No chip on the notice band: the prompt is the tag's.
try std.testing.expectEqual(Pane.Prompt.none, pane.prompt);
try std.testing.expect(has(try headOf(p), "s ⏎ select · M-⏎ as a list · C-r history · esc"));
typeKeys(p, "self");
try std.testing.expect(has(try headOf(p), "s self = Exec Edit x/self/ 2 selections in 3 lines ⏎ select"));
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expect(selecting(p, pane).?.dim == false);
// No match: 0, and the selection it began with.
typeKeys(p, "x");
try std.testing.expect(has(try headOf(p), "= Exec Edit x/selfx/ 0 "));
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
p.update(.{ .key = .{ .cp = Key.backspace } });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
// No regex: the two from before, dimmed, and why.
typeKeys(p, "(");
// Its reason in place of the hints (UX D14), what follows it dim.
try std.testing.expect(std.mem.endsWith(u8, try headOf(p), " bad regular expression · the 2 from before shown, dimmed"));
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expect(selecting(p, pane).?.dim);
// Esc: rest, the tag and the selection as they were.
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqualStrings(rest, try tagOf(p));
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
const r = pane.body.primaryRange(pane.file.?.content, 0);
try std.testing.expectEqual(pane.file.?.content.len, @max(r.anchor, r.head));
try std.testing.expect(selecting(p, pane) == null);
}
test "Enter keeps what s found, the pattern in / and in the history Up brings back; K keeps, counted; a pipe from the body asks in the tag and runs off the loop" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n");
typeKeys(p, "%sself..");
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expectEqualStrings("self..", p.registers.value('/', 0).?);
try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(1).?);
// K over the two: Up brings `self..` back, `b` keeps one of them.
typeKeys(p, "K");
p.update(.{ .key = .{ .cp = Key.up } });
try std.testing.expectEqualStrings("self..", p.view().tag_state.field.text());
try std.testing.expect(has(try headOf(p), "K self.. = Exec Edit g/self../ keeps 2 of 2"));
p.update(.{ .key = .{ .cp = Key.down } });
typeKeys(p, "b");
try std.testing.expect(has(try headOf(p), "K b = Exec Edit g/b/ keeps 1 of 2 ⏎ keep"));
// Ctrl-r: the history under the tag, a row a line.
p.update(.{ .key = .{ .cp = 'r', .ctrl = true } });
try std.testing.expectEqual(@as(u16, 1), Band.takes(p, p.view().active));
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
try std.testing.expectEqualStrings("b", p.prompt_history.search.get(1).?);
try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(2).?);
// | from the body: in the tag, the plain word Edit's, Enter pipes.
typeKeys(p, "|");
try std.testing.expectEqual(Pane.Prompt.none, pane.prompt);
p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
try std.testing.expect(has(try headOf(p), "| tr a-z A-Z = Exec Edit |tr a-z A-Z ⋯ ⏎ replace"));
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqualStrings("tr a-z A-Z", p.registers.value('|', 0).?);
var asked: ?u32 = null;
while (p.nextEffect()) |effect| if (effect == .pipe) {
asked = effect.pipe.id;
};
const request = p.pipe.pipeRequest(asked orelse return error.MissingPipeEffect).?;
try std.testing.expectEqualStrings("tr a-z A-Z", request.command);
try std.testing.expectEqualSlices(u8, "self.b", request.inputs[0]);
// Esc in a pipe's prompt applies nothing: the live run dropped.
typeKeys(p, "|cat");
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(p.pipe.preview == null);
}
const dirty = "dirty one\nclean\ndirty two dirty\nclean\ndirty three\ndirty four dirty\nclean\ndirty five\n";
/// The glyph in the blank after the line number of body row `row`.
fn gutterAt(p: *Pardes, arena: std.mem.Allocator, row: u16) ![]const u8 {
p.sync();
const s = try p.render(arena);
const pane = p.panes[0].?;
const r = p.view().rects[0];
const x = r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1);
return s.at(x, p.bodyTop(pane, r) + row).grapheme();
}
test "/ searches the body as it is typed: the current place selected, `▸` in the key ink on its line alone (the others are the rail's ticks), the places on the hit ground, counted 3/7 · 5 lines; Enter folds /dirty/ 3/7 into the trail; n says where it went, round the end too; the first Esc clears the tints and dims the word, Look on it lights them again (UX D14)" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const pane = try p.setTestFile(dirty);
pane.body.cur_row = 2;
pane.body.cur_col = 6;
typeKeys(p, "/dirty");
try std.testing.expect(has(try headOf(p), "/ dirty = Look /dirty/ 3/7 · 5 lines ⏎ land · M-⏎ as a list"));
try std.testing.expectEqual(@as(?usize, 2), pane.places.current);
// (Its first row under the head's, UX DESIGN M2.)
try std.testing.expectEqualStrings(" ", try gutterAt(p, frame.allocator(), 1));
try std.testing.expectEqualStrings("▸", try gutterAt(p, frame.allocator(), 2));
try std.testing.expectEqualStrings(" ", try gutterAt(p, frame.allocator(), 7));
{
const s = try p.render(frame.allocator());
const r = p.view().rects[0];
const c = p.chrome();
const x = r.x + config.GUTTER + File.gutterWidth(pane);
const y = p.bodyTop(pane, r);
try std.testing.expectEqual(pardes.Color{ .rgb = c.page.key }, s.at(x - 1 - File.laneCells(pane) - pane.layers.heat, y + 2).style.fg);
// Line 5's place (`dirty` at its start) on the hit ground (line 1's
// under the head's row, UX DESIGN M2).
try std.testing.expectEqual(pardes.Color{ .rgb = c.hit }, s.at(x, y + 4).style.bg);
}
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 3/7 › /test.txt "));
try std.testing.expectEqualStrings("dirty", p.registers.value('/', 0).?);
try std.testing.expectEqualStrings(" ", try gutterAt(p, frame.allocator(), 0));
// n: the word in place, and the line said.
typeKeys(p, "n");
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 4/7 › "));
try std.testing.expect(has(p.messages.saidBy(pane), "/dirty/ 4/7 · line 5"));
typeKeys(p, "nnnn");
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 1/7 ↻ › "));
// Esc: the tints go, the word stays, dimmed; Look on it lights them
// again, the place it was on selected.
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(!pane.places.started);
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 1/7 ↻ › "));
try std.testing.expect(unlit(p, pane) != null);
typeKeys(p, "j");
Trail.lookStep(p, 0, 0);
try std.testing.expect(pane.places.started and unlit(p, pane) == null);
try std.testing.expectEqual(@as(?usize, 0), pane.places.current);
const sel = pane.body.primaryRange(pane.file.?.content, 0);
try std.testing.expectEqual(@as(usize, 0), @min(sel.anchor, sel.head));
// Off a place: –/7.
typeKeys(p, "j");
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ –/7"));
// One search word a pane: a new search takes its place.
typeKeys(p, "gg/clean");
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/clean/ 1/3 › /test.txt "));
try std.testing.expectEqual(@as(u8, 1), pane.trail.n);
}
test "? searches back from the caret; no match is 0; a pattern that is no regex keeps the last places dimmed; Esc puts the body back; * makes the search word with no prompt" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile(dirty);
pane.body.cur_row = 2;
pane.body.cur_col = 6;
const was = pane.body.primaryRange(pane.file.?.content, 0);
typeKeys(p, "?dirty");
try std.testing.expect(has(try headOf(p), "? dirty = Look ?dirty? 2/7 · 5 lines ⏎ land"));
typeKeys(p, "x");
try std.testing.expect(has(try headOf(p), "= Look ?dirtyx? 0 ⏎ land"));
try std.testing.expectEqualDeep(was, pane.body.primaryRange(pane.file.?.content, 0));
p.update(.{ .key = .{ .cp = Key.backspace } });
typeKeys(p, "(");
try std.testing.expect(has(try headOf(p), " bad regular expression · "));
try std.testing.expect(dims(p, pane) and pane.places.started);
try std.testing.expectEqualStrings("dirty", pane.places.pattern);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(!pane.places.started);
try std.testing.expectEqualDeep(was, pane.body.primaryRange(pane.file.?.content, 0));
try std.testing.expectEqual(@as(u8, 0), pane.trail.n);
// `*` on `dirty` at the top: its places, its word, no prompt.
typeKeys(p, "gge*");
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/\\bdirty\\b/ 1/7 › "));
}
test "sam prompts one after another make one recipe word, the Edit line it is; a motion ends it and the next starts the pane's one again; ! adds nothing; the scope fenced in the gutter, what K drops struck; Look puts its selections back, Exec runs it as Edit" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n");
typeKeys(p, "%sother");
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/other/ › /test.txt "));
// Look on it: the selection it made, again.
typeKeys(p, "gg");
Trail.lookStep(p, 0, 0);
const back = pane.body.primaryRange(pane.file.?.content, 0);
try std.testing.expectEqual(@as(usize, 24), @min(back.anchor, back.head));
try std.testing.expectEqual(@as(usize, 29), @max(back.anchor, back.head));
// A motion ends it: the next s is a recipe of its own, the pane's one.
typeKeys(p, "j%sself..");
// (Its first row under the head's, UX DESIGN M2.)
for ([_]u16{ 1, 2 }) |row| try std.testing.expectEqualStrings("┃", try gutterAt(p, frame.allocator(), row));
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ › /test.txt "));
try std.testing.expectEqual(@as(u8, 1), pane.trail.n);
// K right after: `self.b` would go, struck through.
typeKeys(p, "Ka");
p.sync();
const s = try p.render(frame.allocator());
const r = p.view().rects[0];
const cell = s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r) + 1);
try std.testing.expect(cell.style.strikethrough and cell.style.dim);
try std.testing.expect(!s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r)).style.strikethrough);
p.update(.{ .key = .{ .cp = Key.enter } });
typeKeys(p, "|");
p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt "));
// `!` applies and adds nothing: an Edit line cannot say it.
typeKeys(p, "!");
p.update(.{ .key = .{ .cp = 'e', .text = "echo" } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt "));
while (p.nextEffect()) |_| {}
if (p.pipe.wait) |*w| w.deinit();
p.pipe.wait = null;
// Exec on it: Edit runs it, its command off the loop.
typeKeys(p, "%");
Trail.execStep(p, 0, 0);
try std.testing.expect(p.pipe.edit_run != null);
}
/// The pipe request the last key made, its id.
fn lastPipe(p: *Pardes) ?u32 {
var id: ?u32 = null;
while (p.nextEffect()) |effect| if (effect == .pipe) {
id = effect.pipe.id;
};
return id;
}
test "a pipe prompt runs a known filter live, a run a selection: the outputs ghost lines under the lines they replace, counted; one no filter waits for C-p; Enter over runs that failed is refused once, then applies the ones that worked; when every run failed nothing" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile("b\na\nc\n");
typeKeys(p, "%s[ab]");
p.update(.{ .key = .{ .cp = Key.enter } });
typeKeys(p, "|");
p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
try std.testing.expect(has(try headOf(p), "| tr a-z A-Z = Exec Edit |tr a-z A-Z ⋯ ⏎ replace"));
const first = lastPipe(p) orelse return error.MissingLiveRun;
const asked = p.pipe.pipeRequest(first).?;
try std.testing.expectEqual(@as(usize, 2), asked.inputs.len);
try std.testing.expect(has(asked.command, "tr a-z A-Z") and has(asked.command, "\\036"));
p.update(.{ .pipe_resp = .{ .id = first, .success = true, .outputs = &.{ "B\x1e\x1e0", "A\x1e\x1e0" } } });
try std.testing.expect(has(try headOf(p), " 2 lines → 2 · exit 0 ⏎ replace"));
// The body: each output a ghost line under the line it replaces, the
// rows below pushed down; the text as it was; its first row under the
// head's (UX DESIGN M2).
p.sync();
const s = try p.render(frame.allocator());
const r = p.view().rects[0];
const x = r.x + config.GUTTER + File.gutterWidth(pane);
const y = p.bodyTop(pane, r);
for ([_][]const u8{ "B", "a", "A", "c" }, 1..) |want, row| try std.testing.expectEqualStrings(want, s.at(x, y + @as(u16, @intCast(row))).grapheme());
// On the chrome's diff rows (R10), the ghost in the page's text.
try std.testing.expectEqual(pardes.Color{ .rgb = p.chrome().del.row }, s.at(x, y + 2).style.bg);
try std.testing.expectEqual(pardes.Color{ .rgb = p.chrome().add.row }, s.at(x, y + 1).style.bg);
try std.testing.expectEqual(pardes.Color{ .rgb = p.chrome().page.text }, s.at(x, y + 1).style.fg);
try std.testing.expectEqualStrings("b\na\nc\n", pane.file.?.content);
// Enter: what the live run made, applied.
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqualStrings("B\nA\nc\n", pane.file.?.content);
try std.testing.expect(lastPipe(p) == null);
// No known filter: not run until C-p.
typeKeys(p, "|");
p.update(.{ .key = .{ .cp = 'r', .text = "rot13" } });
try std.testing.expect(has(try headOf(p), " rot13 isn't a known filter · C-p runs it"));
try std.testing.expect(lastPipe(p) == null);
p.update(.{ .key = .{ .cp = 'p', .ctrl = true } });
const second = lastPipe(p) orelse return error.MissingLiveRun;
p.update(.{ .pipe_resp = .{ .id = second, .success = true, .outputs = &.{ "\x1eoops: no\x1e2", "X\x1e\x1e0" } } });
try std.testing.expect(has(try headOf(p), " 2 runs · 1 ok · 1 exit 2 oops: no "));
// Enter refused once, said; again, the one that worked applied.
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind);
try std.testing.expect(has(try headOf(p), "oops: no — ⏎ again applies the 1 that worked"));
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqualStrings("B\nX\nc\n", pane.file.?.content);
// Every run failed: Enter applies nothing, and says so.
typeKeys(p, "|sort");
const third = lastPipe(p) orelse return error.MissingLiveRun;
p.update(.{ .pipe_resp = .{ .id = third, .success = true, .outputs = &.{ "\x1e\x1e1", "\x1e\x1e1" } } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind);
try std.testing.expect(has(p.messages.saidBy(pane), "every run failed"));
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqualStrings("B\nX\nc\n", pane.file.?.content);
try std.testing.expect(p.pipe.preview == null);
}
test "a live run's framing says each run's output, stderr and status in a real shell" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
_ = try p.setTestFile("one\ntwo\n");
typeKeys(p, "%s\\w+");
p.update(.{ .key = .{ .cp = Key.enter } });
typeKeys(p, "|");
p.update(.{ .key = .{ .cp = 'g', .text = "grep o" } });
p.update(.{ .key = .{ .cp = 'p', .ctrl = true } });
const id = lastPipe(p) orelse return error.MissingLiveRun;
const job = try @import("selection_pipe.zig").Job.copy(std.testing.allocator, p.pipe.pipeRequest(id).?);
defer job.deinit(std.testing.allocator);
var response = @import("selection_pipe.zig").runJob(std.testing.allocator, std.testing.io, job);
defer response.deinit(std.testing.allocator);
try std.testing.expect(response.success);
p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = response.outputs } });
const live_run = p.pipe.preview.?;
try std.testing.expectEqualSlices(u8, &.{ 0, 0 }, live_run.codes);
try std.testing.expectEqualStrings("one\n", live_run.outs[0]);
p.update(.{ .key = .{ .cp = Key.backspace } });
p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
const again = lastPipe(p) orelse return error.MissingLiveRun;
const job2 = try @import("selection_pipe.zig").Job.copy(std.testing.allocator, p.pipe.pipeRequest(again).?);
defer job2.deinit(std.testing.allocator);
var response2 = @import("selection_pipe.zig").runJob(std.testing.allocator, std.testing.io, job2);
defer response2.deinit(std.testing.allocator);
p.update(.{ .pipe_resp = .{ .id = again, .success = true, .outputs = response2.outputs } });
// `grep x` finds nothing: exit 1 for both, an empty stderr.
try std.testing.expectEqualSlices(u8, &.{ 1, 1 }, p.pipe.preview.?.codes);
}
test "Alt-Enter in / or s keeps the result as a list (SPEC §7.2): where jumps walk, a picker of a row a place in the tag of the pane its Enter lands in, the body as it was, its Enter the list word in the trail; more than a list holds, the first ones and a word saying so; under Jumps new-pane, /'s query pane as before" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
const Pick = pardes.Pick;
const pane = try p.setTestFile(dirty);
typeKeys(p, "/dirty");
p.update(.{ .key = .{ .cp = Key.enter, .alt = true } });
const pk = Pick.live(p) orelse return error.TestUnexpectedResult;
try std.testing.expectEqual(Pick.Source.list, pk.source);
try std.testing.expectEqualStrings("/dirty/", pk.word.slice());
try std.testing.expectEqual(@as(usize, 7), Pick.count(p, pk));
try std.testing.expectEqual(pane.serial, p.view().tag_state.host);
try std.testing.expect(!pane.places.started);
// The third place (line 3's second `dirty`): Enter lands there, the
// list word before it.
p.update(.{ .key = .{ .cp = Key.down } });
p.update(.{ .key = .{ .cp = Key.down } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 10), pane.body.cur_col);
try std.testing.expect(has(try tagOf(p), "/dirty/ 3/7 › "));
// `s` over the whole text: its selections the rows, its word the Edit
// line it stands for; Esc rolls the list up, the selection as it was.
typeKeys(p, "%sdirty");
p.update(.{ .key = .{ .cp = Key.enter, .alt = true } });
const sel = Pick.live(p) orelse return error.TestUnexpectedResult;
try std.testing.expectEqualStrings("Edit x/dirty/", sel.word.slice());
try std.testing.expectEqual(@as(usize, 7), Pick.count(p, sel));
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqual(@as(usize, 0), pane.body.nsel);
// More places than a list holds (Query.max_rows): the first ones.
const many = try std.testing.allocator.alloc(u8, 2 * (panes.Query.max_rows + 5));
defer std.testing.allocator.free(many);
for (0..panes.Query.max_rows + 5) |i| @memcpy(many[2 * i ..][0..2], "x\n");
_ = try p.setTestFile(many);
typeKeys(p, "/x");
p.update(.{ .key = .{ .cp = Key.enter, .alt = true } });
const big = Pick.live(p) orelse return error.TestUnexpectedResult;
try std.testing.expectEqual(@as(usize, panes.Query.max_rows), Pick.count(p, big));
try std.testing.expect(has(p.messages.saidBy(p.panes[p.view().active].?), "the first 2000 of 2005 places"));
p.update(.{ .key = .{ .cp = Key.escape } });
// Under Jumps new-pane, `/`'s query pane, as before.
p.settings.jumps = .@"new-pane";
typeKeys(p, "/x");
p.update(.{ .key = .{ .cp = Key.enter, .alt = true } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expect(p.panes[p.view().active].?.query != null);
}
test "a search's count keeps ` · N lines` after it in the dim ink, and drops it with the hints where they do not fit beside it; a wrap's ↻ is the count's (UX E7, D3)" {
for ([_]u16{ 200, 52 }) |cols| {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = cols, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile(dirty);
pane.body.cur_row = 2;
pane.body.cur_col = 6;
typeKeys(p, "/dirty");
const h = try head(p, p.scratch.allocator(), pane);
const lines = std.mem.indexOf(u8, h.text, " \u{b7} 5 lines");
if (cols == 200) {
try std.testing.expect(has(h.text, "3/7 \u{b7} 5 lines \u{23ce} land"));
const dim = for (h.spans) |span| {
if (span.lo == lines.? and span.style == .dim) break span;
} else return error.TestUnexpectedResult;
try std.testing.expectEqualStrings(" \u{b7} 5 lines", h.text[dim.lo..dim.hi]);
} else {
// No room for the hints: the count alone, at the row's end.
try std.testing.expect(lines == null);
try std.testing.expect(std.mem.indexOf(u8, h.text, "\u{23ce} land") == null);
try std.testing.expect(std.mem.endsWith(u8, h.text, "3/7"));
}
}
// From the last line round the end: `↻` after the count, before its lines.
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile(dirty);
pane.body.cur_row = 7;
pane.body.cur_col = 6;
typeKeys(p, "/dirty");
try std.testing.expect(has(try headOf(p), "1/7 \u{21bb} \u{b7} 5 lines \u{23ce} land"));
}
test "C-r's history has the band's cursor like any list (UX D5): `▶` on its newest line, Down and C-n, Up and C-p move it, Enter takes the line under it" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
_ = try p.setTestFile("self.a = 1;\npub fn b() void {}\nself.c = 2;\n");
typeKeys(p, "/self");
p.update(.{ .key = .{ .cp = Key.enter } });
typeKeys(p, "/pub");
p.update(.{ .key = .{ .cp = Key.enter } });
typeKeys(p, "/");
p.update(.{ .key = .{ .cp = 'r', .ctrl = true } });
var out: [Band.max_steps]Band.Step = undefined;
const a = p.scratch.allocator();
var rows = (try steps(p, a, &out))[0].rows;
try std.testing.expectEqual(@as(usize, 2), rows.len);
try std.testing.expectEqualStrings("pub", rows[0].text);
try std.testing.expect(rows[0].on and !rows[1].on);
for ([_]Key{ .{ .cp = 'n', .ctrl = true }, .{ .cp = Key.up }, .{ .cp = Key.down }, .{ .cp = 'p', .ctrl = true }, .{ .cp = 'n', .ctrl = true } }, [_]bool{ false, true, false, true, false }) |k, first| {
p.update(.{ .key = k });
rows = (try steps(p, a, &out))[0].rows;
try std.testing.expect(rows[0].on == first and rows[1].on == !first);
// The field as typed: the rows stay those it filters.
try std.testing.expectEqualStrings("", p.view().tag_state.field.text());
}
// Enter: the line under the cursor, `self`, searched for and kept.
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqualStrings("self", p.registers.value('/', 0).?);
try std.testing.expectEqualStrings("self", p.prompt_history.search.get(1).?);
}
test "a search's current hit under C-r's band is put in the rows the band leaves the body, the band over its top rows; one already there is not moved (UX DESIGN I1, D14)" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
while (p.nextEffect()) |_| {}
var text: std.ArrayList(u8) = .empty;
defer text.deinit(std.testing.allocator);
for (1..201) |i| try text.print(std.testing.allocator, "{s} {d}\n", .{ if (i == 105 or i == 125) "the hit on row" else "a row", i });
const pane = try p.setTestFile(text.items);
// A history whose lines all hold `hit`: C-r's band as tall as they.
for ([_][]const u8{ "/hitA", "/hitB", "/hitC", "/hitD", "/hitE", "/hitF", "/hitG", "/hitH" }) |q| {
typeKeys(p, q);
p.update(.{ .key = .{ .cp = Key.enter } });
}
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
// The view at line 100, the caret on its first row; line 105 the
// fifth row of the body, where the band will be.
panes.File.setTop(pane, .{ .line = 99 });
pane.body.cur_row = 99;
p.sync();
typeKeys(p, "/");
p.update(.{ .key = .{ .cp = 'r', .ctrl = true } });
p.sync();
const id = p.view().active;
const rows = pane.rows;
const at = Band.covered(p, pane, id);
try std.testing.expect(at.band >= 8 and pane.view.covered > 6);
try std.testing.expectEqual(@as(usize, 99), pane.file.?.scroll);
typeKeys(p, "hit");
p.sync();
// The hit, line 105, under the band: in the body's visible rows.
try std.testing.expectEqual(@as(i32, 104), pane.body.cur_row);
const row = @as(usize, @intCast(pane.body.cur_row)) - pane.file.?.scroll;
try std.testing.expect(row >= pane.view.covered and row < rows);
try std.testing.expectEqual(rows, pane.rows);
// The next keys keep the hit where it is: it is visible.
const top = pane.file.?.scroll;
typeKeys(p, " on");
p.sync();
try std.testing.expectEqual(@as(i32, 104), pane.body.cur_row);
try std.testing.expectEqual(top, pane.file.?.scroll);
}
|