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

const std = @import("std");
const pardes = @import("root.zig");
const config = @import("config.zig");
const layout = @import("layout.zig");
const look = @import("look.zig");
const panes = @import("panes.zig");
const filesystem = @import("fs.zig");
const exec = @import("exec.zig");
const bindings = @import("bindings.zig");
const Kind = @import("Kind.zig");
const Names = @import("Names.zig");
const Stream = @import("Stream.zig");
const Trail = @import("Trail.zig");
const TagState = @import("TagState.zig");
const Band = @import("Band.zig");
const Query = panes.Query;
const File = panes.File;
const Output = panes.Output;
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const Key = pardes.Key;

/// What a picker lists (SPEC §5.1, the sources pardes has): the files
/// under the asking pane's directory, the lines of them holding the
/// query, the files opened lately, the panes, the asking text's
/// declarations, the lines holding the query in every open pane (All, its
/// places in each), the jump list, rows handed over (a language server's
/// answer, SPC e's places), titled by their word, the messages' history
/// (SPC h m), and the themes (SPC t t, the window wearing the one under
/// the cursor).
pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes };

/// Each source's word in the tag and the leader keys of the builtin that
/// opens it, its key cells (`␣ f Find`).
const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 }).init(.{
    .find = .{ .word = "Find", .keys = "f" },
    .grep = .{ .word = "Grep", .keys = "f" },
    .recent = .{ .word = "Recent", .keys = "f" },
    .panes = .{ .word = "Panes", .keys = "b" },
    .symbols = .{ .word = "Symbols", .keys = "s" },
    .all = .{ .word = "All", .keys = "" },
    .jumplist = .{ .word = "Jumplist", .keys = "j" },
    .list = .{ .word = "List", .keys = "l" },
    .messages = .{ .word = "Messages", .keys = "hm" },
    .themes = .{ .word = "Themes", .keys = "t" },
});

/// The pickers kept after they roll up, for their list words and Resume.
pub const max_lists = 8;
/// Refinements a picker stacks (C-SPC).
pub const max_refine = 3;

pub const replica = .{ .len = .{.{ "refined", "nrefined" }} };

/// Its serial: the disk engine's target, a list word's index.
id: u32,
source: Source,
/// Its word, `Find`, or a list's own (`Refs`).
word: Kind.Buf(24) = .{},
/// The leader keys under which its builtin is, drawn as key cells.
keys: Kind.Buf(4) = .{},
/// Where Find and Grep look; what the rows' paths are relative to.
dir: Kind.Buf(4096) = .{},
/// The pane that asked, and the one its Enter lands in, by serial.
owner: u32 = 0,
landing: u32 = 0,
/// The landing pane was made for it: Esc takes it away.
made: bool = false,
/// Unrolled in a view's tag now.
unrolled: bool = false,
names: Names = .{},
/// A Grep's lines, as the disk engine sends them (Query.take).
found: std.ArrayList(Query.Found) = .empty,
found_bytes: std.ArrayList(u8) = .empty,
/// A list's rows, as they were handed over (`path:line:col text`).
rows: []u8 = &.{},
/// The query and the cursor as it rolled up (live, they are its view's
/// field and cursor).
query: Kind.Buf(256) = .{},
at: u32 = 0,
/// The landing pane's own text while its body previews (a reading pane:
/// put back when the picker rolls up), and its caret and top then (put
/// back too when it previewed its own file, with nothing set aside).
aside: ?File.State = null,
aside_row: i32 = 0,
aside_col: i32 = 0,
aside_top: usize = 0,
/// The row the preview shows (`no_row`: none yet); asked again on the
/// frame after the cursor moves, never on the key that moved it.
shown: u32 = no_row,
/// The preview on (M-p).
previews: bool = true,
/// Marked rows (Tab), by what each is (`idOf`), in order.
marks: std.ArrayList(u32) = .empty,
/// The queries refined from (C-SPC), each with the names it listed then:
/// Backspace on an empty field goes back to them.
refined: [max_refine]Refined = undefined,
nrefined: u8 = 0,
/// The band's second step: the sources to switch to (M-h), the acts on
/// the picked rows (M-l, M-Enter); `edit`: the field is the act Edit's
/// command, the query kept in `query`.
spine: enum(u8) { rows, sources, acts, edit } = .rows,
/// The act step's cursor, among the acts offered.
act_at: u8 = 0,
/// The places Walk queued (C-i steps them in the landing pane): each a
/// path in `queue_bytes`, its line and column.
queue: std.ArrayList(Queued) = .empty,
queue_bytes: std.ArrayList(u8) = .empty,
queue_at: u32 = 0,

pub const Queued = struct { path: u32, len: u16, line: u32, col: u32 };

const Refined = struct { query: Kind.Buf(64) = .{}, names: Names = .{} };

const no_row = std.math.maxInt(u32);

pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void {
    for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(gpa);
    pk.marks.deinit(gpa);
    pk.queue.deinit(gpa);
    pk.queue_bytes.deinit(gpa);
    pk.names.deinit(gpa);
    pk.found.deinit(gpa);
    pk.found_bytes.deinit(gpa);
    gpa.free(pk.rows);
}

/// Whether a search a builtin asks for from pane `id` is a picker in the
/// tag (SPEC §14.3 phase 4): in a session whose jumps walk, from the
/// keyboard or a click, never a script's (a 9P write's: the query pane,
/// whose rows it reads back, and whose `not found` it hears).
pub fn asked(p: *const Pardes) bool {
    return p.settings.jumps == .walk and !p.fs.serving;
}

/// Picker `id`, kept or live.
pub fn byId(p: *const Pardes, id: u32) ?*Pick {
    if (id == 0) return null;
    for (p.picks) |slot| if (slot) |pk| if (pk.id == id) return pk;
    return null;
}

/// The picker live in the live view's tag.
pub fn live(p: *const Pardes) ?*Pick {
    const s = &p.view().tag_state;
    if (s.kind != .pick) return null;
    const pk = byId(p, s.pick) orelse return null;
    return if (pk.unrolled) pk else null;
}

/// A picker of `source` asked from pane `from`, unrolled in the tag of the
/// pane its Enter will land in (SPEC §3.5), its field `query`. `rows` are
/// a list's (`source` `list`, titled `word`).
pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: []const u8, rows: []const u8) void {
    const asker = p.panes[from] orelse return;
    TagState.toRest(p);
    const pk = make(p, source) catch |err| return p.reportError(.at(from), "pick", err);
    pk.word.set(if (word.len > 0) word else words.get(source).word);
    pk.keys.set(words.get(source).keys);
    pk.dir.set(Pardes.paneDir(asker));
    pk.rows = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(from), "pick", err);
    hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "pick", err);
    unroll(p, pk, query);
    start(p, pk);
    filter(p, pk);
    // The themes: the cursor on the one worn (their order, the field empty).
    if (source == .themes and query.len == 0 and p.custom_theme == null) p.view().tag_state.rows.at = @intCast(p.settings.theme);
}

/// A new picker in the ring, the oldest kept one dropped for it.
fn make(p: *Pardes, source: Source) !*Pick {
    var slot: ?usize = null;
    for (p.picks, 0..) |s, i| if (s == null) {
        slot = i;
        break;
    };
    if (slot == null) {
        // The oldest not live.
        var oldest: ?usize = null;
        for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and (oldest == null or pk.id < p.picks[oldest.?].?.id)) {
            oldest = i;
        };
        const i = oldest orelse return error.NoPickerSlots;
        p.picks[i].?.deinit(p.gpa);
        p.gpa.destroy(p.picks[i].?);
        p.picks[i] = null;
        slot = i;
    }
    const pk = try p.gpa.create(Pick);
    p.next_serial += 1;
    pk.* = .{ .id = p.next_serial, .source = source };
    p.picks[slot.?] = pk;
    return pk;
}

/// Picker `pk` asked from pane `from`: the pane it lands in is `from` when
/// it reads; its reader when it is held and has one; else a pane made under
/// it as its reader would be, empty until the preview fills it. The
/// keyboard stays where it was: the landing pane is the tag's host.
fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void {
    const asker = p.panes[from].?;
    pk.owner = asker.serial;
    pk.made = false;
    // A theme is no place: its list is the asking pane's own tag (§3.5),
    // and its preview the whole window.
    if (pk.source == .themes) {
        pk.landing = asker.serial;
        p.view().active = from;
        return;
    }
    const reader = if (Trail.reading(p, asker)) from else Trail.readerOf(p, asker);
    pk.landing = p.panes[reader orelse try landingFor(p, from)].?.serial;
    pk.made = reader == null;
    p.view().active = from;
}

/// A pane made under pane `from` for a picker, where its reader goes.
fn landingFor(p: *Pardes, from: usize) !usize {
    const asker = p.panes[from].?;
    const free = p.freeSlot() orelse return error.NoPaneSlots;
    const content = try p.gpa.dupe(u8, "");
    errdefer p.gpa.free(content);
    _ = try Output.open(p, free, Pardes.paneDir(asker), .preview, "", content);
    layout.placeNew(p, from, from, free, .reader);
    layout.compute(p);
    return free;
}

/// Picker `pk` live in the live view's tag: its host its landing pane, its
/// field `query`, the cursor where it was.
fn unroll(p: *Pardes, pk: *Pick, query: []const u8) void {
    const v = p.view();
    const s = &v.tag_state;
    s.kind = .pick;
    s.pick = pk.id;
    s.host = pk.landing;
    s.field.set(query);
    s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) };
    pk.unrolled = true;
    pk.shown = no_row;
    // The whole window previews a theme.
    if (pk.source == .themes) s.previewing = .full;
    if (p.paneBySerial(pk.landing)) |id| {
        const pane = p.panes[id].?;
        pk.aside_row = pane.body.cur_row;
        pk.aside_col = pane.body.cur_col;
        pk.aside_top = if (pane.file) |f| f.scroll else 0;
    }
}

/// Its source begun: the names gathered, a listing started.
fn start(p: *Pardes, pk: *Pick) void {
    pk.names.reset();
    pk.found.clearRetainingCapacity();
    pk.found_bytes.clearRetainingCapacity();
    const dir = pk.dir.slice();
    switch (pk.source) {
        .find => {
            Stream.query(p, pk.id, .files, "", dir, .now) catch |err| return p.reportError(.at(p.view().active), "pick", err);
            if (p.fs.serving) Stream.step(p);
        },
        .grep, .all => {},
        .recent => Query.gather(p, &pk.names, .recent, dir, null, null),
        .panes => Query.gather(p, &pk.names, .panes, dir, null, null),
        .symbols => Query.gather(p, &pk.names, .symbols, dir, null, p.paneBySerial(pk.owner)),
        .jumplist => {
            var out: std.Io.Writer.Allocating = .init(p.gpa);
            defer out.deinit();
            Output.jumpsText(p, &out.writer) catch return;
            addRows(p, pk, out.written());
        },
        .list => addRows(p, pk, pk.rows),
        .messages => {
            var out: std.Io.Writer.Allocating = .init(p.gpa);
            defer out.deinit();
            Output.messagesText(p, &out.writer) catch return;
            addRows(p, pk, out.written());
        },
        .themes => for (pardes.colors.themes, 0..) |t, i| {
            pk.names.add(p.gpa, t.name, 0, t.name.len, 0, @intCast(i)) catch return;
        },
    }
}

/// Rows of text as names, a row each, matched whole.
fn addRows(p: *Pardes, pk: *Pick, text: []const u8) void {
    var lines = std.mem.splitScalar(u8, text, '\n');
    var i: u32 = 0;
    while (lines.next()) |ln| : (i += 1) {
        if (ln.len == 0) continue;
        pk.names.add(p.gpa, ln, 0, ln.len, 0, i) catch return;
    }
}

/// Its rows are names scored by the query: any source's but a live Grep's
/// or All's, and theirs once refined.
fn fuzzy(pk: *const Pick) bool {
    return pk.nrefined > 0 or (pk.source != .grep and pk.source != .all);
}

/// The field typed: the rows again for it. A Grep's lines are the disk
/// engine's, once the typing pauses; the names are scored a frame's count
/// at a time from here.
pub fn filter(p: *Pardes, pk: *Pick) void {
    const q = std.mem.trim(u8, p.view().tag_state.field.text(), " ");
    p.view().tag_state.rows.at = 0;
    pk.shown = no_row;
    if (fuzzy(pk)) return pk.names.typed(p.gpa, q);
    if (pk.source == .grep) {
        pk.found.clearRetainingCapacity();
        pk.found_bytes.clearRetainingCapacity();
        if (q.len > 0) {
            Stream.query(p, pk.id, .grep, q, pk.dir.slice(), if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err);
            if (p.fs.serving) Stream.step(p);
        } else if (p.stream.target == pk.id) _ = p.stream.stop();
        return;
    }
    {
        // All: each open text's places, found a frame's more at a time.
        for (p.panes) |slot| {
            const tp = slot orelse continue;
            if (!searchable(tp)) continue;
            if (q.len == 0) {
                if (tp.places.from == pk.id) tp.places.clear(p.gpa);
            } else tp.places.search(p, tp, .list, pk.id, q, false, null, false);
        }
    }
}

/// A pane whose text All searches: a file's or a list's, not a query
/// pane's nor a preview's.
fn searchable(tp: *const Pane) bool {
    const f = tp.file orelse return false;
    if (tp.query != null) return false;
    if (f.output) |o| if (o.from == .preview) return false;
    return true;
}

/// The panes All's places are in, in the order of their serials.
fn allPanes(p: *const Pardes, pk: *const Pick, out: *[pardes.MAX_PANES]usize) []usize {
    var n: usize = 0;
    for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == pk.id and tp.places.shows(tp) and tp.places.hits.items.len > 0) {
        out[n] = i;
        n += 1;
    };
    std.mem.sort(usize, out[0..n], p, struct {
        fn lt(pp: *const Pardes, a: usize, b: usize) bool {
            return pp.panes[a].?.serial < pp.panes[b].?.serial;
        }
    }.lt);
    return out[0..n];
}

/// The disk engine's rows for picker `target` (Stream.receive).
pub fn take(p: *Pardes, target: u32, kind: Stream.Kind, rows: []const u8) bool {
    const pk = byId(p, target) orelse return false;
    Query.take(p, pk, kind, rows);
    // A listing's names, scored as they come.
    if (kind == .files) pk.names.rescore(p.gpa);
    return true;
}

/// Pane `serial`'s declarations came (Stream.receiveParse): a Symbols
/// picker asked from it gathers them.
pub fn declsArrived(p: *Pardes, serial: u32) void {
    for (p.picks) |slot| if (slot) |pk| if (pk.unrolled and pk.source == .symbols and pk.owner == serial and pk.names.cands.items.len == 0) {
        Query.gather(p, &pk.names, .symbols, pk.dir.slice(), null, p.paneBySerial(serial));
        pk.names.typed(p.gpa, pk.names.queryText());
        pk.names.rescore(p.gpa);
    };
}

/// After every step: each live picker's names scored on (a frame's count),
/// and on a frame of its own after the cursor stood, the preview of the
/// current row.
pub fn produceAll(p: *Pardes, tick: bool) void {
    for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) {
        if (pk.names.busy()) pk.names.rescore(p.gpa);
        // A theme's preview in the step of the key that moved to it.
        if (pk.source == .themes) pardes.colors.previewTheme(p, themeAt(p, pk));
        if (tick) preview(p, pk);
    };
}

/// The frames a live picker still owes: scoring, a preview (nextWake's).
pub fn busy(p: *const Pardes) bool {
    for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) {
        if (pk.names.busy() or (pk.previews and pk.shown != p.view().tag_state.rows.at)) return true;
    };
    return false;
}

// ---- the rows ----

/// The theme the cursor of a themes picker is on.
fn themeAt(p: *const Pardes, pk: *const Pick) ?usize {
    const n = pk.names.hits.items.len;
    if (n == 0) return null;
    const at = @min(p.view().tag_state.rows.at, n - 1);
    return pk.names.cands.items[pk.names.hits.items[at].cand].ref;
}

/// The rows the list has now.
pub fn count(p: *const Pardes, pk: *const Pick) usize {
    if (fuzzy(pk)) return pk.names.hits.items.len;
    switch (pk.source) {
        .grep => return pk.found.items.len,
        .all => {
            var order: [pardes.MAX_PANES]usize = undefined;
            var n: usize = 0;
            for (allPanes(p, pk, &order)) |i| n += p.panes[i].?.places.hits.items.len;
            return n;
        },
        else => return pk.names.hits.items.len,
    }
}

/// What row `i` is, kept by a mark across a new query: a name's candidate,
/// a line's place in its source.
fn idOf(pk: *const Pick, i: usize) u32 {
    return if (fuzzy(pk)) pk.names.hits.items[i].cand else @intCast(i);
}

fn marked(pk: *const Pick, id: u32) ?usize {
    const at = std.sort.lowerBound(u32, pk.marks.items, id, struct {
        fn order(a: u32, b: u32) std.math.Order {
            return std.math.order(a, b);
        }
    }.order);
    return if (at < pk.marks.items.len and pk.marks.items[at] == id) at else null;
}

/// Where a row points: a place in a file, or a pane by its serial.
const Target = union(enum) { none, place: struct { path: []const u8, at: look.Spot }, pane: u32 };

/// Row `i` as the band shows it and what it points at, its text in
/// `arena`.
const Row = struct { text: []const u8, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none };

fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row {
    const dir = pk.dir.slice();
    if (!fuzzy(pk) and pk.source == .all) {
        var order: [pardes.MAX_PANES]usize = undefined;
        var k = i;
        for (allPanes(p, pk, &order)) |id| {
            const tp = p.panes[id].?;
            const hits = tp.places.hits.items;
            if (k >= hits.len) {
                k -= hits.len;
                continue;
            }
            const f = &tp.file.?;
            const h = hits[k];
            const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), h.start);
            const ls = File.lineStart(p.gpa, f, line);
            const le = std.mem.indexOfScalarPos(u8, f.content, h.start, '\n') orelse f.content.len;
            const whole = f.content[ls..le];
            const lead = whole.len - std.mem.trimStart(u8, whole, " \t").len;
            const name = if (f.output == null) std.Io.Dir.path.basename(f.path) else "";
            const pre = try std.fmt.allocPrint(arena, config.pane_addr ++ "{d} {s}:{d}", .{ tp.serial, name, line + 1 });
            const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, whole[lead..@min(whole.len, lead + 240)] });
            var marks: std.ArrayList(u16) = .empty;
            var c = h.start - ls;
            while (c < h.end - ls and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead));
            const target: Target = if (f.output == null) .{ .place = .{ .path = f.path, .at = .{ .line = line + 1, .col = h.start - ls + 1 } } } else .{ .pane = tp.serial };
            return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = target };
        }
        return .{ .text = "" };
    }
    if (!fuzzy(pk)) {
        const fd = pk.found.items[i];
        const name = pk.found_bytes.items[fd.path..][0..fd.path_len];
        const code = pk.found_bytes.items[fd.code..][0..fd.code_len];
        const lead = code.len - std.mem.trimStart(u8, code, " \t").len;
        const pre = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(name), fd.line });
        const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, code[lead..] });
        var marks: std.ArrayList(u16) = .empty;
        var c = fd.col;
        while (c < fd.end and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead));
        const path = try std.Io.Dir.path.join(arena, &.{ dir, name });
        return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = .{ .place = .{ .path = path, .at = .{ .line = fd.line, .col = fd.col + 1 } } } };
    }
    var marks: [Names.max_query * 4]u16 = undefined;
    var nmarks: usize = 0;
    const text = pk.names.row(i, &marks, &nmarks);
    const cand = pk.names.cands.items[pk.names.hits.items[i].cand];
    var row: Row = .{ .text = text, .marks = try arena.dupe(u16, marks[0..nmarks]) };
    switch (pk.source) {
        .find => {
            var namebuf: [4096]u8 = undefined;
            const name = if (text.len > 1 and text[0] == '"' and text[text.len - 1] == '"') look.unquoted(&namebuf, text[1 .. text.len - 1]) else text;
            row.faint = @intCast(if (std.mem.lastIndexOfScalar(u8, text, '/')) |k| k + 1 else 0);
            row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = .{ .line = 1, .col = 1 } } };
        },
        .panes => {
            row.pre = cand.key -| 1;
            row.dim = p.paneBySerial(cand.ref) == null;
            row.target = .{ .pane = cand.ref };
        },
        .symbols => {
            row.pre = 6;
            const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row;
            const f = owner.file orelse return row;
            row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } };
        },
        .themes => {},
        .recent, .jumplist, .list, .grep, .all => {
            const t = look.parsePathLine(text);
            row.pre = @intCast(t.end);
            if (t.path.len == 0) return row;
            const path = if (t.path[0] == '/' or t.path[0] == '@') t.path else try std.Io.Dir.path.join(arena, &.{ dir, t.path });
            row.target = .{ .place = .{ .path = path, .at = t.at } };
        },
        // A message (`✗ 3: words`, Output.messagesText): its cause's pane
        // while it is open; a place under it (indented): that place.
        .messages => {
            const lead = text.len - std.mem.trimStart(u8, text, " ").len;
            if (lead == 0) {
                const sp = std.mem.indexOfScalar(u8, text, ' ') orelse return row;
                const digits = text[sp + 1 ..];
                const n = std.mem.indexOfNone(u8, digits, "0123456789") orelse return row;
                if (n == 0 or digits[n] != ':') return row;
                const serial = std.fmt.parseInt(u32, digits[0..n], 10) catch return row;
                if (p.paneBySerial(serial) != null) row.target = .{ .pane = serial };
                return row;
            }
            const t = look.parsePathLine(text[lead..]);
            row.pre = @intCast(lead + t.end);
            if (t.path.len == 0) return row;
            row.target = .{ .place = .{ .path = t.path, .at = t.at } };
        },
    }
    return row;
}

// ---- the tag ----

/// The head of the landing pane's tag (SPEC §5.3): the key cells, the
/// source's word, the query, the count `cursor/total` and `•marked`; on a
/// second row the other sources' words, under spines from the key cells.
pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head {
    const pk = live(p) orelse return null;
    const s = &p.view().tag_state;
    var b = try TagState.Builder.of(p, arena, pane);
    const text = &b.text;
    // SPC's cell, then its keys': `␣ f`.
    if (pk.keys.len > 0) try b.keyCells(.leader, pk.keys.slice());
    try text.appendSlice(arena, pk.word.slice());
    try text.append(arena, ' ');
    for (pk.refined[0..pk.nrefined]) |r| try text.print(arena, "{s} | ", .{r.query.slice()});
    if (pk.spine == .edit) try text.print(arena, "{s} | Edit ", .{pk.query.slice()});
    const caret: u32 = @intCast(text.items.len + s.field.caret);
    try text.appendSlice(arena, s.field.text());
    // The count at the row's right end (UX D3): `cursor/matches`, `0` with
    // none, ` •M` marked.
    const counted = text.items.len;
    const n = count(p, pk);
    if (n == 0) try text.append(arena, '0') else try text.print(arena, "{d}/{d}", .{ s.rows.at + 1, n });
    if (pk.marks.items.len > 0) try text.print(arena, " •{d}", .{pk.marks.items.len});
    if (pk.names.busy() or p.stream.busyFor(pk.id)) try text.appendSlice(arena, " ⋯");
    // Themes have no acts and no other sources: no second row.
    if (pk.source == .themes) {
        const hints = text.items.len;
        try b.styled("⏎ wear it · esc", .dim);
        try b.right(counted, hints);
        var h = b.done();
        h.caret = caret;
        return h;
    }
    try b.right(counted, text.items.len);
    // The second row, one row (UX D2): under the spines from the key
    // cells, from two cells right of the last, the acts, `|`, the other
    // sources' words, each switching to it; what does not fit is dropped
    // from the right (the sources first) and the row ends in a dim `…`
    // (M-l and M-h reach them all).
    try b.row(if (b.ncols > 0) b.cols[b.ncols - 1] + 2 else 0);
    var offer: [acts.len + 1 + std.enums.values(Source).len][]const u8 = undefined;
    var nw: usize = 0;
    for (acts) |act| if (offered(pk, act)) {
        offer[nw] = act.word;
        nw += 1;
    };
    offer[nw] = "|";
    nw += 1;
    inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes and src != pk.source) {
        offer[nw] = words.get(src).word;
        nw += 1;
    };
    for (offer[0..nw], 0..) |word, i| {
        const gap: usize = @intFromBool(i > 0);
        const rest: usize = if (i + 1 < nw) 2 else 0;
        if (b.col() + gap + File.displayWidth(p.settings.tab, word) + rest > b.width) {
            try b.put(if (gap > 0) " " else "");
            try b.styled("…", .dim);
            break;
        }
        try b.put(if (gap > 0) " " else "");
        try b.put(word);
    }
    var h = b.done();
    h.caret = caret;
    return h;
}

/// The band's rows (UX D6): as many as the list will show, from what the
/// source has (not what the query keeps: typing never moves the body),
/// four at least, eleven at most, and 40 % of the host's column at most
/// (its panes' rows, which a borrow moves between them, never changes).
pub fn bandRows(p: *const Pardes) u16 {
    const pk = live(p) orelse return 0;
    const have = if (!fuzzy(pk)) Band.Cursor.shown else pk.names.cands.items.len;
    const v = p.view();
    const at = @import("layout.zig").findPane(p, TagState.hostOf(p) orelse return 0) orelse return 0;
    var column: usize = 0;
    for (v.cols[at.col].panes[0..v.cols[at.col].n]) |id| column += v.rects[id].h;
    const rows: usize = @max(1, @min(Band.Cursor.shown, @max(4, have), column * 2 / 5));
    // Its second step's rows too: the sources, the acts and what they act on.
    return @intCast(switch (pk.spine) {
        .sources => @max(rows, spine_rows.len),
        .acts => acts: {
            var n: usize = 1;
            for (acts) |act| n += @intFromBool(offered(pk, act));
            break :acts @max(rows, n);
        },
        .rows, .edit => rows,
    });
}

/// The band's steps: the rows around the cursor.
pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step {
    const pk = live(p) orelse return &.{};
    const s = &p.view().tag_state;
    const n = count(p, pk);
    const out = try arena.alloc(Band.Step, if (pk.spine == .sources or pk.spine == .acts) 2 else 1);
    if (pk.spine == .acts) out[1] = try actStep(p, pk, arena);
    if (pk.spine == .sources) {
        const rows = try arena.alloc(Band.Row, spine_rows.len);
        for (spine_rows, rows, 0..) |src, *row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{c} {s}", .{ src.key, src.word }), .key = 1, .index = @intCast(i), .dim = src.source == pk.source };
        out[1] = .{ .rows = rows };
    }
    if (n == 0) {
        const none = try arena.alloc(Band.Row, 1);
        none[0] = .{ .text = if (pk.names.busy() or p.stream.busyFor(pk.id)) "⋯" else if (s.field.len == 0 and pk.source == .grep) "type to search" else "nothing matches", .dim = true };
        out[0] = .{ .rows = none };
        return out;
    }
    const w = s.rows.window(@intCast(@min(n, std.math.maxInt(u16))));
    const rows = try arena.alloc(Band.Row, w.hi - w.lo);
    for (rows, w.lo..) |*row, i| {
        const r = try rowAt(p, pk, arena, i);
        row.* = .{ .text = r.text, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i) };
    }
    out[0] = .{ .rows = rows };
    return out;
}

// ---- the preview ----

/// The landing pane's body showing the current row's place (SPEC §5.3):
/// a file at its line, the query's matches lit for a Grep. Its own text is
/// set aside the first time, put back when the picker rolls up. A file an
/// open pane shows is taken from it; any other is read.
fn preview(p: *Pardes, pk: *Pick) void {
    const s = &p.view().tag_state;
    if (pk.shown == s.rows.at or !pk.previews) return;
    pk.shown = s.rows.at;
    if (count(p, pk) == 0) return;
    var frame = std.heap.ArenaAllocator.init(p.gpa);
    defer frame.deinit();
    const row = rowAt(p, pk, frame.allocator(), s.rows.at) catch return;
    const place = switch (row.target) {
        .place => |t| t,
        else => return,
    };
    const id = p.paneBySerial(pk.landing) orelse return;
    const pane = p.panes[id].?;
    const f = if (pane.file) |*file| file else return;
    if (f.twin != 0) return;
    if (!std.mem.eql(u8, f.path, place.path)) {
        if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return;
        const bytes = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return);
        if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) {
            p.gpa.free(bytes);
            return;
        }
        const path = p.gpa.dupe(u8, place.path) catch {
            p.gpa.free(bytes);
            return;
        };
        if (pk.aside == null and !pk.made) {
            const history = File.History.create(p.gpa) catch {
                p.gpa.free(bytes);
                p.gpa.free(path);
                return;
            };
            pk.aside = pane.file;
            pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history };
        } else {
            const pf = &pane.file.?;
            p.gpa.free(pf.path);
            pf.path = path;
            File.setContent(p, pf, bytes);
            pf.saved_revision = pf.revision;
            pf.scroll = 0;
            pf.scroll_row = 0;
            pf.syntax_dirty = true;
            pane.places.clear(p.gpa);
        }
        pane.hscroll = 0;
        p.sync();
    }
    const keyboard = p.view().active;
    defer p.view().active = keyboard;
    look.clearNavigationSelection(p, pane);
    const pf = &pane.file.?;
    const at = place.at;
    if (at.line == 0 or at.line > File.nlines(p.gpa, pf)) {
        pf.scroll = 0;
        pf.scroll_row = 0;
        pane.body.cur_row = 0;
        pane.body.cur_col = 0;
        return;
    }
    look.focusPaneLine(p, id, at, .center);
    // A Grep's matches in the file lit, as its own pane would have them.
    if (pk.source == .grep) pane.places.search(p, pane, .list, pk.id, std.mem.trim(u8, s.field.text(), " "), true, null, false);
}

/// The text of `path` as an open pane has it, copied: no read for it.
fn openText(p: *Pardes, path: []const u8) ?[]u8 {
    for (p.panes) |slot| {
        const tp = slot orelse continue;
        const tf = tp.file orelse continue;
        if (tf.output != null or !std.mem.eql(u8, tf.path, path)) continue;
        return p.gpa.dupe(u8, tf.content) catch null;
    }
    return null;
}

/// The landing pane as the picker found it: its own text back, or the
/// pane made for the picker taken away; the places it lit put out.
fn restore(p: *Pardes, pk: *Pick) void {
    if (pk.source == .themes) return pardes.colors.previewTheme(p, null);
    const id = p.paneBySerial(pk.landing) orelse return;
    for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa);
    if (pk.made) {
        pk.made = false;
        p.removePane(id, p.paneBySerial(pk.owner)) catch |err| p.reportError(.at(id), "pick", err);
        return;
    }
    putBack(p, pk);
}

/// The landing pane's own text back in it, the preview's freed.
fn putBack(p: *Pardes, pk: *Pick) void {
    const id = p.paneBySerial(pk.landing) orelse return;
    const pane = p.panes[id].?;
    if (pk.made) return;
    const own = pk.aside orelse {
        // Its own file previewed: its caret and top as they were.
        look.clearNavigationSelection(p, pane);
        pane.body.cur_row = pk.aside_row;
        pane.body.cur_col = pk.aside_col;
        if (pane.file != null) File.setTop(pane, .{ .line = pk.aside_top });
        return;
    };
    pk.aside = null;
    File.deinit(p, pane, &pane.file.?);
    pane.file = own;
    pane.body.cur_row = pk.aside_row;
    pane.body.cur_col = pk.aside_col;
    pane.body.vsel.active = false;
    p.sync();
}

/// The live picker rolled up (Esc, or the tag put to rest by anything):
/// its query and cursor kept for its list word and Resume, every body as
/// it was (TagState.toRest).
pub fn rollUp(p: *Pardes) void {
    const pk = live(p) orelse return;
    const s = &p.view().tag_state;
    if (pk.spine != .edit) pk.query.set(s.field.text());
    pk.spine = .rows;
    pk.at = s.rows.at;
    pk.unrolled = false;
    if (p.stream.target == pk.id) _ = p.stream.stop();
    restore(p, pk);
}

/// Every picker freed, a live one's landing pane put back first (the
/// session's end).
pub fn deinitAll(p: *Pardes) void {
    for (&p.picks) |*slot| if (slot.*) |pk| {
        if (pk.unrolled) {
            pk.unrolled = false;
            if (pk.aside) |own| if (p.paneBySerial(pk.landing)) |id| {
                const pane = p.panes[id].?;
                File.deinit(p, pane, &pane.file.?);
                pane.file = own;
                pk.aside = null;
            };
        }
        pk.deinit(p.gpa);
        p.gpa.destroy(pk);
        slot.* = null;
    };
}

// ---- keys ----

/// A key in the live picker (keys.zig tagStateKey, SPEC §5.4). Esc is
/// the tag's: TagState.toRest rolls it up.
pub fn key(p: *Pardes, k: Key) void {
    const pk = live(p) orelse return TagState.toRest(p);
    const s = &p.view().tag_state;
    const n: u16 = @intCast(@min(count(p, pk), std.math.maxInt(u16)));
    const plain = !k.ctrl and !k.alt;
    const ctrl = k.ctrl and !k.alt;
    const alt = k.alt and !k.ctrl;
    if (pk.spine == .sources) {
        pk.spine = .rows;
        for (spine_rows) |src| if (plain and k.cp == src.key) return switchTo(p, pk, src.source);
        return;
    }
    if (pk.spine == .acts) return actKey(p, pk, k);
    // Themes: Enter wears the one under the cursor; the rows and the field.
    if (pk.source == .themes) {
        if (plain and k.cp == Key.enter) {
            const at = themeAt(p, pk) orelse return;
            TagState.toRest(p);
            pardes.colors.setThemeIndex(p, at);
            return;
        }
        if (s.rows.key(k, n)) return;
        if (s.field.key(k)) filter(p, pk);
        return;
    }
    if (pk.spine == .edit) {
        if (plain and k.cp == Key.enter) return editRows(p, pk);
        if (plain and k.cp == Key.backspace and s.field.len == 0 or alt and k.cp == 'h') {
            s.field.set(pk.query.slice());
            pk.spine = .rows;
            return;
        }
        _ = s.field.key(k);
        return;
    }
    if (alt and (k.cp == Key.enter or k.cp == 'l')) {
        pk.spine = .acts;
        pk.act_at = 0;
        return;
    }
    if (plain and k.cp == Key.enter) return land(p, if (k.shift) .below else .walk);
    if (ctrl and k.cp == 's') return land(p, .below);
    if (ctrl and k.cp == 'v') return land(p, .column);
    if (plain and k.cp == Key.tab) {
        if (n == 0) return;
        toggle(p, pk, idOf(pk, s.rows.at));
        _ = s.rows.key(.{ .cp = if (k.shift) Key.up else Key.down }, n);
        return;
    }
    if (alt and k.cp == 'a') return markAll(p, pk);
    if (alt and k.cp == 'h') {
        pk.spine = .sources;
        return;
    }
    if (ctrl and (k.cp == ' ' or k.cp == '@')) return refine(p, pk, false);
    if (ctrl and k.cp == 'q') return keep(p, pk);
    if (alt and k.cp == 'p') {
        pk.previews = !pk.previews;
        pk.shown = no_row;
        if (!pk.previews) putBack(p, pk);
        return;
    }
    if (plain and k.cp == Key.backspace and s.field.len == 0) return back(p, pk);
    if (s.rows.key(k, n)) return;
    if (s.field.key(k)) filter(p, pk);
}

/// The source spine (M-h): a key a source, the query kept.
const spine_rows = [_]struct { key: u8, word: []const u8, source: ?Source }{
    .{ .key = 'f', .word = "Find", .source = .find },
    .{ .key = 'g', .word = "Grep", .source = .grep },
    .{ .key = 'r', .word = "Recent", .source = .recent },
    .{ .key = 'b', .word = "Panes", .source = .panes },
    .{ .key = 's', .word = "Symbols", .source = .symbols },
    .{ .key = '/', .word = "All", .source = .all },
    .{ .key = '?', .word = "Help", .source = null },
};

/// The live picker's source another (`null`: Help over the binding tree),
/// its query kept, its landing pane the same.
fn switchTo(p: *Pardes, pk: *Pick, source: ?Source) void {
    const s = &p.view().tag_state;
    const to = source orelse {
        var query: Kind.Buf(256) = .{};
        query.set(s.field.text());
        TagState.toRest(p);
        TagState.openHelp(p, null, "");
        p.view().tag_state.field.set(query.slice());
        return TagState.filter(p);
    };
    if (p.stream.target == pk.id) _ = p.stream.stop();
    for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa);
    for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(p.gpa);
    pk.nrefined = 0;
    pk.marks.clearRetainingCapacity();
    pk.source = to;
    pk.word.set(words.get(to).word);
    pk.keys.set(words.get(to).keys);
    start(p, pk);
    filter(p, pk);
}

fn toggle(p: *Pardes, pk: *Pick, id: u32) void {
    if (marked(pk, id)) |at| {
        _ = pk.marks.orderedRemove(at);
        return;
    }
    const at = std.sort.lowerBound(u32, pk.marks.items, id, struct {
        fn order(a: u32, b: u32) std.math.Order {
            return std.math.order(a, b);
        }
    }.order);
    pk.marks.insert(p.gpa, at, id) catch |err| p.reportError(.at(p.view().active), "pick", err);
}

/// Every row marked, or none when every one is.
fn markAll(p: *Pardes, pk: *Pick) void {
    const n = count(p, pk);
    const all = pk.marks.items.len == n;
    pk.marks.clearRetainingCapacity();
    if (all) return;
    pk.marks.ensureTotalCapacity(p.gpa, n) catch |err| return p.reportError(.at(p.view().active), "pick", err);
    for (0..n) |i| pk.marks.appendAssumeCapacity(idOf(pk, i));
    std.mem.sort(u32, pk.marks.items, {}, std.sort.asc(u32));
}

/// C-SPC: the rows the query keeps become the list, the query starts
/// empty; a Grep's lines and All's become names to score from here.
fn refine(p: *Pardes, pk: *Pick, drop: bool) void {
    const s = &p.view().tag_state;
    const q = std.mem.trim(u8, s.field.text(), " ");
    if (q.len == 0 and !drop or pk.nrefined == max_refine) return;
    // Dropped: the marked rows, or the current one.
    const current = if (count(p, pk) > 0) idOf(pk, s.rows.at) else std.math.maxInt(u32);
    var next: Names = .{};
    if (fuzzy(pk)) {
        for (pk.names.hits.items) |h| {
            if (drop and (if (pk.marks.items.len > 0) marked(pk, h.cand) != null else h.cand == current)) continue;
            const c = pk.names.cands.items[h.cand];
            next.add(p.gpa, pk.names.bytes.items[c.start..][0..c.len], c.key, c.key_len, c.base, c.ref) catch break;
        }
    } else {
        var arena = std.heap.ArenaAllocator.init(p.gpa);
        defer arena.deinit();
        for (0..count(p, pk)) |i| {
            if (drop and (if (pk.marks.items.len > 0) marked(pk, @intCast(i)) != null else i == current)) continue;
            _ = arena.reset(.retain_capacity);
            const row = rowAt(p, pk, arena.allocator(), i) catch break;
            const at = switch (row.target) {
                .place => |t| t,
                else => continue,
            };
            const ln = std.fmt.allocPrint(arena.allocator(), "{s}:{d}:{d} {s}", .{ relative(at.path, pk.dir.slice()), at.at.line, at.at.col, row.text[@min(row.text.len, row.pre + 1)..] }) catch break;
            next.add(p.gpa, ln, 0, ln.len, 0, @intCast(i)) catch break;
        }
        if (p.stream.target == pk.id) _ = p.stream.stop();
        for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa);
    }
    pk.refined[pk.nrefined] = .{ .names = pk.names };
    pk.refined[pk.nrefined].query.set(q);
    pk.nrefined += 1;
    pk.names = next;
    pk.marks.clearRetainingCapacity();
    s.field.clear();
    filter(p, pk);
}

fn relative(path: []const u8, dir: []const u8) []const u8 {
    const d = std.mem.trimEnd(u8, dir, "/");
    if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..];
    return path;
}

/// Backspace on an empty field: the last refinement undone, its query
/// back; else back a step, to the leader's level the picker was run from.
fn back(p: *Pardes, pk: *Pick) void {
    const v = p.view();
    const s = &v.tag_state;
    if (pk.nrefined > 0) {
        pk.nrefined -= 1;
        const r = &pk.refined[pk.nrefined];
        pk.names.deinit(p.gpa);
        pk.names = r.names;
        pk.marks.clearRetainingCapacity();
        s.field.set(r.query.slice());
        s.rows.at = 0;
        pk.shown = no_row;
        // A live source's own rows again: All's places are found anew.
        if (!fuzzy(pk) and pk.source == .all) filter(p, pk);
        return;
    }
    const keys = pk.keys;
    TagState.toRest(p);
    if (keys.len == 0) return;
    v.prefix = .leader;
    @memcpy(v.leader_keys[0..keys.len], keys.slice());
    v.leader_n = @intCast(keys.len);
    s.root = .leader;
    s.unrolled = true;
}

/// C-q: the rows (the marked, else all, `Query.max_rows` at most) kept as
/// text in a +Search under the asking pane, the source's word and query
/// its first line, each row an address a Look opens.
fn keep(p: *Pardes, pk: *Pick) void {
    const s = &p.view().tag_state;
    const from = p.paneBySerial(pk.owner) orelse p.view().active;
    // The history kept is the +Messages (SPEC §10.4).
    if (pk.source == .messages) {
        TagState.toRest(p);
        return Output.openMessages(p, from) catch |err| p.reportError(.at(from), "messages", err);
    }
    var out: std.Io.Writer.Allocating = .init(p.gpa);
    defer out.deinit();
    var arena = std.heap.ArenaAllocator.init(p.gpa);
    defer arena.deinit();
    out.writer.print("{s} ", .{pk.word.slice()}) catch return;
    for (pk.refined[0..pk.nrefined]) |r| out.writer.print("{s} | ", .{r.query.slice()}) catch return;
    out.writer.print("{s}\n", .{s.field.text()}) catch return;
    var kept: usize = 0;
    for (0..count(p, pk)) |i| {
        if (kept == Query.max_rows) break;
        if (pk.marks.items.len > 0 and marked(pk, idOf(pk, i)) == null) continue;
        _ = arena.reset(.retain_capacity);
        const row = rowAt(p, pk, arena.allocator(), i) catch break;
        switch (row.target) {
            .place => |t| if (pk.source == .symbols)
                out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, std.mem.trimStart(u8, row.text, " 0123456789") }) catch break
            else
                out.writer.print("{s}\n", .{row.text}) catch break,
            else => out.writer.print("{s}\n", .{row.text}) catch break,
        }
        kept += 1;
    }
    TagState.toRest(p);
    const free = p.freeSlot() orelse return p.reportError(.at(from), "pick", error.NoPaneSlots);
    const content = out.toOwnedSlice() catch |err| return p.reportError(.at(from), "pick", err);
    _ = Output.open(p, free, pk.dir.slice(), .search, "", content) catch |err| {
        p.gpa.free(content);
        return p.reportError(.at(from), "pick", err);
    };
    layout.placeNew(p, from, from, free, .doc);
}

/// How Enter lands: a walk step, a new pane below, a new column; `queue`:
/// a walk step to the first, the others queued for C-i (the act Walk).
const How = enum { walk, below, column, queue };

/// Enter: the current row, or the marked ones, looked at from the asking
/// pane (look.open, the walk's way: a reading pane steps, a held one's
/// reader does), the first as `how` says, the others each in a pane below.
/// The list rolls into the landing pane's trail as its word (item 4).
fn land(p: *Pardes, how: How) void {
    const pk = live(p) orelse return;
    var arena = std.heap.ArenaAllocator.init(p.gpa);
    defer arena.deinit();
    const a = arena.allocator();
    const picked = pickedRows(p, pk, a) catch return;
    if (picked.len == 0) return;
    // Walk: the first now, the others queued for C-i.
    pk.queue.clearRetainingCapacity();
    pk.queue_bytes.clearRetainingCapacity();
    pk.queue_at = 0;
    if (how == .queue) for (picked[1..]) |t| switch (t) {
        .place => |at| {
            const q: Queued = .{ .path = @intCast(pk.queue_bytes.items.len), .len = @intCast(@min(at.path.len, std.math.maxInt(u16))), .line = std.math.lossyCast(u32, at.at.line), .col = std.math.lossyCast(u32, at.at.col) };
            pk.queue_bytes.appendSlice(p.gpa, at.path[0..q.len]) catch break;
            pk.queue.append(p.gpa, q) catch break;
        },
        else => {},
    };
    // A step from the pane it lands in when that reads (its owner's reader
    // or itself), else from its owner, whose reader the place opens as.
    const landing = if (pk.made) null else p.paneBySerial(pk.landing);
    TagState.toRest(p);
    const v = p.view();
    const owner = p.paneBySerial(pk.owner) orelse v.active;
    const from = if (how == .walk or how == .queue) landing orelse owner else owner;
    v.active = from;
    v.jumps.force = true;
    for (picked, 0..) |t, k| switch (t) {
        .none => {},
        .pane => |serial| if (p.paneBySerial(serial)) |tid| {
            v.active = tid;
            if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col);
        } else {
            _ = p.store.reopen(p, serial, from);
        },
        .place => |at| if (k == 0 and (how == .walk or how == .queue)) {
            switch (look.open(p, from, at.path, at.at, .replace)) {
                .none => {},
                else => listed(p, pk),
            }
        } else if (k == 0 and how == .column) {
            layout.newColumn(p, from);
            const c = layout.activeColumn(p) orelse continue;
            p.exec_column = c;
            defer p.exec_column = null;
            pardes.tagline.exitHeader(p);
            _ = look.open(p, from, at.path, at.at, .below);
        } else if (how != .queue) {
            _ = look.open(p, from, at.path, at.at, .below);
        },
    };
    if (how == .queue and pk.queue.items.len > 0) {
        var said: Kind.Buf(64) = .{};
        p.setMessage(.at(v.active), said.print("Walk: {d} more places here, C-i for the next", .{pk.queue.items.len}));
    }
}

// ---- after Enter: the list word ----

/// The list as its word in a trail says it (SPEC §5.6): its source, its
/// query, where its cursor is among its rows, and its marks:
/// `Find pick 3/6 •2`.
fn wordOf(p: *const Pardes, pk: *const Pick, buf: *Kind.Buf(Trail.max_text)) []const u8 {
    var w: std.Io.Writer = .fixed(&buf.bytes);
    w.writeAll(pk.word.slice()) catch {};
    for (pk.refined[0..pk.nrefined]) |r| w.print(" {s} |", .{r.query.slice()}) catch {};
    if (pk.query.len > 0) w.print(" {s}", .{pk.query.slice()}) catch {};
    const n = count(p, pk);
    w.print(" {d}/{d}", .{ if (n == 0) 0 else pk.at + 1, n }) catch {};
    if (pk.marks.items.len > 0) w.print(" •{d}", .{pk.marks.items.len}) catch {};
    buf.len = @intCast(w.buffered().len);
    return buf.slice();
}

/// The list rolled into the trail of the reading pane it landed in, its
/// word before the place: the list `n` and `N` walk there.
fn listed(p: *Pardes, pk: *const Pick) void {
    const pane = p.panes[p.view().active] orelse return;
    if (!Trail.reading(p, pane)) return;
    var w: Trail.Word = .{ .index = pk.id };
    _ = wordOf(p, pk, &w.text);
    Trail.through(&pane.trail, .{ .list = w });
    // The newest list or search is the word n and N walk (SPEC §6.3): a
    // search's tints go with it (§7.3: lit while it is n's).
    if (pane.places.provenance == .search) pane.places.clear(p.gpa);
}

/// `n` and `N` in a reading pane whose trail's newest list or search word
/// is a list's: its next or previous row in place of the current step
/// (Trail.replaceStep), its word saying where it is now. False when there
/// is no list for them to walk (normal.zig: the search's then).
pub fn walkList(p: *Pardes, id: usize, forward: bool) bool {
    const pane = p.panes[id] orelse return false;
    if (!Trail.reading(p, pane)) return false;
    const t = &pane.trail;
    var i: usize = @min(t.cur, t.n);
    while (i > 0) {
        i -= 1;
        switch (t.steps[i]) {
            .list => break,
            .search => return false,
            else => {},
        }
    } else return false;
    const pk = byId(p, t.steps[i].list.index) orelse return false;
    const n = count(p, pk);
    if (n == 0) return false;
    if (if (forward) pk.at + 1 >= n else pk.at == 0) {
        p.setMessage(.at(id), if (forward) "n: the list's last row" else "N: the list's first row");
        return true;
    }
    pk.at = if (forward) pk.at + 1 else pk.at - 1;
    var arena = std.heap.ArenaAllocator.init(p.gpa);
    defer arena.deinit();
    const row = rowAt(p, pk, arena.allocator(), pk.at) catch return true;
    const at = switch (row.target) {
        .place => |x| x,
        else => return true,
    };
    _ = wordOf(p, pk, &t.steps[i].list.text);
    _ = Trail.replaceStep(p, id, at.path, at.at) catch |err| p.reportError(.at(id), "walk", err);
    return true;
}

/// Look on a list word in pane `id`'s trail (SPEC §6.3): the list unrolled
/// again in that pane's tag, its rows, marks, cursor and query as they were.
pub fn reopen(p: *Pardes, id: usize, index: u32) void {
    const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept");
    const pane = p.panes[id] orelse return;
    TagState.toRest(p);
    pk.landing = pane.serial;
    pk.made = false;
    unroll(p, pk, pk.query.slice());
    unrollRows(p, pk);
}

/// A list unrolled again: All's places found again, the cursor where it was.
fn unrollRows(p: *Pardes, pk: *Pick) void {
    const at = pk.at;
    if (!fuzzy(pk) and pk.source == .all) filter(p, pk);
    p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16)));
}

/// Exec on a list word (SPEC §6.3): its source run again with its query,
/// from pane `id`.
pub fn rerun(p: *Pardes, id: usize, index: u32) void {
    const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept");
    var query: Kind.Buf(256) = .{};
    query.set(pk.query.slice());
    open(p, id, pk.source, pk.word.slice(), query.slice(), pk.rows);
}

/// Resume (`SPC '`): the last picker reopened as it was, from pane `from`,
/// in the tag of the pane its Enter lands in.
pub fn resumeFrom(p: *Pardes, from: usize) void {
    var newest: ?*Pick = null;
    for (p.picks) |slot| if (slot) |pk| if (newest == null or pk.id > newest.?.id) {
        newest = pk;
    };
    const pk = newest orelse return p.setMessage(.at(from), "Resume: no picker yet");
    TagState.toRest(p);
    if (p.panes[from] == null) return;
    hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "Resume", err);
    unroll(p, pk, pk.query.slice());
    unrollRows(p, pk);
}

/// B3 on a picker's row (mouse.zig bandPress): Enter on it.
pub fn landHere(p: *Pardes) void {
    const pk = live(p) orelse return;
    if (pk.spine == .rows) land(p, .walk);
}

/// The rows an act or Enter takes: the marked, else the current.
fn pickedRows(p: *Pardes, pk: *const Pick, a: std.mem.Allocator) ![]Target {
    const s = &p.view().tag_state;
    const n = count(p, pk);
    var picked: std.ArrayList(Target) = .empty;
    if (n == 0) return picked.items;
    if (pk.marks.items.len == 0) {
        try picked.append(a, (try rowAt(p, pk, a, s.rows.at)).target);
    } else for (0..n) |i| if (marked(pk, idOf(pk, i)) != null) {
        try picked.append(a, (try rowAt(p, pk, a, i)).target);
    };
    return picked.items;
}

/// C-i past a reading pane's newest step (Jump.jumpBy, SPEC §6.4): the
/// next place a Walk queued in it, through the list its trail holds last.
pub fn stepQueue(p: *Pardes, id: usize) bool {
    const pane = p.panes[id] orelse return false;
    const t = &pane.trail;
    var i: usize = @min(t.cur, t.n);
    const pk = while (i > 0) {
        i -= 1;
        if (t.steps[i] == .list) break byId(p, t.steps[i].list.index) orelse return false;
    } else return false;
    if (pk.queue_at >= pk.queue.items.len) return false;
    const q = pk.queue.items[pk.queue_at];
    pk.queue_at += 1;
    p.view().jumps.force = true;
    _ = look.open(p, id, pk.queue_bytes.items[q.path..][0..q.len], .{ .line = q.line, .col = q.col }, .replace);
    return true;
}

// ---- acts ----

/// What the act step offers (SPEC §5.5): the same everywhere, but a list
/// of panes, whose rows are no places, has Look, Copy, Keep, Drop and Del.
const Act = struct { key: u8, word: []const u8, says: []const u8 };
const acts = [_]Act{
    .{ .key = 'w', .word = "Walk", .says = "here, one by one (C-i)" },
    .{ .key = 'o', .word = "Look", .says = "open them (Enter)" },
    .{ .key = 's', .word = "Split", .says = "each in a pane below" },
    .{ .key = 'v', .word = "Newcol", .says = "in a new column" },
    .{ .key = 'g', .word = "Grep", .says = "in their directory, the same pattern" },
    .{ .key = 'e', .word = "Edit", .says = "a sam command on each line" },
    .{ .key = 'y', .word = "Copy", .says = "the places, as text" },
    .{ .key = 'k', .word = "Keep", .says = "the rows as a +Search" },
    .{ .key = 'x', .word = "Drop", .says = "the picked from the list" },
    .{ .key = 'd', .word = "Del", .says = "close those panes" },
};

fn offered(pk: *const Pick, act: Act) bool {
    if (pk.source == .panes) return std.mem.indexOfScalar(u8, "oykxd", act.key) != null;
    return act.key != 'd';
}

/// The act step: what it acts on (`on 2 marked`, `on core/pick.zig`),
/// then the acts.
fn actStep(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator) !Band.Step {
    var rows: std.ArrayList(Band.Row) = .empty;
    const s = &p.view().tag_state;
    const on = if (pk.marks.items.len > 0)
        try std.fmt.allocPrint(arena, "on {d} marked", .{pk.marks.items.len})
    else if (count(p, pk) > 0) on: {
        const row = try rowAt(p, pk, arena, s.rows.at);
        break :on try std.fmt.allocPrint(arena, "on {s}", .{switch (row.target) {
            .place => |t| relative(t.path, pk.dir.slice()),
            else => row.text,
        }});
    } else "on nothing";
    try rows.append(arena, .{ .text = on, .dim = true });
    var k: u8 = 0;
    for (acts) |act| if (offered(pk, act)) {
        try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{c} {s: <7} {s}", .{ act.key, act.word, act.says }), .key = 1, .on = k == pk.act_at, .index = k });
        k += 1;
    };
    return .{ .rows = rows.items };
}

fn actKey(p: *Pardes, pk: *Pick, k: Key) void {
    const plain = !k.ctrl and !k.alt;
    var n: u8 = 0;
    for (acts) |act| n += @intFromBool(offered(pk, act));
    if (plain and (k.cp == Key.down or k.cp == Key.up)) {
        pk.act_at = if (k.cp == Key.down) (pk.act_at + 1) % n else (pk.act_at + n - 1) % n;
        return;
    }
    var at: u8 = 0;
    for (acts) |act| if (offered(pk, act)) {
        if (plain and (k.cp == act.key or k.cp == Key.enter and at == pk.act_at)) return doAct(p, pk, act.key);
        at += 1;
    };
    // Anything else (M-h, Left): back to the rows.
    pk.spine = .rows;
}

/// Act `key` on the picked rows.
fn doAct(p: *Pardes, pk: *Pick, key_: u8) void {
    const s = &p.view().tag_state;
    pk.spine = .rows;
    switch (key_) {
        'w' => land(p, .queue),
        'o' => land(p, .walk),
        's' => land(p, .below),
        'v' => land(p, .column),
        'k' => keep(p, pk),
        'x' => refine(p, pk, true),
        'e' => {
            pk.query.set(s.field.text());
            s.field.clear();
            pk.spine = .edit;
        },
        'g' => {
            var arena = std.heap.ArenaAllocator.init(p.gpa);
            defer arena.deinit();
            const picked = pickedRows(p, pk, arena.allocator()) catch return;
            const dir = for (picked) |t| switch (t) {
                .place => |at| break std.Io.Dir.path.dirname(at.path) orelse pk.dir.slice(),
                else => {},
            } else pk.dir.slice();
            const q = if (pk.source == .grep) arena.allocator().dupe(u8, s.field.text()) catch return else "";
            const where = arena.allocator().dupe(u8, dir) catch return;
            const from = p.paneBySerial(pk.owner) orelse p.view().active;
            TagState.toRest(p);
            open(p, from, .grep, "", "", "");
            const grep = live(p) orelse return;
            grep.dir.set(where);
            p.view().tag_state.field.set(q);
            filter(p, grep);
        },
        'y' => {
            var out: std.Io.Writer.Allocating = .init(p.gpa);
            defer out.deinit();
            var arena = std.heap.ArenaAllocator.init(p.gpa);
            defer arena.deinit();
            const picked = pickedRows(p, pk, arena.allocator()) catch return;
            for (picked) |t| switch (t) {
                .place => |at| out.writer.print("{s}:{d}\n", .{ at.path, @max(1, at.at.line) }) catch return,
                .pane => |serial| out.writer.print(config.pane_addr ++ "{d}\n", .{serial}) catch return,
                .none => {},
            };
            p.registers.put(p.gpa, '"', out.written(), 0, 1, true) catch |err| return p.reportError(.at(p.view().active), "pick", err);
            var said: Kind.Buf(64) = .{};
            p.setMessage(.at(p.view().active), said.print("Copy: {d} places into the \" register", .{picked.len}));
        },
        'd' => {
            var arena = std.heap.ArenaAllocator.init(p.gpa);
            defer arena.deinit();
            const picked = pickedRows(p, pk, arena.allocator()) catch return;
            for (picked) |t| if (t == .pane) if (p.paneBySerial(t.pane)) |id| if (id != p.paneBySerial(pk.landing)) {
                p.removePane(id, null) catch |err| p.reportError(.at(id), "pick", err);
            };
            pk.marks.clearRetainingCapacity();
            start(p, pk);
            filter(p, pk);
        },
        else => {},
    }
}

/// Edit's Enter: its command run on each picked row's line, in the open
/// text that shows its file (edit_cmd.zig, an undo step a line); a row
/// whose file no pane shows is passed over, and said.
fn editRows(p: *Pardes, pk: *Pick) void {
    const s = &p.view().tag_state;
    var arena = std.heap.ArenaAllocator.init(p.gpa);
    defer arena.deinit();
    const a = arena.allocator();
    const command = a.dupe(u8, std.mem.trim(u8, s.field.text(), " ")) catch return;
    const picked = pickedRows(p, pk, a) catch return;
    TagState.toRest(p);
    if (command.len == 0) return;
    var ran: usize = 0;
    // From the last line up, so an edit that adds lines moves none still to come.
    var k = picked.len;
    while (k > 0) {
        k -= 1;
        const at = switch (picked[k]) {
            .place => |t| t,
            else => continue,
        };
        const id = for (p.panes, 0..) |slot, i| {
            const tp = slot orelse continue;
            const f = tp.file orelse continue;
            if (f.output == null and std.mem.eql(u8, f.path, at.path)) break i;
        } else continue;
        @import("edit_cmd.zig").run(p, id, std.fmt.allocPrint(a, "{d} {s}", .{ @max(1, at.at.line), command }) catch return);
        ran += 1;
    }
    var said: Kind.Buf(96) = .{};
    p.setMessage(.at(p.view().active), said.print("Edit {s}: {d} of {d} lines, in open texts", .{ command[0..@min(command.len, 40)], ran, picked.len }));
}

/// A word of the picker's tag or band run (B2, exec.zig
/// executeBuiltinLine) while it is live: an act's word acts, a source's
/// switches to it (Grep, both, is the source); anything else is no
/// picker's.
pub fn execWord(p: *Pardes, txt: []const u8) bool {
    const pk = live(p) orelse return false;
    const word = std.mem.trim(u8, txt, " \t\n");
    for (spine_rows) |src| if (std.mem.eql(u8, word, src.word)) {
        switchTo(p, pk, src.source);
        return true;
    };
    if (std.mem.eql(u8, word, "Jumplist")) {
        switchTo(p, pk, .jumplist);
        return true;
    }
    for (acts) |act| if (offered(pk, act) and std.mem.eql(u8, word, act.word)) {
        doAct(p, pk, act.key);
        return true;
    };
    return false;
}

fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 {
    try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text });
    var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)];
    return std.Io.Dir.path.join(p.gpa, &.{ dir, name });
}

fn tagOf(p: *Pardes, arena: std.mem.Allocator, id: usize) ![]const u8 {
    return pardes.tagline.tagText(p, arena, p.panes[id].?);
}

fn paneCount(p: *const Pardes) usize {
    var n: usize = 0;
    for (p.panes) |slot| n += @intFromBool(slot != null);
    return n;
}

fn settle(p: *Pardes) void {
    var n: usize = 0;
    while (n < 50 and (busy(p) or p.stream.busyFor(live(p).?.id))) : (n += 1) {
        Stream.step(p);
        p.update(.tick);
    }
}

test "a picker from a held pane unrolls in a reader made for it: its rows in the band, the body the current row's file, Esc takes the reader away" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "pick_state.zig", "//! The state a picker keeps\nconst x = 2;\n");
    defer p.gpa.free(b_path);
    const held = try p.setTestFile("held\n");
    _ = held;
    const asker = p.view().active;
    // Held: Keep.
    Trail.keep(p.panes[asker].?);
    const dir = std.Io.Dir.path.dirname(a_path).?;
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ dir, "held.txt" });
    p.stream.engine = .walk;
    const npanes = paneCount(p);
    open(p, asker, .find, "", "", "");
    const pk = live(p).?;
    // A reader made for it, under the asker; its tag is the picker's.
    try std.testing.expectEqual(npanes + 1, paneCount(p));
    try std.testing.expect(pk.made);
    const reader = p.paneBySerial(pk.landing).?;
    try std.testing.expectEqual(@as(?usize, reader), TagState.hostOf(p));
    try std.testing.expectEqual(asker, p.view().active);
    settle(p);
    try std.testing.expectEqual(@as(usize, 2), count(p, pk));
    for ("pick") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, pk));
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const tag = try tagOf(p, a, reader);
    // Out of rest no path (UX D1): not the previewed file's, not Keep;
    // the head starts the tag's text.
    const first = tag[0..std.mem.indexOfScalar(u8, tag, '\n').?];
    try std.testing.expect(std.mem.startsWith(u8, first, "␣ f Find pick ") and std.mem.endsWith(u8, first, "  1/1"));
    try std.testing.expect(std.mem.indexOf(u8, tag, "│ Walk Look Split Newcol Grep Edit Copy Keep Drop | Grep Recent Panes Symbols All Jumplist") != null);
    // The body previews the row's file, after a frame of its own.
    p.update(.tick);
    try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path);
    _ = try p.render(a);
    const r = p.view().rects[reader];
    try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme());
    try std.testing.expect(p.panes[reader].?.band_rows >= 1);
    // Esc: the reader made for it goes, the asker as it was.
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(npanes, paneCount(p));
    try std.testing.expect(live(p) == null);
    try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind);
    try std.testing.expectEqualStrings("pick", pk.query.slice());
}

test "a picker's act row is one row under the spines, two cells right of the last: what does not fit dropped from the right, the sources first, a dim `…` ending it" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 40 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    p.stream.engine = .walk;
    open(p, asker, .find, "", "", "");
    const reader = p.paneBySerial(live(p).?.landing).?;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const tag = try tagOf(p, a, reader);
    var rows = std.mem.splitScalar(u8, tag, '\n');
    try std.testing.expect(std.mem.startsWith(u8, rows.next().?, "␣ f Find "));
    const acts_row = rows.next().?;
    try std.testing.expect(rows.next() == null);
    try std.testing.expect(std.mem.startsWith(u8, acts_row, "│ │ Walk Look "));
    try std.testing.expect(std.mem.endsWith(u8, acts_row, " …"));
    try std.testing.expect(File.displayWidth(p.settings.tab, acts_row) <= pardes.tagline.tagWidth(p, reader));
    const h = (try head(p, a, p.panes[reader].?)).?;
    try std.testing.expect(h.spans[h.spans.len - 1].style == .dim);
}

test "a picker's band is sized from its list at open, 4 rows at least, and typing never moves it" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    // In the test's directory: its two files listed.
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" });
    p.stream.engine = .walk;
    open(p, asker, .find, "", "", "");
    settle(p);
    const reader = p.paneBySerial(live(p).?.landing).?;
    p.sync();
    const rows = p.panes[reader].?.band_rows;
    // One or two files listed: four rows, ground under them.
    try std.testing.expectEqual(@as(u16, 4), rows);
    for ("zzq") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    p.sync();
    try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?));
    try std.testing.expectEqual(rows, p.panes[reader].?.band_rows);
}

test "a picker's keys: Tab marks and moves, M-a all and none, C-SPC refines and Backspace undoes it, M-h switches source keeping the query" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    look.lookAt(p, p.view().active, a_path);
    const id = p.view().active;
    open(p, id, .list, "Refs", "", "alpha.zig:1:1 one\nalpha.zig:1:2 two\nbeta.zig:1:1 tree\nalpha.zig:1:4 four\n");
    const pk = live(p).?;
    settle(p);
    const s = &p.view().tag_state;
    try std.testing.expectEqual(@as(usize, 4), count(p, pk));
    p.update(.{ .key = .{ .cp = Key.tab } });
    try std.testing.expectEqual(@as(u16, 1), s.rows.at);
    p.update(.{ .key = .{ .cp = Key.tab } });
    try std.testing.expectEqual(@as(usize, 2), pk.marks.items.len);
    p.update(.{ .key = .{ .cp = Key.up } });
    p.update(.{ .key = .{ .cp = Key.tab } });
    try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len);
    try std.testing.expectEqual(@as(u16, 2), s.rows.at);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const refs = try tagOf(p, frame.allocator(), id);
    try std.testing.expect(std.mem.indexOf(u8, refs, " Refs ") != null and std.mem.indexOf(u8, refs, "  3/4 •1\n") != null);
    p.update(.{ .key = .{ .cp = 'a', .alt = true } });
    try std.testing.expectEqual(@as(usize, 4), pk.marks.items.len);
    p.update(.{ .key = .{ .cp = 'a', .alt = true } });
    try std.testing.expectEqual(@as(usize, 0), pk.marks.items.len);
    // C-SPC: what `alpha` keeps becomes the list; `w` then narrows it.
    for ("alpha") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), count(p, pk));
    p.update(.{ .key = .{ .cp = ' ', .ctrl = true } });
    try std.testing.expectEqual(@as(u8, 1), pk.nrefined);
    try std.testing.expectEqual(@as(u16, 0), s.field.len);
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), count(p, pk));
    for ("w") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, pk));
    _ = frame.reset(.retain_capacity);
    const refined = try tagOf(p, frame.allocator(), id);
    try std.testing.expect(std.mem.indexOf(u8, refined, " Refs alpha | w ") != null and std.mem.indexOf(u8, refined, "  1/1\n") != null);
    // Backspace twice: the `w` goes, then the refinement, its query back.
    p.update(.{ .key = .{ .cp = Key.backspace } });
    p.update(.{ .key = .{ .cp = Key.backspace } });
    try std.testing.expectEqual(@as(u8, 0), pk.nrefined);
    try std.testing.expectEqualStrings("alpha", s.field.text());
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), count(p, pk));
    // M-p: the preview off, and no frame asked for it.
    p.update(.{ .key = .{ .cp = 'p', .alt = true } });
    try std.testing.expect(!pk.previews and !busy(p));
    p.update(.{ .key = .{ .cp = 'p', .alt = true } });
    // M-h r: Recent, the query kept.
    p.update(.{ .key = .{ .cp = 'h', .alt = true } });
    try std.testing.expect(pk.spine == .sources);
    p.update(.{ .key = .{ .cp = 'r', .text = "r" } });
    try std.testing.expectEqual(Source.recent, pk.source);
    try std.testing.expectEqualStrings("alpha", s.field.text());
    p.update(.{ .key = .{ .cp = Key.escape } });
}

test "Enter lands as a walk step in the reading pane; S-Enter opens below; from a held pane the reader made for the picker becomes its reader" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n");
    defer p.gpa.free(b_path);
    look.lookAt(p, p.view().active, a_path);
    const id = p.view().active;
    const npanes = paneCount(p);
    open(p, id, .list, "Refs", "", "beta.zig:3:1 three\n");
    settle(p);
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expect(live(p) == null);
    const here = p.panes[p.view().active].?;
    try std.testing.expectEqualStrings(b_path, here.file.?.path);
    try std.testing.expectEqual(@as(i32, 2), here.body.cur_row);
    try std.testing.expect(here.file.?.output == null);
    try std.testing.expectEqual(npanes, paneCount(p));
    // Its trail: where it was, then the place.
    try std.testing.expect(here.trail.n >= 2);
    // S-Enter: a pane below, the reading pane as it was.
    open(p, p.view().active, .list, "Refs", "", "alpha.zig:1:7 alpha\n");
    settle(p);
    p.update(.{ .key = .{ .cp = Key.enter, .shift = true } });
    try std.testing.expectEqual(npanes + 1, paneCount(p));
    try std.testing.expectEqualStrings(a_path, p.panes[p.view().active].?.file.?.path);

    // From a held pane: the reader made for the picker is taken away and
    // the place opens as the held pane's reader, its trail its owner's.
    const held = p.view().active;
    Trail.keep(p.panes[held].?);
    open(p, held, .list, "Refs", "", "beta.zig:2:1 two\n");
    const pk = live(p).?;
    try std.testing.expect(pk.made);
    settle(p);
    p.update(.{ .key = .{ .cp = Key.enter } });
    const reader = Trail.readerOf(p, p.panes[held].?).?;
    try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path);
    try std.testing.expectEqual(npanes + 2, paneCount(p));
}

test "M-l unrolls the act step, which says what it acts on; Copy puts the places in the register, Drop takes the picked rows out, Walk queues the rest for C-i" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\nthree\nfour\n");
    defer p.gpa.free(a_path);
    look.lookAt(p, p.view().active, a_path);
    const id = p.view().active;
    const rows = "alpha.zig:1:1 one\nalpha.zig:2:1 two\nalpha.zig:3:1 three\nalpha.zig:4:1 four\n";
    open(p, id, .list, "Refs", "", rows);
    const pk = live(p).?;
    settle(p);
    p.update(.{ .key = .{ .cp = 'l', .alt = true } });
    try std.testing.expect(pk.spine == .acts);
    // The band as tall as the acts and what they act on, the list's rows fewer.
    try std.testing.expectEqual(@as(u16, 10), bandRows(p));
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?;
    try std.testing.expectEqual(@as(u8, 2), band.nsteps);
    try std.testing.expectEqualStrings("on alpha.zig", band.steps[1].rows[0].text);
    // y: the place copied, the act step rolled back to the rows.
    p.update(.{ .key = .{ .cp = 'y', .text = "y" } });
    try std.testing.expect(pk.spine == .rows);
    // x: the current row dropped, as a refinement.
    p.update(.{ .key = .{ .cp = 'l', .alt = true } });
    p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), count(p, pk));
    try std.testing.expectEqual(@as(u8, 1), pk.nrefined);
    // Tab Tab: two marked; Walk lands on the first and queues the second.
    p.update(.{ .key = .{ .cp = Key.tab } });
    p.update(.{ .key = .{ .cp = Key.tab } });
    p.update(.{ .key = .{ .cp = 'l', .alt = true } });
    _ = frame.reset(.retain_capacity);
    const marked_band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?;
    try std.testing.expectEqualStrings("on 2 marked", marked_band.steps[1].rows[0].text);
    p.update(.{ .key = .{ .cp = 'w', .text = "w" } });
    try std.testing.expect(live(p) == null);
    try std.testing.expectEqual(@as(i32, 1), p.panes[p.view().active].?.body.cur_row);
    try std.testing.expectEqual(@as(usize, 1), pk.queue.items.len);
}

test "after Enter the list is a word in the reader's trail: n and N walk its rows in place, a Look on it reopens it with its cursor and marks, Exec runs it again, Resume reopens the last" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\nthree\nfour\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "beta.zig", "b1\nb2\n");
    defer p.gpa.free(b_path);
    _ = try p.setTestFile("held\n");
    const held = p.view().active;
    Trail.keep(p.panes[held].?);
    p.gpa.free(p.panes[held].?.file.?.path);
    p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" });
    open(p, held, .list, "Refs", "", "alpha.zig:2:1 two\nbeta.zig:2:1 b2\nalpha.zig:4:1 four\n");
    const pk = live(p).?;
    settle(p);
    p.update(.{ .key = .{ .cp = Key.tab } });
    p.update(.{ .key = .{ .cp = Key.up } });
    p.update(.{ .key = .{ .cp = Key.enter } });
    // The reader: its owner, the list's word, the place.
    const reader = Trail.readerOf(p, p.panes[held].?).?;
    var t = &p.panes[reader].?.trail;
    try std.testing.expectEqual(@as(u8, 3), t.n);
    try std.testing.expect(t.steps[1] == .list);
    try std.testing.expectEqualStrings("Refs 1/3 •1", t.steps[1].list.text.slice());
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), "‹@p") != null);
    try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), " › Refs 1/3 •1 › ") != null);
    // n: the next row, in place of the step (another file: a pane in its place).
    p.view().active = reader;
    p.update(.{ .key = .{ .cp = 'n', .text = "n" } });
    const r2 = Trail.readerOf(p, p.panes[held].?).?;
    try std.testing.expectEqualStrings(b_path, p.panes[r2].?.file.?.path);
    t = &p.panes[r2].?.trail;
    try std.testing.expectEqual(@as(u8, 3), t.n);
    try std.testing.expectEqualStrings("Refs 2/3 •1", t.steps[1].list.text.slice());
    p.update(.{ .key = .{ .cp = 'N', .text = "N", .shift = true } });
    const r3 = Trail.readerOf(p, p.panes[held].?).?;
    try std.testing.expectEqualStrings(a_path, p.panes[r3].?.file.?.path);
    try std.testing.expectEqual(@as(i32, 1), p.panes[r3].?.body.cur_row);
    // Look on the word: the list again, in the reader's tag, as it was.
    Trail.lookStep(p, r3, 1);
    try std.testing.expect(live(p) == pk);
    try std.testing.expectEqual(@as(?usize, r3), TagState.hostOf(p));
    try std.testing.expectEqual(@as(u16, 0), p.view().tag_state.rows.at);
    try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Exec on it: a new picker of the same source.
    Trail.execStep(p, r3, 1);
    try std.testing.expect(live(p) != null and live(p) != pk);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Resume: the last one.
    exec.runBuiltin(p, .Resume, held, "", null);
    try std.testing.expect(live(p) != null);
    p.update(.{ .key = .{ .cp = Key.escape } });
}

test "pick-ui §14.3 phase 4: SPC f f from a held pane opens in its reader and Esc removes it; from a reading pane it unrolls there; Enter lands as a step leaving the list word; n walks; a Look on the word reopens it with its cursor and marks" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    p.stream.engine = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "pick.zig", "const pick = 1;\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "pick_test.zig", "test {}\n");
    defer p.gpa.free(b_path);
    const c_path = try testFile(p, &tmp, "other.zig", "x\n");
    defer p.gpa.free(c_path);
    _ = try p.setTestFile("held\n");
    const held = p.view().active;
    Trail.keep(p.panes[held].?);
    p.gpa.free(p.panes[held].?.file.?.path);
    p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" });
    const npanes = paneCount(p);
    const typeIn = struct {
        fn f(pp: *Pardes, keys: []const u8) void {
            for (keys) |c| pp.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
        }
    }.f;
    // SPC f f from the held pane: a reader made for it, which Esc takes.
    typeIn(p, " ff");
    try std.testing.expect(live(p) != null and live(p).?.made);
    try std.testing.expectEqual(npanes + 1, paneCount(p));
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(npanes, paneCount(p));
    try std.testing.expectEqual(held, p.view().active);
    // Again, typed into: Enter lands in a reader of the held pane.
    typeIn(p, " ffpick");
    const pk = live(p).?;
    settle(p);
    try std.testing.expectEqual(@as(usize, 2), count(p, pk));
    p.update(.{ .key = .{ .cp = Key.tab } });
    p.update(.{ .key = .{ .cp = Key.up } });
    p.update(.{ .key = .{ .cp = Key.enter } });
    const reader = Trail.readerOf(p, p.panes[held].?).?;
    const t = &p.panes[reader].?.trail;
    try std.testing.expect(t.n == 3 and t.steps[1] == .list);
    try std.testing.expect(std.mem.startsWith(u8, t.steps[1].list.text.slice(), "Find pick 1/2 •1"));
    const first = p.panes[reader].?.file.?.path;
    try std.testing.expect(std.mem.eql(u8, first, a_path) or std.mem.eql(u8, first, b_path));
    // n: the other row, in place of the step.
    p.view().active = reader;
    p.update(.{ .key = .{ .cp = 'n', .text = "n" } });
    const now = Trail.readerOf(p, p.panes[held].?).?;
    try std.testing.expect(!std.mem.eql(u8, p.panes[now].?.file.?.path, first));
    try std.testing.expectEqual(@as(u8, 3), p.panes[now].?.trail.n);
    // SPC f f from the reader, which reads: it unrolls in the reader itself.
    typeIn(p, " ff");
    try std.testing.expectEqual(@as(?usize, now), TagState.hostOf(p));
    try std.testing.expect(!live(p).?.made);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // A Look on the list word: the list again, its cursor and its mark.
    Trail.lookStep(p, now, 1);
    try std.testing.expect(live(p) == pk);
    try std.testing.expectEqual(@as(u16, 1), p.view().tag_state.rows.at);
    try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len);
    try std.testing.expectEqualStrings("pick", p.view().tag_state.field.text());
    p.update(.{ .key = .{ .cp = Key.escape } });
}

test "a picker from a reading pane unrolls in that pane, its own text set aside while it previews and back on Esc" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n");
    defer p.gpa.free(b_path);
    look.lookAt(p, p.view().active, a_path);
    const id = p.view().active;
    try std.testing.expect(Trail.reading(p, p.panes[id].?));
    const npanes = paneCount(p);
    open(p, id, .list, "Refs", "", "beta.zig:2:1 two\nalpha.zig:1:7 alpha\n");
    const pk = live(p).?;
    try std.testing.expect(!pk.made);
    try std.testing.expectEqual(npanes, paneCount(p));
    try std.testing.expectEqual(@as(?usize, id), TagState.hostOf(p));
    settle(p);
    try std.testing.expectEqual(@as(usize, 2), count(p, pk));
    try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path);
    try std.testing.expectEqual(@as(i32, 1), p.panes[id].?.body.cur_row);
    try std.testing.expect(pk.aside != null);
    // Down: the next row's file, on the frame after.
    p.update(.{ .key = .{ .cp = Key.down } });
    try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path);
    p.update(.tick);
    try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(pk.aside == null);
    try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path);
    try std.testing.expect(p.panes[id].?.file.?.output == null);
    try std.testing.expectEqual(npanes, paneCount(p));
}

test "SPC t t is a picker of the themes in the asking pane's tag, the whole window wearing the row under the cursor and nothing dimmed; Esc puts the theme back, Enter wears it" {
    const Key_ = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const asker = p.view().active;
    p.newScratchBelow(asker);
    p.view().active = asker;
    p.settings.jumps = .walk;
    const themes = pardes.colors.themes;
    const was = p.settings.theme;
    const worn = p.theme().name;
    for (" tt") |c| p.update(.{ .key = .{ .cp = c } });
    const s = &p.view().tag_state;
    try std.testing.expectEqual(TagState.Kind.pick, s.kind);
    try std.testing.expectEqual(Source.themes, live(p).?.source);
    try std.testing.expectEqual(p.panes[asker].?.serial, s.host);
    try std.testing.expectEqual(@as(u16, @intCast(was)), s.rows.at);
    try std.testing.expectEqual(pardes.MAX_PANES, s.previewing.count());
    // Down: the window wears the next theme, the session's unchanged.
    p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } });
    const shown = s.rows.at;
    try std.testing.expect(std.mem.eql(u8, p.theme().name, themes[shown].name) and shown != was);
    try std.testing.expectEqual(was, p.settings.theme);
    // Esc: its own again.
    p.update(.{ .key = .{ .cp = Key_.escape } });
    try std.testing.expectEqualStrings(worn, p.theme().name);
    try std.testing.expect(p.theme_preview == null);
    // Again, and Enter wears it.
    for (" tt") |c| p.update(.{ .key = .{ .cp = c } });
    p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } });
    p.update(.{ .key = .{ .cp = Key_.enter } });
    try std.testing.expectEqual(@as(@TypeOf(p.settings.theme), @intCast(shown)), p.settings.theme);
    try std.testing.expectEqual(TagState.Kind.rest, s.kind);
    try std.testing.expect(p.theme_preview == null);
    try std.testing.expectEqualStrings(themes[shown].name, p.theme().name);
}

test "n and N walk the newest list or search word, or the one Looked at (SPEC §6.3, §7.3): a list landed after a search puts the search's tints out and n walks the list; Look on the search word lights it again and n steps its places" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 });
    defer p.deinit();
    p.settings.jumps = .walk;
    const pane = try p.setTestFile("dirty one\nclean\ndirty two\nclean\ndirty three\n");
    const id = p.view().active;
    for ("/dirty") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expect(pane.places.started);
    // A list lands in the pane after the search: the list is n's.
    open(p, id, .list, "Refs", "", "/test.txt:2:1 clean\n/test.txt:4:1 clean\n");
    landHere(p);
    try std.testing.expectEqual(id, p.view().active);
    try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
    try std.testing.expect(!pane.places.started);
    p.update(.{ .key = .{ .cp = 'n', .text = "n" } });
    try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row);
    // Look on the search word: lit again, and n steps its places.
    var i: u8 = 0;
    while (i < pane.trail.n and pane.trail.steps[i] != .search) i += 1;
    try std.testing.expect(i < pane.trail.n);
    Trail.lookStep(p, id, i);
    try std.testing.expect(pane.places.started);
    const was = pane.places.current;
    p.update(.{ .key = .{ .cp = 'n', .text = "n" } });
    try std.testing.expect(pane.places.current != null and !std.meta.eql(was, pane.places.current));
}