summaryrefslogtreecommitdiff
path: root/core/builtins.zig
blob: 829935c77565cbb18783d254bf27dabf38610f02 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
//! Command structs and runtime settings form the builtin registry; bindings live in config.zig.
//!
//! THE CONVENTION: the `///` block right above a builtin's `pub const
//! <Word> = struct` is what a USER reads, in Help, `pardes help`, /commands,
//! `pardes words` and the manual's glossary (`registry.doc`): what the word
//! does, its argument's forms as typed, what it does bare, where its answer
//! goes, an example where the forms are not obvious. No file names, no
//! "registration", no history: notes for whoever reads the code are `//`
//! lines inside the struct. Its first sentence (to the first `. `) is the
//! summary, at most `summary_max` bytes; a blank `///` starts a paragraph.
//! The compiler holds it: a builtin with no `///`, a summary past the bound
//! or a `///` naming a .zig file fails the build, naming the builtin.
const std = @import("std");
const pardes = @import("root.zig");
const tagline = @import("tagline.zig");
const dump = @import("dump.zig");
const exec = @import("exec.zig");
const look = @import("look.zig");
const PlumbRules = @import("Plumb.zig");
const edit = @import("edit.zig");
const colors = @import("colors.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const panes = @import("panes.zig");
const layout = @import("layout.zig");
const config = @import("config.zig");
const limits = @import("memory.zig").limits;
const keys = @import("keys.zig");
const Jump = @import("Jump.zig");

/// What this build's own frontend draws and its host does: the render's.
pub const frontend: config.Settings.Capabilities = .{
    .font_picker = pardes.font_picker,
    // The tty's font belongs to its emulator.
    .tagline_font_size = pardes.platform != .tui,
    .window_opacity = pardes.platform == .gui or pardes.platform == .macos,
    // The grip's width, the cursor's blink and the Pet are the SDL window's.
    .pixels = pardes.platform == .gui,
};

/// The terminal's build and the window's (docs/next-daemon.md, "Phase 6:
/// GUI replica notes"): each has the other's words, which a view takes as
/// its own frontend does (`viewCapabilities`), so a terminal's replica of a
/// window's session steps as the window's own does, and back.
pub const desktop = pardes.platform == .tui or pardes.platform == .gui;
const window_capabilities: config.Settings.Capabilities = .{ .font_picker = true, .tagline_font_size = true, .window_opacity = true, .pixels = true };
const terminal_capabilities: config.Settings.Capabilities = .{ .font_picker = false, .tagline_font_size = false, .window_opacity = false, .pixels = false };

/// The words this build has: a desktop build's are the window's.
pub const capabilities: config.Settings.Capabilities = if (desktop) window_capabilities else frontend;

/// What the live view's frontend takes: a window's, or a terminal's
/// (`Pardes.frontend`, which its client says, Event.frontend).
pub fn viewCapabilities(p: *const Pardes) config.Settings.Capabilities {
    if (comptime !desktop) return frontend;
    return if (p.view().frontend.windowed) window_capabilities else terminal_capabilities;
}

/// The live view's frontend, by name (the Settings report's platform).
pub fn viewPlatform(p: *const Pardes) []const u8 {
    if (comptime !desktop) return @tagName(pardes.platform);
    return if (p.view().frontend.windowed) "gui" else "tui";
}

/// Where a builtin acts: at the pane it runs from, or on the editor as a
/// whole. acme keeps its window verbs on a window's ctl and its session
/// commands elsewhere, as webfs and upas/fs keep session settings on a root
/// ctl; pardes's root `ctl` takes the session builtins and a pane's `ctl`
/// the pane ones. A builtin says `pub const scope: Scope = .session;`,
/// and every setting is one; the rest act on their pane.
/// The kinds of pane a builtin may be for alone (registry.needs).
pub const PaneKind = enum {
    terminal,
    image,
    /// An image pane, or a terminal, whose program's kitty graphics are
    /// pictures too.
    picture,
    /// A terminal, or a +Pager: a program's colours.
    program_colors,

    pub fn has(kind: PaneKind, pane: *const panes.Pane) bool {
        return switch (kind) {
            .terminal => pane.isTerminal(),
            .image => pane.addon != null,
            .picture => pane.addon != null or pane.isTerminal(),
            .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager),
        };
    }

    pub fn noun(kind: PaneKind) []const u8 {
        return switch (kind) {
            .terminal => "a terminal",
            .image => "an image",
            .picture => "an image or a terminal",
            .program_colors => "a terminal or a +Pager",
        };
    }
};

pub const Scope = enum { pane, session };

pub const Ctx = struct {
    p: *Pardes,
    pane: *Pane,
    id: usize,
    txt: []const u8,
    arg: ?[]const u8,
    /// Made by a gesture on the pane's body -- a middle click, the execute
    /// key -- as acme's execute() asks of its Text (exec.c:122,169): an
    /// Exec from a body may be a bound REPL's (exec.zig routeToRepl).
    from_body: bool = false,
};

fn isEnabled(comptime T: type) bool {
    return !@hasDecl(T, "enabled") or T.enabled;
}

/// Why `word`, a builtin some build has, is none in this one: `GUI-only`
/// for the GUI's own (`gui_only`), else `not in this build`; null for a
/// word that is one here, or in no build.
pub fn absentWhy(name: []const u8) ?[]const u8 {
    @setEvalBranchQuota(20000);
    inline for (@typeInfo(@This()).@"struct".decl_names) |d| {
        if (comptime @TypeOf(@field(@This(), d)) == type) {
            const T = @field(@This(), d);
            if (comptime @typeInfo(T) == .@"struct" and @hasDecl(T, "run") and !isEnabled(T)) {
                if (std.mem.eql(u8, d, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build";
            }
        }
    }
    return null;
}

fn manualBuiltinList() []const type {
    comptime {
        @setEvalBranchQuota(4000);
        var list: []const type = &.{};
        for (@typeInfo(@This()).@"struct".decl_names) |d| {
            if (@TypeOf(@field(@This(), d)) != type) continue;
            const T = @field(@This(), d);
            if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue;
            if (@TypeOf(T.run) != fn (Ctx) void)
                @compileError(d ++ ".run must have signature fn (Ctx) void");
            list = list ++ .{T};
        }
        return list;
    }
}

fn settingList() []const config.Settings.Setting {
    comptime {
        var list: []const config.Settings.Setting = &.{};
        for (config.Settings.settings) |setting| if (setting.enabled(capabilities)) {
            list = list ++ .{setting};
        };
        return list;
    }
}

pub fn word(comptime T: type) []const u8 {
    const n = @typeName(T);
    const dot = std.mem.lastIndexOfScalar(u8, n, '.') orelse return n;
    return n[dot + 1 ..];
}

/// A builtin's documentation (THE CONVENTION, at the top of this file).
pub const Doc = struct {
    /// Its first sentence: a line of /commands and of `pardes words`.
    summary: []const u8,
    /// All of it, a line a paragraph, the summary first.
    text: []const u8,
};

/// The longest summary, in bytes: a line's worth after its word.
pub const summary_max = 100;

/// `text`'s first sentence: to the first `.` a blank or a line's end
/// follows (`a.zig@main` and `from..to` go on).
fn docOf(comptime text: []const u8) Doc {
    for (text, 0..) |c, i| {
        if (c == '\n') return .{ .summary = text[0..i], .text = text };
        if (c == '.' and (i + 1 == text.len or text[i + 1] == ' ' or text[i + 1] == '\n')) return .{ .summary = text[0 .. i + 1], .text = text };
    }
    return .{ .summary = text, .text = text };
}

/// The `///` lines from `from` to `to` in `source` as paragraphs: each
/// line's text after `///` joined to the next by a blank, a blank `///` a
/// line break.
fn paragraphs(comptime source: []const u8, comptime from: usize, comptime to: usize) []const u8 {
    var text: []const u8 = "";
    var lines = std.mem.splitScalar(u8, source[from..to], '\n');
    var gap: []const u8 = "";
    while (lines.next()) |line| {
        const said = std.mem.trim(u8, line["///".len..], " ");
        if (said.len == 0) {
            if (text.len > 0) gap = "\n";
            continue;
        }
        text = text ++ (if (text.len == 0) "" else if (gap.len > 0) gap else " ") ++ said;
        gap = "";
    }
    return text;
}

pub const OutputTraits = struct {
    name: []const u8,
    steps: bool = false,
    jumps: bool = false,
    // This producer emits location rows whose labels and source excerpts may be styled.
    locations: bool = false,
    commands: bool = false,
    doc: bool = false,
    // Saving promotes this scratch buffer into an ordinary file.
    saves: bool = false,
};

// Keep enum-dependent signatures out of the outer declaration walk.
pub const registry = struct {
    /// Whether builtin `b` is one the live view's frontend takes: a window's
    /// own words (a builtin that says `in_window`, the settings a terminal
    /// cannot show) in a window's view alone. The rest of a build's words are
    /// every view's.
    pub fn here(p: *const Pardes, b: Builtin()) bool {
        return hereFor(b, viewCapabilities(p), !desktop or p.view().frontend.windowed);
    }

    /// `here` for a frontend of these capabilities, windowed or not.
    pub fn hereFor(b: Builtin(), caps: config.Settings.Capabilities, windowed: bool) bool {
        inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return !@hasDecl(T, "in_window") or windowed;
        inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return setting.enabled(caps);
        unreachable;
    }

    pub fn Builtin() type {
        // Duplicate-name validation compares every pair.
        @setEvalBranchQuota(200_000);
        const manual = manualBuiltinList();
        const generated = settingList();
        const count = manual.len + generated.len;
        const Tag = std.math.IntFittingRange(0, count - 1);
        var names: [count][]const u8 = undefined;
        for (manual, 0..) |T, i| names[i] = word(T);
        for (generated, manual.len..) |setting, i| names[i] = setting.word;
        for (names, 0..) |name, i| for (names[i + 1 ..]) |later|
            if (std.mem.eql(u8, name, later)) @compileError("duplicate builtin name: " ++ name);
        return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count));
    }

    /// What a hand-written builtin says as `name` (`pub const takes_arg =
    /// true;`), `default` when it says nothing, and `setting` for a setting.
    fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) {
        inline for (comptime manualBuiltinList(), 0..) |T, i|
            if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default;
        return setting;
    }

    /// What a user reads of builtin `b` (THE CONVENTION, at the top).
    pub fn doc(b: Builtin()) Doc {
        return docs[@backingInt(b)];
    }

    /// Each builtin's documentation, by its number: a hand-written one's
    /// the `///` block above it, read off this file at compile time; a
    /// setting's its `doc`.
    const docs = docs: {
        const manual = manualBuiltinList();
        const generated = settingList();
        var table: [manual.len + generated.len]Doc = undefined;
        var found: [manual.len]bool = @splat(false);
        // a few branches a byte of the source, once
        @setEvalBranchQuota(4_000_000);
        const source = @embedFile("builtins.zig");
        var block: ?usize = null; // where the `///` lines above this one start
        var block_end: usize = 0;
        var at: usize = 0;
        while (at < source.len) {
            const end = std.mem.indexOfScalarPos(u8, source, at, '\n') orelse source.len;
            const line = source[at..end];
            if (std.mem.startsWith(u8, line, "///")) {
                if (block == null) block = at;
                block_end = end;
            } else {
                if (block) |from| if (std.mem.startsWith(u8, line, "pub const ")) {
                    const rest = line["pub const ".len..];
                    if (std.mem.indexOf(u8, rest, " = struct")) |name_end| for (manual, 0..) |T, i| {
                        if (!std.mem.eql(u8, word(T), rest[0..name_end])) continue;
                        table[i] = docOf(paragraphs(source, from, block_end));
                        found[i] = true;
                    };
                };
                block = null;
            }
            at = end + 1;
        }
        for (manual, 0..) |T, i| {
            if (!found[i]) @compileError("builtin " ++ word(T) ++ " has no documentation: a `///` block right above `pub const " ++ word(T) ++ " = struct`");
            held(word(T), table[i]);
        }
        for (generated, manual.len..) |setting, i| {
            table[i] = docOf(setting.doc);
            held(setting.word, table[i]);
        }
        break :docs table;
    };

    /// THE CONVENTION's two rules the compiler can read.
    fn held(comptime name: []const u8, comptime d: Doc) void {
        if (d.summary.len > summary_max)
            @compileError(std.fmt.comptimePrint("builtin {s}: its first sentence is {d} bytes, over {d}: \"{s}\"", .{ name, d.summary.len, summary_max, d.summary }));
        if (std.mem.indexOf(u8, d.text, ".zig") != null)
            @compileError("builtin " ++ name ++ ": its documentation names a source file; a note for the code's reader is a `//` line inside the struct");
    }

    pub fn takesArg(b: Builtin()) bool {
        // Every setting takes its value, and a switch flips when bare.
        return declOr(b, "takes_arg", false, true);
    }

    /// Whether the word takes its argument joined by a `+` as one word a
    /// tag can hold and a click take whole (`Term+fish`). Only a builtin
    /// that says `pub const plus_arg = true;`: others have arguments a `+`
    /// may be in (`Dump+2024.zon` is a name, not Dump's argument).
    pub fn plusArg(b: Builtin()) bool {
        return declOr(b, "plus_arg", false, false);
    }

    /// Whether the word means nothing without its argument (`Mount`,
    /// `Msg`, a setting's value), or would ask for it at a prompt (`Find`):
    /// a ctl refuses it bare before any line of the write runs. A builtin
    /// says `pub const requires_arg = true;` beside `takes_arg`.
    /// The one kind of pane a builtin means something on, or null for any:
    /// it says `pub const needs: PaneKind = .terminal;`, and on any other
    /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are.
    pub fn needs(b: Builtin()) ?PaneKind {
        return declOr(b, "needs", @as(?PaneKind, null), null);
    }

    pub fn requiresArg(b: Builtin()) bool {
        inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i|
            if (@backingInt(b) == i) return switch (setting.action) {
                // a switch flips bare, a choice steps, and DumpDir and Shell bare
                // are the default
                .toggle, .dump_dir, .choice, .shell => false,
                .theme, .font, .tagline_size, .window_opacity, .message_linger, .inactive_dim, .grip_width => true,
                // bare, it says the current value (exec.applySettingBuiltin)
                .tab, .callstack_depth => false,
            };
        return declOr(b, "requires_arg", false, false);
    }

    pub fn scope(b: Builtin()) Scope {
        return declOr(b, "scope", Scope.pane, .session);
    }

    pub fn outputTraits(b: Builtin()) ?OutputTraits {
        return declOr(b, "output", @as(?OutputTraits, null), null);
    }

    /// Does this builtin say its own name on the message row before it runs?
    /// The ones that own that row themselves declare `quiet` and do not.
    pub fn announces(b: Builtin()) bool {
        // a setting builtin changes something invisible; say so
        return !declOr(b, "quiet", false, false);
    }

    pub fn dispatch(b: Builtin(), c: Ctx) void {
        inline for (comptime manualBuiltinList(), 0..) |T, i|
            if (@backingInt(b) == i) return T.run(c);
        inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i|
            if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg);
        unreachable;
    }
};

// ---- the two acme verbs ----

/// Look at its argument as B3 does: open the file or address it names, else
/// find the word.
///
/// `Look notes.txt:12` opens the file at line 12, or goes to the pane already
/// showing it; an address may be a line, `:12:5`, `/re/`, a directory (a pane
/// listing it) or a URL (the browser, by a plumbing rule). A relative path is
/// found in the directory of the pane looked from, then of each pane on the
/// jump list. Bare (Enter): the selection, else what is under the cursor.
pub const Look = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    // a look's answer is the pane it opens or the place it jumps to; its own
    // name on the message row would only be noise over that
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        // Bare (a key bound to it, a tag's Look with nothing held): the
        // selection, else what Enter on the cursor takes, the one expansion.
        const arg = c.arg orelse (exec.currentOperand(c.p, c.pane) orelse return);
        look.lookAt(c.p, c.id, arg);
    }
};

/// Run its argument as B2 on it would: a builtin, else a shell command.
///
/// `Exec Newcol` runs the builtin. `Exec make test` runs the line: from a
/// terminal at an idle, empty prompt, typed into its shell; from anywhere
/// else, in a command pane (a terminal running `$SHELL -c` the line, which
/// shows its output and `exit N` when it ends; Kill stops it). Run by name, a
/// line is never a REPL's.
pub const Exec = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        // the destination pane is Look's business (it focuses what answered);
        // an execute deliberately leaves you where you were
        _ = exec.executeFrom(c.p, c.id, c.arg orelse return, c.from_body);
    }
};

// ---- session ----

/// Which panes a refusal asks about: every one (Exit, Restore), one (Del),
/// or a column's (Delcol).
pub const Asked = union(enum) { all, pane: usize, column: usize };

/// acme's rowclean (editors/acme/wind.c:511-529, winclean), asked before
/// what would throw unsaved text away: each pane holding some nobody has
/// been told about is listed in +Unsaved, `<name>: Modified`, under it
/// `Exit again to discard`, with a short notice, `3 unsaved panes -- Exit
/// again to discard`,
/// naming the word asking, since repeating it throws the text away, and is
/// then clean for the asking, as winclean clears `dirty`; so the same word
/// again, with nothing edited since, goes ahead. Only the same word: a
/// Restore a script was refused does not spend the warning an Exit owes
/// the person at the keyboard. A scratch of under 100 bytes is no loss
/// worth the question, as winclean does not ask for one.
pub fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool {
    // Every pane asked about is an `unsaved <serial> <name>` record, as
    // acme's rowclean names them all (wind.c:511); the refusal a write
    // gets names the one, or counts them, never a list cut short.
    var count: usize = 0;
    var one_buf: [limits.host_path_cap + 24]u8 = undefined;
    var one: []const u8 = "";
    // The whole list goes into +Unsaved, where it stays; the notice is short.
    var listed: std.ArrayList(u8) = .empty;
    const arena = c.p.scratch.allocator();
    for (c.p.panes, 0..) |slot, id| {
        const pane = slot orelse continue;
        switch (which) {
            .all => {},
            .pane => |only| if (id != only) continue,
            .column => |col| if ((layout.findPane(c.p, id) orelse continue).col != col) continue,
        }
        const f = pane.file orelse continue;
        // Twins (Zerox) hold one text: closing one while another stays
        // loses nothing, and the text is asked about once.
        if (f.twin != 0) {
            const asked_elsewhere = for (c.p.panes, 0..) |other_slot, other_id| {
                const other = other_slot orelse continue;
                const of = other.file orelse continue;
                if (other_id == id or of.twin != f.twin) continue;
                const closing = switch (which) {
                    .all => true,
                    .pane => |only| other_id == only,
                    .column => |col| if (layout.findPane(c.p, other_id)) |at| at.col == col else false,
                };
                if (!closing or other_id < id) break true;
            } else false;
            if (asked_elsewhere) continue;
        }
        // A +New scratch saves nowhere, but what is typed in it is as lost;
        // under 100 bytes it is not asked about, as acme's winclean does not
        // whine about a small unnamed window, nor about a command's output.
        const scratch = if (f.output) |o| o.from == .cmd and o.from.cmd == .New else false;
        // A file deleted on disk is asked about, edited or not: its text is
        // nowhere else now (acme's winclean asks the same).
        const gone = f.disk_gone and f.output == null;
        if (!gone) {
            if (f.revision == f.saved_revision or !(panes.Output.fileTraits(f.output).saves or scratch)) continue;
            if (f.output != null and f.content.len < 100) continue;
            // Dirty by a rename alone is no text to lose, as get says (ctl.zig).
            // Nor is a buffer never edited at all: its first edit is what keeps
            // the text it had (File.zig), so with none there is nothing to lose.
            const saved = f.saved_hash orelse continue;
            if (panes.File.fileHash(&f) == saved) continue;
        }
        if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == asking) continue;
        pane.discard_warned = .{ .revision = f.revision, .by = asking };
        // Scratches share a name: each is named with its pane's serial too,
        // `/dir/+New (pane 12)`, the same in every refusal (Exit, Restore,
        // Del, Delcol).
        var name_buf: [limits.host_path_cap + 24]u8 = undefined;
        const name = if (scratch) std.fmt.bufPrint(&name_buf, "{s} (pane {d})", .{ f.path, pane.serial }) catch f.path else f.path;
        pardes.ctlfs.events.noteLog(c.p, .unsaved, pane);
        listed.print(arena, "{s}: Modified\n", .{name}) catch {};
        if (count == 0) one = std.fmt.bufPrint(&one_buf, "{s}", .{name}) catch name;
        count += 1;
    }
    if (count > 0) {
        listed.print(arena, "\n{s} again to discard\n", .{@tagName(asking)}) catch {};
        // A refused Delcol changes nothing, the layout included: its records
        // and its notice say it, and no +Unsaved opens.
        if (asking != .Delcol) if (c.p.gpa.dupe(u8, listed.items)) |content| panes.Output.openUnsaved(c.p, c.id, content) else |_| {};
        var short: pardes.Kind.Buf(96) = .{};
        c.p.reportFailure(c.id, short.print("{d} unsaved pane{s} \u{2014} {s} again to discard", .{ count, if (count == 1) "" else "s", @tagName(asking) }));
    }
    if (count > 0 and (c.p.fs.no_prompt or c.p.fs.capturing)) {
        var said_buf: pardes.Kind.Buf(limits.host_path_cap + 96) = .{};
        const said = if (count == 1)
            said_buf.print("{s}: Modified ({s} again to discard)", .{ one, @tagName(asking) })
        else
            said_buf.print("{d} unsaved panes: Modified ({s} again to discard)", .{ count, @tagName(asking) });
        var room: @TypeOf(c.p.fs.failure) = undefined;
        const kept = pardes.ctlfs.fitErr(said, &room);
        @memcpy(c.p.fs.failure[0..kept.len], kept);
        c.p.fs.failure_len = @intCast(kept.len);
    }
    return count > 0;
}

/// Quit the editor; refused once while a pane holds unsaved text.
///
/// Each pane with unsaved text is listed in +Unsaved and the notice counts
/// them; Exit again, nothing edited since, quits and discards it. On the way
/// out the session's panes are kept in the state file, for History and
/// Restore.
pub const Exit = struct {
    // acme's Exit (editors/acme/exec.c:892), asking warnModifiedIn first.
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        if (warnModifiedIn(c, .Exit, .all)) return;
        c.p.endSession();
        c.p.emit(.quit);
    }
};

/// Stop the commands pardes started that are still running.
///
/// They are the lines pardes typed into a terminal (from an exec, a middle
/// click, a pty/run) and its command panes. Bare, every one; `Kill make ls`,
/// those whose line starts with one of the words. Each gets SIGTERM: a
/// command pane's whole command, a terminal's foreground job, never its
/// shell, which stays.
pub const Kill = struct {
    // acme's Kill (exec.c, `kill`; acme.c's WKill) posts the "kill" note,
    // which ends a process; here a terminal's job between its C and D marks.
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const names = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        var stopped = false;
        var jobless = false;
        var running = false;
        for (c.p.panes, 0..) |slot, id| {
            const pane = slot orelse continue;
            const command: ?[]const u8 = if (pane.command) |line| (if (pane.command_done) null else line) else null;
            // The command pardes last typed here, running now.
            const typed_runs = if (pane.sent_command) |sent| typed: {
                const at = panes.Term.prompt(pane.terminal);
                break :typed at.phase == .running and at.started == sent.seq;
            } else false;
            if (command == null and !typed_runs) continue;
            running = true;
            const first = if (command) |line| first: {
                const said = std.mem.trim(u8, line, " \t");
                break :first said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len];
            } else pane.sent_command.?.word[0..pane.sent_command.?.len];
            if (names.len > 0) {
                var words = std.mem.tokenizeAny(u8, names, " \t");
                while (words.next()) |w| {
                    if (std.mem.eql(u8, w, first)) break;
                } else continue;
            }
            // A command pane's child is the command: the whole of its
            // process group goes, as acme's Kill ends the process. A
            // terminal's job is asked of the host now, not queued: the job
            // the marks say is running is the one signalled, not whatever
            // runs by then.
            if (command != null) {
                c.p.emit(.{ .signal_pty = .{ .pane = .at(id), .serial = pane.serial, .sig = .term } });
                stopped = true;
            } else if (c.p.hostKillJob(id)) stopped = true else jobless = true;
        }
        if (stopped) return;
        if (jobless) return c.p.reportFailure(c.id, "Kill: no job to signal (its shell runs it without job control)");
        // Said, but no failure: a script's Kill, named or not, has nothing
        // left to do. Only commands running, none of them the one named, is.
        if (names.len > 0 and running)
            c.p.reportFailure(c.id, "Kill: no running command has that first word")
        else
            c.p.setMessage(.at(c.id), "Kill: nothing running");
    }
};

/// Write the session's panes and layout to the state file, for Restore.
///
/// `Dump export <path>` writes them to a file of their own instead (`~` the
/// home directory). The workspace tag then holds a `Restore <path>` word that
/// brings them back.
pub const Dump = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        var to: ?[]const u8 = null;
        if (c.arg) |arg| {
            const trimmed = std.mem.trim(u8, arg, " \t");
            if (!std.mem.startsWith(u8, trimmed, "export ")) return c.p.reportFailure(c.id, "Dump: takes export <path>, or nothing");
            const path = std.mem.trim(u8, trimmed["export".len..], " \t");
            if (path.len == 0) return c.p.reportFailure(c.id, "Dump: takes export <path>, or nothing");
            to = path;
        }
        // Never a Dump said done that wrote nothing: its failure is said.
        dump.dumpTo(c.p, to) catch |err| c.p.reportError(.at(c.id), "Dump", err);
    }
};

/// Replace every pane with those of a dump.
///
/// `Restore <label>`: the state file's dump of that label (History lists
/// them); `Restore <file>`: a dump file's, a path, or the name of a file in
/// the DumpDir or the directory pardes runs in. Bare: the last one this
/// session made, else the newest. A file that is not a dump is said first;
/// then, as Exit, it is refused once while a pane holds unsaved text.
pub const Restore = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const typed: ?[]const u8 = c.arg orelse c.p.last_dump;
        // A file it names, its whole path (`~`, the DumpDir, the directory
        // it runs in): what the log's `restore` record and every message
        // name. Else a label of the state file's.
        var full_buf: [4096]u8 = undefined;
        var label_buf: [256]u8 = undefined;
        const file = if (typed) |t| dump.restoreFile(c.p.tape, t, c.p.settings.dump_dir.get(), &full_buf) else null;
        const name = if (file) |path| path else c.p.tape.authority(pardes.Db.labelled, .{ &c.p.db, c.p, typed, @as([]u8, &label_buf) }) orelse {
            var buf: pardes.Kind.Buf(320) = .{};
            return c.p.reportFailure(c.id, if (typed) |t| buf.print("Restore: no dump labelled {s}", .{t}) else "Restore: no dump yet; name one");
        };
        if (name.len > c.p.restore_buf.len) return c.p.reportFailure(c.id, "Restore: that name is too long");
        // A file that cannot be read is said now, and fails a ctl write:
        // the host reads it only after this step, where nobody hears.
        // First, so a Restore that could never happen spends no warning.
        if (file) |path| {
            const bytes = @import("fs.zig").readFile(c.p.tape, c.p.gpa, path) catch |err| {
                var buf: pardes.Kind.Buf(limits.host_path_cap + 160) = .{};
                var words: [128]u8 = undefined;
                const why = switch (err) {
                    error.FileNotFound => "no such file",
                    error.PermissionDenied => "permission denied",
                    error.IsDirectory => "a directory, not a dump",
                    else => pardes.Messages.errorWords(err, &words),
                };
                return c.p.reportFailure(c.id, buf.print("Restore: {s}: {s}", .{ path[0..@min(path.len, limits.host_path_cap)], why }));
            };
            defer c.p.gpa.free(bytes);
            // Nor does a file that is not a dump, before any warning.
            var why_buf: [256]u8 = undefined;
            pardes.dump.check(c.p.gpa, bytes, &why_buf) catch |err| {
                var buf: pardes.Kind.Buf(limits.host_path_cap + 320) = .{};
                const why = if (err == error.OutOfMemory) pardes.Messages.errorWords(err, &why_buf) else why_buf[0..std.mem.indexOfScalar(u8, &why_buf, 0).?];
                return c.p.reportFailure(c.id, buf.print("Restore: {s}: not a pardes dump: {s}", .{ path[0..@min(path.len, limits.host_path_cap)], why }));
            };
        }
        // acme's Load adds a dump's windows to the ones there; a Restore
        // replaces them all, so it asks what Exit asks first.
        if (warnModifiedIn(c, .Restore, .all)) return;
        @memcpy(c.p.restore_buf[0..name.len], name);
        c.p.restore_req = c.p.restore_buf[0..name.len];
    }
};

/// Detach this pardes from its terminal or window, leaving the session
/// running.
///
/// `pardes attach` (or `pardes-gui attach`) shows it again, as a client.
pub const Detach = struct {
    pub const scope: Scope = .session;
    pub const enabled = pardes.can_attach;
    pub fn run(c: Ctx) void {
        c.p.emit(.{ .detach = .{ .pane = .at(c.id) } });
    }
};

/// Take in the shells of a session that died holding them, each as a terminal
/// here.
///
/// The pardes daemon kept their terminals open; with none kept for this
/// session, it says so.
pub const Adopt = struct {
    pub const scope: Scope = .session;
    pub const enabled = pardes.can_attach;
    pub fn run(c: Ctx) void {
        c.p.tape.host(c.p, .adopt, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session");
    }
};

/// Move this session onto the pardes installed since it started, in place.
///
/// Its text, undo, views, terminals with their running shells, and its
/// terminals and windows come along; the pardes daemon moves too. A pardes
/// that cannot move to another build in place says so.
pub const Upgrade = struct {
    pub const scope: Scope = .session;
    pub const enabled = pardes.can_attach;
    pub fn run(c: Ctx) void {
        c.p.tape.host(c.p, .upgrade, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Upgrade: this pardes cannot move to another build in place");
    }
};

/// Mount another pardes's 9P tree under /n/<name>, given its dial address.
///
/// `Mount <name> <dial>`, the dial `unix!/path`, a socket's path,
/// `tcp!<numeric-ip>!<port>` or a session's name. One that cannot be reached
/// is said at once, and not kept.
pub const Mount = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t");
        const e_args = "wrong #args in control message \"Mount\": Mount name dial";
        const name = args.next() orelse return c.p.reportFailure(c.id, e_args);
        const dial = std.mem.trim(u8, args.rest(), " \t");
        if (dial.len == 0) return c.p.reportFailure(c.id, e_args);
        c.p.fs.mount(c.p.gpa, name, dial) catch |err| {
            var said: pardes.Kind.Buf(200) = .{};
            if (err == error.BadDial) return c.p.reportFailure(c.id, said.print("Mount: bad dial address: {s} (unix!/path, /path, tcp!<numeric-ip>!<port>, or a session name)", .{dial[0..@min(dial.len, 100)]}));
            return c.p.reportError(.at(c.id), "Mount", err);
        };
        // A socket path that is not there: said so (ENOENT), not a dial
        // that went unanswered.
        const sock_path: ?[]const u8 = if (std.mem.startsWith(u8, dial, "unix!")) dial[5..] else if (dial.len > 0 and dial[0] == '/') dial else null;
        if (sock_path) |path| if (@import("exec.zig").kindOf(c.p.tape, path) == null) {
            if (c.p.fs.mounts.pop()) |gone| {
                c.p.gpa.free(gone.name);
                c.p.gpa.free(gone.dial);
            }
            var said: pardes.Kind.Buf(200) = .{};
            return c.p.reportFailure(c.id, said.print("Mount {s}: {s}: no such socket", .{ name[0..@min(name.len, 32)], path[0..@min(path.len, 100)] }));
        };
        // A mount that cannot be reached is said now, and taken back, not
        // found out by the first look through it.
        const reached = c.p.tape.site(.probe, null, @import("runtime").ninep_io.Client.probeMount, .{ c.p.gpa, dial });
        reached catch |err| {
            if (c.p.fs.mounts.pop()) |gone| {
                c.p.gpa.free(gone.name);
                c.p.gpa.free(gone.dial);
            }
            var what: pardes.Kind.Buf(160) = .{};
            return c.p.reportError(.at(c.id), what.print("Mount {s} {s}", .{ name[0..@min(name.len, 32)], dial }), err);
        };
    }
};

/// Unmount the 9P tree mounted under /n/<name>: `Unmount <name>`.
pub const Unmount = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t");
        const name = args.next() orelse return c.p.reportError(.at(c.id), "Unmount name", error.MissingArgument);
        if (args.next() != null) return c.p.reportError(.at(c.id), "Unmount name", error.TooManyArguments);
        pardes.filesystem.unmount(c.p, name) catch |err| {
            // "no such": the words 9ns reads as ENOENT.
            if (err == error.NotMounted) {
                var said: pardes.Kind.Buf(96) = .{};
                return c.p.reportFailure(c.id, said.print("Unmount: no such mount {s}", .{name}));
            }
            return c.p.reportError(.at(c.id), "Unmount", err);
        };
    }
};

// ---- the message row ----

/// Show its argument on this pane's message row: `Msg built`.
pub const Msg = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub const quiet = true; // it IS the message row
    pub fn run(c: Ctx) void {
        if (c.arg) |text|
            c.p.setMessage(.at(c.id), text)
        else
            c.p.reportError(.at(c.id), comptime word(@This()), error.NoMessage);
    }
};

/// Switch to the next bundled theme.
pub const NextColor = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        colors.setThemeIndex(c.p, (@as(usize, c.p.settings.theme) + 1) % pardes.themes.len);
    }
};

/// List the bundled themes in a +Themes, each a `Theme <name>` line to run.
pub const Themes = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.themes_buffer, .steps = true, .commands = true };
    pub fn run(c: Ctx) void {
        // From the keyboard, where the walk is on: a picker in the tag, the
        // window wearing its row (Pick.zig, SPEC §5.1).
        if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .themes, "", "", "");
        panes.Output.openThemes(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "themes", err);
    }
};

/// Load a theme from a .zon file: `ThemeFile ~/themes/mine.zon`.
///
/// DumpThemes writes the bundled ones out to start from.
pub const ThemeFile = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        var home_buf: [4096]u8 = undefined;
        const arg = c.p.expandHome(std.mem.trim(u8, c.arg orelse return, " \t\r\n"), &home_buf);
        // Said with why, not "invalid theme path".
        if (!std.mem.endsWith(u8, arg, ".zon")) {
            var said: pardes.Kind.Buf(320) = .{};
            return c.p.reportFailure(c.id, said.print("ThemeFile: {s}: invalid theme path: a theme file is a .zon (DumpThemes writes some to start from)", .{arg[0..@min(arg.len, 200)]}));
        }
        colors.requestThemeFile(c.p, c.id, arg);
    }
};

/// Write the bundled themes into the configuration directory's themes, to
/// edit.
///
/// ThemeFile loads one back.
pub const DumpThemes = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        if (c.p.configDir() == null) {
            c.p.reportError(.at(c.id), "dump themes", error.NoConfigDirectory);
            return;
        }
        c.p.emit(.{ .dump_themes = .{ .pane = .at(c.id) } });
    }
};

/// List this machine's fonts in a +Fonts, each a `Font <name>` line to run.
pub const Fonts = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.fonts_buffer, .steps = true, .commands = true };
    pub const enabled = capabilities.font_picker;
    pub const gui_only = true;
    pub const in_window = true;
    pub fn run(c: Ctx) void {
        panes.Output.openFonts(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "fonts", err);
    }
};

/// Show, at the pane's head, the declarations its top row is in.
///
/// `TreeContext on` or `off` sets it; bare, it flips. Only a source file the
/// parser knows has them.
pub const TreeContext = struct {
    pub const takes_arg = true;

    pub fn run(c: Ctx) void {
        if (!panes.File.supportsContext(c.pane)) return c.p.reportFailure(c.id, "TreeContext: only a source file the parser knows has context");
        const file = &c.pane.file.?;
        const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        const on = if (arg.len == 0) !file.tree_context else if (std.mem.eql(u8, arg, "on")) true else if (std.mem.eql(u8, arg, "off")) false else {
            c.p.reportError(.at(c.id), "TreeContext", error.ExpectedOnOrOff);
            return;
        };
        file.tree_context = on;
        file.syntax_dirty = true;
        c.pane.geometry_key = 0;
        c.p.surface.body_layers[c.id].rows = 0;
    }
};

/// A toggle's argument, when it has one: the state its tag word names,
/// set rather than flipped. Null runs no step and says what it takes.
fn stateArg(c: Ctx, comptime T: type, comptime builtin_word: []const u8, comptime takes: []const u8) ?T {
    const a = std.mem.trim(u8, c.arg orelse return null, " \t");
    return std.meta.stringToEnum(T, a) orelse {
        var said: pardes.Kind.Buf(128) = .{};
        c.p.reportFailure(c.id, said.print("invalid argument: " ++ builtin_word ++ " takes " ++ takes ++ ", not \"{s}\"", .{a[0..@min(a.len, 32)]}));
        return null;
    };
}

const OnOff = enum { on, off };

/// Load, unload or reload an addon, a library that brings a kind of pane.
///
/// `Addon load <path>`, `Addon unload <name>`, `Addon reload <name>`; bare,
/// the kinds here.
pub const Addon = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        pardes.Addon.run(c.p, c.id, c.arg);
    }
};

/// Draw an image pane's picture, or a terminal's kitty graphics, as glyph
/// art.
///
/// `Petscii on` or `Petscii off` sets it; bare, it flips. A terminal's kitty
/// graphics are the pictures its program placed (yazi's previews).
pub const Petscii = struct {
    pub const needs: PaneKind = .picture;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        // `on|off` sets it, as the tag's `petscii:on` reads; none flips it.
        const now = if (c.pane.addon) |k| k.art.glyph else c.pane.terminal != null and c.pane.term_petscii;
        if (c.arg != null) {
            const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return;
            if ((want == .on) == now) return;
        }
        if (c.pane.addon) |k| k.art.glyph = !k.art.glyph;
        if (c.pane.terminal != null) c.pane.term_petscii = !c.pane.term_petscii;
    }
};

/// Draw an image pane's glyph art in the C64 palette, or in the terminal's
/// own 16 colours.
///
/// `Palette commodore` or `Palette terminal` sets it; bare, it flips.
pub const Palette = struct {
    pub const needs: PaneKind = .image;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const art = &(c.pane.addon orelse return).art;
        if (c.arg != null) {
            const want = stateArg(c, pardes.Placement.Art.Palette, "Palette", "commodore or terminal") orelse return;
            if (want == art.palette) return;
        }
        art.palette = if (art.palette == .commodore) .terminal else .commodore;
    }
};

/// Add the printable ASCII glyphs to those an image pane's glyph art is made
/// of, or take them out.
///
/// `Ascii on` or `off` sets it; bare, it flips.
pub const Ascii = struct {
    pub const needs: PaneKind = .image;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const art = &(c.pane.addon orelse return).art;
        if (c.arg != null) {
            const want = stateArg(c, OnOff, "Ascii", "on or off") orelse return;
            if ((want == .on) == art.ascii) return;
        }
        art.ascii = !art.ascii;
    }
};

// ---- the system clipboard ----

/// Copy the selection to the system clipboard.
///
/// Every cursor's selection, joined; in an image or a PDF's pane, what it has
/// selected.
pub const ClipYank = struct {
    pub fn run(c: Ctx) void {
        edit.clipYank(c.p, c.pane, false);
    }
};

/// Copy the primary selection alone to the system clipboard.
///
/// ClipYank (`SPC y`) copies every cursor's selection, joined; with one
/// cursor the two are the same.
pub const ClipYankMain = struct {
    pub fn run(c: Ctx) void {
        edit.clipYank(c.p, c.pane, true);
    }
};

/// Paste the system clipboard after the selection.
pub const ClipPaste = struct {
    pub fn run(c: Ctx) void {
        edit.clipRequest(c.p, c.id, .after);
    }
};

/// Paste the system clipboard before the selection.
pub const ClipPasteBefore = struct {
    pub fn run(c: Ctx) void {
        edit.clipRequest(c.p, c.id, .before);
    }
};

/// Replace the selection with the system clipboard.
pub const ClipReplace = struct {
    pub fn run(c: Ctx) void {
        edit.clipRequest(c.p, c.id, .replace);
    }
};

// ---- panes and columns ----

/// Read this pane's file again from disk; refused once over unsaved edits, as
/// Del is.
///
/// `Get <file>` loads that file into the pane instead, the pane taking its
/// name. In a directory's pane, it reads the directory again.
pub const Get = struct {
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const ctl = @import("ninep/ctl.zig");
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Get: " ++ @import("edit_cmd.zig").e_busy);
        const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Get: only a file pane takes it");
        const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        // A directory pane: the directory read again (Dir.zig), as acme's
        // Get is in a directory window; a file is a Look's from there.
        if (f.listing != null) {
            if (typed.len > 0) return c.p.reportFailure(c.id, "Get: a directory pane reads its directory; a Look at the file opens it");
            return panes.Dir.show(c.p, c.id, c.id);
        }
        if (!panes.Output.fileTraits(f.output).saves) return c.p.reportFailure(c.id, "Get: only a file pane takes it");
        var home_buf: [4096]u8 = undefined;
        const path = if (typed.len == 0) c.pane.file.?.path else std.Io.Dir.path.resolvePosix(c.p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), c.p.expandHome(typed, &home_buf) }) catch |err| return c.p.reportError(.at(c.id), "Get", err);
        // A file that is not there, or a directory, is said before unsaved
        // edits are asked about: there would be nothing to load over them.
        if (typed.len > 0) if (@import("fs.zig").localPath(path)) |local| {
            var said: pardes.Kind.Buf(320) = .{};
            const kind = exec.kindOf(c.p.tape, local);
            if (kind == null or kind.? == .directory)
                return c.p.reportFailure(c.id, said.print("Get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (kind == null) "no such file" else "is a directory" }));
        };
        if (ctl.getRefused(c.p, c.pane, "Get")) |said| return c.p.reportFailure(c.id, said);
        const got = if (typed.len == 0) ctl.get(c.p, c.pane) else ctl.getFile(c.p, c.pane, path);
        got catch |err| {
            var said: pardes.Kind.Buf(400) = .{};
            var words: [128]u8 = undefined;
            const why = if (err == error.FileNotFound) "no such file" else pardes.Messages.errorWords(err, &words);
            c.p.reportFailure(c.id, said.print("Get: {s}: {s}", .{ path[0..@min(path.len, 256)], why }));
        };
    }
};

/// Save every pane holding unsaved edits to a file, each as its own Save.
///
/// One that is refused (changed on disk since, a write that fails) says so,
/// and the rest are saved all the same.
pub const Putall = struct {
    // acme's Putall.
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        for (c.p.panes, 0..) |slot, id| {
            const pane = slot orelse continue;
            const f = pane.file orelse continue;
            if (f.output != null or f.listing != null or f.revision == f.saved_revision) continue;
            // A Zerox pair is one buffer: saved once, by its first pane.
            if (f.twin != 0) if (for (c.p.panes[0..id]) |earlier| {
                if ((earlier orelse continue).file) |ef| if (ef.twin == f.twin) break true;
            } else false) continue;
            exec.saveFile(c.p, id);
        }
    }
};

/// Add directories where a Look tries a name it finds nowhere else
/// (`stdio.h`, `<foo.h>`).
///
/// `Incl <dir> ...` adds them, each absolute or from `~`; bare, it lists
/// them; `Incl -` empties the list. The list is the session's.
pub const Incl = struct {
    // acme's Incl, for the session.
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const p = c.p;
        const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (std.mem.eql(u8, typed, "-")) {
            for (p.incl.items) |dir| p.gpa.free(dir);
            p.incl.clearRetainingCapacity();
            return p.setMessage(.at(c.id), "Incl: none");
        }
        // All checked before any is taken: `-` clears, alone; a directory
        // is absolute (or ~) and there.
        var check = std.mem.tokenizeAny(u8, typed, " \t");
        while (check.next()) |dir_word| {
            var said: pardes.Kind.Buf(320) = .{};
            const shown = dir_word[0..@min(dir_word.len, 200)];
            if (std.mem.eql(u8, dir_word, "-")) return p.reportFailure(c.id, "Incl: invalid: - clears the list, alone");
            if (dir_word[0] != '/' and dir_word[0] != '~')
                return p.reportFailure(c.id, said.print("Incl: invalid directory: {s} is relative", .{shown}));
            var home_buf: [4096]u8 = undefined;
            const expanded = p.expandHome(dir_word, &home_buf);
            if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(p.tape, local) != .directory)
                return p.reportFailure(c.id, if (exec.kindOf(p.tape, local) != null)
                    said.print("Incl: not a directory: {s}", .{shown})
                else
                    said.print("Incl: no such directory: {s}", .{shown}));
        }
        var words = std.mem.tokenizeAny(u8, typed, " \t");
        while (words.next()) |dir_word| {
            var home_buf: [4096]u8 = undefined;
            const full = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), p.expandHome(dir_word, &home_buf) }) catch |err| return p.reportError(.at(c.id), "Incl", err);
            if (!std.Io.Dir.path.isAbsolute(full)) return p.reportFailure(c.id, "Incl: invalid directory");
            for (p.incl.items) |dir| {
                if (std.mem.eql(u8, dir, full)) break;
            } else {
                const copy = p.gpa.dupe(u8, full) catch |err| return p.reportError(.at(c.id), "Incl", err);
                p.incl.append(p.gpa, copy) catch |err| {
                    p.gpa.free(copy);
                    return p.reportError(.at(c.id), "Incl", err);
                };
            }
        }
        if (typed.len > 0) return;
        var list: std.Io.Writer.Allocating = .init(p.scratch.allocator());
        list.writer.writeAll("Incl:") catch |err| return p.reportError(.at(c.id), "Incl", err);
        for (p.incl.items) |dir| list.writer.print(" {s}", .{dir}) catch |err| return p.reportError(.at(c.id), "Incl", err);
        if (p.incl.items.len == 0) list.writer.writeAll(" none") catch |err| return p.reportError(.at(c.id), "Incl", err);
        p.setMessage(.at(c.id), list.written());
    }
};

/// Open the plumbing file, the plumber's rules, in the configuration
/// directory beside `init`.
///
/// Saved, they are the rules in force (plumb(6)'s rule sets). Not there yet,
/// it holds `include basic`, the default rules.
pub const Plumb = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        if (std.mem.trim(u8, c.arg orelse "", " \t\r\n").len > 0) return c.p.reportFailure(c.id, PlumbRules.e_word);
        var buf: [4096]u8 = undefined;
        const path = PlumbRules.filePath(c.p, &buf) orelse
            return c.p.reportFailure(c.id, "Plumb: no plumbing file here: no configuration directory");
        openConfigFile(c, "Plumb", path, "include basic\n");
    }
};

/// Open a second pane on this pane's file: the same text, undo and unsaved
/// state.
///
/// Each pane keeps a scroll and a cursor of its own. Only a file's pane takes
/// it.
pub const Zerox = struct {
    // acme's Zerox (File.zerox).
    pub fn run(c: Ctx) void {
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Zerox: " ++ @import("edit_cmd.zig").e_busy);
        const f = c.pane.file orelse return c.p.reportFailure(c.id, "Zerox: only a file pane takes it");
        if (f.output != null or f.listing != null or f.mini != null) return c.p.reportFailure(c.id, "Zerox: only a file pane takes it");
        const free = c.p.freeSlot() orelse return c.p.reportError(.at(c.id), "Zerox", error.NoPaneSlots);
        _ = panes.File.zerox(c.p, c.id, free) catch |err| return c.p.reportError(.at(c.id), "Zerox", err);
        layout.placeNew(c.p, c.id, c.id, free, .doc);
    }
};

/// Write the pane's text to its file, or to the file its argument names.
///
/// `Save <path>` writes it there. Bare, a pane with no file of its own (a
/// +New, a list, a terminal) asks for a path; a file at a revision is
/// read-only, written only to a path. Over a file changed on disk since it
/// was read, it warns once.
pub const Save = struct {
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        // A kind's pane (an image, a PDF) shows a file it does not hold as
        // text: there is nothing of its own to write, bare or to a path.
        // Said, never a silent success.
        if (c.pane.file == null and !c.pane.isTerminal()) {
            const kind = if (c.pane.addon) |k| k.nameOf() else "";
            var said: pardes.Kind.Buf(64) = .{};
            return c.p.reportFailure(c.id, said.print("Save: a{s} {s} pane has no text to save", .{ if (kind.len > 0 and std.mem.indexOfScalar(u8, "aeiou", kind[0]) != null) "n" else "", kind[0..@min(kind.len, 16)] }));
        }
        // A directory's listing is no file to write, bare or to a path, as
        // acme's Put does nothing in a directory window.
        if (c.pane.file) |file| if (file.listing != null) {
            var said: pardes.Kind.Buf(limits.host_path_cap + 48) = .{};
            return c.p.reportFailure(c.id, said.print("Save: {s} is a directory", .{file.path[0..@min(file.path.len, limits.host_path_cap)]}));
        };
        const path = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (path.len > 0) return exec.saveTo(c.p, c.id, path);
        // A file at a revision (jj.zig) is read-only: written elsewhere only.
        if (c.pane.file) |*file| if (@import("jj.zig").of(file) != null) {
            var said: pardes.Kind.Buf(limits.host_path_cap + 64) = .{};
            return c.p.reportFailure(c.id, said.print("Save: {s} is a revision, read-only (Save <path> writes it)", .{file.path[0..@min(file.path.len, limits.host_path_cap)]}));
        };
        // A `+` name is a generated pane's (+Tutor), no file of its own:
        // a bare Save asks for a path, as a +New scratch's does.
        if (c.pane.file) |file| if (file.output == null and !std.mem.startsWith(u8, std.Io.Dir.path.basename(file.path), "+")) return exec.saveFile(c.p, c.id);
        if (c.pane.file != null or c.pane.isTerminal()) panes.startPrompt(c.p, c.pane, &c.pane.body, .save);
    }
};

/// Open an empty scratch pane, +New, in this pane's directory.
///
/// It takes the keyboard. Save asks it for a path to write to; past 100
/// bytes, Exit, Del and Restore ask about its text as about a file's.
pub const New = struct {
    pub const output: OutputTraits = .{ .name = config.scratch_buffer, .doc = true, .saves = true };
    pub fn run(c: Ctx) void {
        c.p.newScratchBelow(c.id);
    }
};

/// Make an empty column right of the keyboard's, its tag taking the keyboard.
///
/// The next pane made from there goes in it. Refused, saying why, when no
/// column fits.
pub const Newcol = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        layout.newColumn(c.p, c.id);
    }
};

/// Close the pane.
///
/// `Del k` gives its rows to the pane above it, `Del j` to the one below,
/// each falling back to the other side; bare, from the keyboard between two
/// panes, it asks k or j on the pane's notice band. A docked pane's rows go
/// back to the pane it answers for. Refused once while the pane holds unsaved
/// text (listed in +Unsaved); Del again, nothing edited since, closes it.
pub const Del = struct {
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const side = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Del: " ++ @import("edit_cmd.zig").e_busy);
        // acme's Del asks winclean first (exec.c del): unsaved text is warned
        // about once, and the same Del again, nothing edited since, closes.
        if (warnModifiedIn(c, .Del, .{ .pane = c.id })) return;
        // A docked pane's rows go back to its owner: nothing to ask.
        if (layout.ownerOf(c.p, c.id)) |owner| return c.p.removePane(c.id, owner) catch |err| c.p.reportError(.at(c.id), "close", err);
        const at = layout.findPane(c.p, c.id);
        const above = if (at) |f| layout.expandedNeighbor(c.p, f.col, f.idx, .above) else null;
        // An owner's docked panes close with it: below is past them.
        const below = if (at) |f| layout.expandedNeighbor(c.p, f.col, layout.groupEnd(c.p, f.col, f.idx) - 1, .below) else null;
        const to: ?usize = if (std.mem.eql(u8, side, "k"))
            above orelse below
        else if (std.mem.eql(u8, side, "j"))
            below orelse above
        else if (side.len > 0)
            return c.p.reportFailure(c.id, "Del: takes k, j or nothing")
        else
            null;
        // Someone at the keyboard with a real choice to make is asked, on the
        // pane's notice band; a click, a 9P write or a script closes it the
        // way it always has. A folded pane gives back only its tag row, and a
        // pane with a prompt open closes as it did rather than trade the
        // prompt for a question.
        if (side.len == 0 and c.p.can_ask and above != null and below != null and
            !c.pane.collapsed and c.pane.prompt == .none)
        {
            c.pane.prompt = .del_side;
            c.pane.question_due_ns = Pane.question_asked;
            c.p.view().active = c.id;
            var rec: [32]u8 = undefined;
            pardes.ctlfs.events.notePath(c.p, "ask", std.fmt.bufPrint(&rec, "{d} del k j", .{c.pane.serial}) catch unreachable); // a u32 fits 32
            // The question says Del already.
            _ = c.p.messages.retire(&.{.echo});
            return;
        }
        c.p.removePane(c.id, to) catch |err| return c.p.reportError(.at(c.id), "close", err);
    }
};

/// Recolour a terminal's or a +Pager's program colours to the theme, or show
/// them as sent.
///
/// Each Filter flips between the two.
pub const Filter = struct {
    pub const needs: PaneKind = .program_colors;
    pub fn run(c: Ctx) void {
        c.pane.tty_filter = !c.pane.tty_filter;
    }
};

/// Turn this text's syntax colours off in this view, or on again.
pub const Syntax = struct {
    // The ink layer (File.Layers).
    pub fn run(c: Ctx) void {
        if (c.pane.file == null) return c.p.reportFailure(c.id, "Syntax: only a text pane has it");
        c.pane.layers.ink = !c.pane.layers.ink;
    }
};

/// Show this file as it was at a jj revision, read-only, beside its pane.
///
/// `At <rev>` (`At main`, `At @-`) opens `path@rev`, as a Look at that name
/// does. In such a pane, `At <rev>` turns it to that revision, the cursor's
/// line kept, and bare `At` opens the file itself. What jj refuses is said in
/// jj's words.
pub const At = struct {
    pub const takes_arg = true;
    pub const run = @import("jj.zig").word;
};

/// Draw jj's changes to this file on its own pane: a lane each, and what they
/// took away.
///
/// `Changes <revset>` pins the revset's changes that touched the file on its
/// pane, or a revision's (`notes.md@main`), and shows them in every view of
/// it: `Changes @-::@`, `Changes trunk()..@`. One set a pane: a later Changes
/// or Compare replaces it. Bare: hidden, or shown again; with none pinned
/// yet, `@`.
///
/// Each change gets a lane after the line number. What the file no longer has
/// stands where it stood as lines of the pane's text with no number,
/// read-only: the cursor, a selection, a search, B2 and B3 work there, and an
/// edit that touches one is refused. After a change's last line comes its
/// description, `id title author age`, its lane ending in an arrow at it; a
/// long one wraps. `] g` and `[ g` step through the changes; B3 on a
/// description's id opens that change's patch at that line
/// (`Diff <id> <path>:<line>`).
pub const Changes = struct {
    pub const takes_arg = true;
    pub const run = @import("jj.zig").changesWord;
};

/// Draw the file's difference between each two jj revisions as one change, as
/// Changes draws one.
///
/// `Compare <rev> <rev> [<rev> ...]`: two points or more in their order, each
/// one revision (a commit or change id, a bookmark, `master@origin`, `@`):
/// `Compare 9ef6312813 ea63317630 master@origin`. A pair is drawn as one
/// change however many lie between its points; after its last line, its row:
/// the two points, how many changes lie between them, their first and last
/// days. One set a pane: a later Changes or Compare replaces it. Bare: as
/// bare Changes.
pub const Compare = struct {
    pub const takes_arg = true;
    pub const run = @import("jj.zig").compareWord;
};

/// Show how many changes touched each declaration of this file, as a heat
/// lane.
///
/// `Churn <window>`: a revset, or a span of time back from now (`3d`, `2w`,
/// `6m`, `1y`). In this view a cell after the line number, from the line
/// numbers' grey to the theme's red on a log scale, and a strip by the scroll
/// thumb. Bare: hidden in this view or shown again; with none counted yet,
/// the file's whole history.
pub const Churn = struct {
    pub const takes_arg = true;
    pub const run = @import("jj.zig").churnWord;
};

/// Show a diff's hunks stacked in a +Diff, each under its place, as a diff
/// viewer shows them.
///
/// Bare, on a diff (a .diff, a .patch, a +Pager holding one): its hunks
/// stacked; on a +Diff: the diff itself, as text. `Diff <file>`: that .diff's
/// or .patch's hunks. `Diff <hash>` (7 to 40 hex digits): `git show` of that
/// commit, in its own `+Diff-<hash>`. `Diff <change> [path[:line]]` (a jj
/// change id): its patch, its header and whole message on top, the cursor at
/// that place. `Diff <from>..<to> [path[:line]]`: the difference between two
/// points, the changes between them on top.
///
/// Each hunk stands under its `path:line` and the declarations around it, a +
/// or - before each line, the words a changed line changed tinted. `SPC j n`
/// and `SPC j p` step through the hunks; B3 on a place opens it.
pub const Diff = struct {
    // The diff viewer's one registration: its word and traits here, all else
    // its own (hunks.zig).
    pub const takes_arg = true;
    pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true };
    pub const run = @import("hunks.zig").word;
};

/// Step this pane to its next input mode: normal, insert, and in a terminal
/// raw.
///
/// From the last it goes back to normal. The keyboard goes to the pane's
/// text.
pub const Mode = struct {
    pub fn run(c: Ctx) void {
        if (c.pane.file == null and !c.pane.isTerminal()) return c.p.reportFailure(c.id, "Mode: only a text or terminal pane has modes");
        keys.cycleMode(c.p, c.id);
    }
};

/// Switch this terminal between raw mode, its keys the program's, and normal
/// mode.
pub const Togglettymode = struct {
    pub const needs: PaneKind = .terminal;
    pub fn run(c: Ctx) void {
        keys.toggleTty(c.p, c.id);
    }
};

/// Run a command of sam's language over the open text panes, starting in this
/// pane's body.
///
/// `Edit ,s/old/new/g` changes every old to new in this pane's text. As
/// acme's Edit: from a tag, a pane's ctl or an exec; one undo step in each
/// file it changes; a failure changes nothing and says why. Left out of
/// sam's: the `'` address, `B <cmd` and `D <cmd`, and `\1` to `\9` in `s`.
pub const Edit = struct {
    // acme's Edit (exec.c `edit`, edit.c). core/edit_cmd.zig runs it;
    // core/sam_edit.zig has what is left out.
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        @import("edit_cmd.zig").run(c.p, c.id, c.arg orelse "");
    }
};

/// Step the pane's text back one edit.
///
/// With no step left, it says so and changes nothing (a ctl write of it still
/// succeeds, as acme's Undo is silent there). A file keeps 256 steps.
pub const Undo = struct {
    // acme's Undo and Redo (exec.c `undo`); limits.undo_max steps.
    pub fn run(c: Ctx) void {
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Undo: " ++ @import("edit_cmd.zig").e_busy);
        if (c.pane.file) |f| if (f.history.journal.done == 0) return c.p.setMessage(.at(c.id), "Undo: nothing to undo");
        edit.undoStep(c.p.editor(), &c.pane.body, true) catch |err| c.p.reportError(.at(c.id), "Undo", err);
    }
};

/// Step the pane's text forward again, one edit Undo took back.
///
/// With none left, it says so and changes nothing.
pub const Redo = struct {
    pub fn run(c: Ctx) void {
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Redo: " ++ @import("edit_cmd.zig").e_busy);
        if (c.pane.file) |f| if (f.history.journal.done == f.history.journal.steps.items.len) return c.p.setMessage(.at(c.id), "Redo: nothing to redo");
        edit.undoStep(c.p.editor(), &c.pane.body, false) catch |err| c.p.reportError(.at(c.id), "Redo", err);
    }
};

/// Fold this pane to its tag, or give it its share of the column again.
pub const Collapse = struct {
    pub fn run(c: Ctx) void {
        layout.toggleCollapse(c.p, c.id);
    }
};

/// Undock a pane from the pane it answers for: it stays where it is, a pane
/// of its own.
///
/// The next search from that pane opens another under it.
pub const Undock = struct {
    pub fn run(c: Ctx) void {
        if (c.pane.docked_to == null) return c.p.reportFailure(c.id, "Undock: not docked to a pane");
        c.pane.docked_to = null;
    }
};

/// Close this column and its panes.
///
/// The column is the one whose tag it ran from, else the pane's. Refused once
/// while a pane in it holds unsaved text, the notice saying how many; Delcol
/// again, nothing edited since, closes them.
pub const Delcol = struct {
    pub fn run(c: Ctx) void {
        // The column of the tag it came from, else the pane's: a pane ctl's
        // Delcol closes that pane's column wherever the keyboard is.
        const col = c.p.exec_column orelse (layout.findPane(c.p, c.id) orelse return).col;
        // acme's Delcol refuses a column with unsaved text (exec.c delcol,
        // cols.c colclean), once: the next Delcol closes it.
        if (warnModifiedIn(c, .Delcol, .{ .column = col })) return;
        layout.removeColumn(c.p, col) catch |err| c.p.reportError(.at(c.id), "close column", err);
    }
};

/// Close the pane, giving its rows to the pane above it, as `Del k` does.
pub const DelAbove = struct {
    pub fn run(c: Ctx) void {
        Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "k" });
    }
};

/// Close the pane, giving its rows to the pane below it, as `Del j` does.
pub const DelBelow = struct {
    pub fn run(c: Ctx) void {
        Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "j" });
    }
};

/// Open a terminal below this pane, in its directory, raw: its keys the
/// shell's at once.
///
/// `Term fish` runs that shell instead of the Shell setting's, as a
/// terminal's own tag word `Term+fish` says; a shell that is not there is
/// said. A directory that is not there makes no terminal.
pub const Term = struct {
    pub const takes_arg = true;
    pub const plus_arg = true;
    pub fn run(c: Ctx) void {
        const arg = std.mem.trim(u8, c.arg orelse "", " \t");
        // A shell that is not there is said, where the host would quietly
        // start its fallback in its place.
        if (arg.len > 0) {
            var why: [320]u8 = undefined;
            // The authority's lookup, taped, as Shell's (exec.zig).
            if (c.p.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ arg[0..@min(arg.len, 200)], &why })) |refused| {
                var said: pardes.Kind.Buf(340) = .{};
                return c.p.reportFailure(c.id, said.print("Term: {s}", .{refused}));
            }
        }
        const pane = exec.spawnTty(c.p, c.id) orelse return;
        if (arg.len > 0) pane.shell = c.p.gpa.dupe(u8, arg) catch null;
    }
};

/// Bind this terminal as a language's REPL: an exec on that language's files
/// is typed into it.
///
/// `Repl python` binds it (the language named as a code fence names it: `py`,
/// `Python`, `sh`); `Repl -` unbinds it; bare, it says what it is bound as.
/// An exec made on the body of a file in that language (a middle click, the
/// execute key, a single word like `ls` as much as a selection), and one made
/// on this terminal's own body, is typed into it (bracketed paste if its
/// program asked for that, else line by line, then Enter) instead of run.
/// With several bound for a language, the exec asks which.
///
/// Still commands, whatever is bound: a word in a tag, `Exec <text>`, a ctl
/// line, and a command word @`cmd` in the text, looked at or clicked.
pub const Repl = struct {
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        const pane = c.pane;
        // A terminal with its emulator -- not a document pane -- and not
        // a command pane whose command, the REPL it would be, is done.
        if (!pane.isTerminal() or pane.terminal == null) return c.p.reportFailure(c.id, "Repl: only a terminal is a REPL");
        if (pane.command != null and pane.command_done) return c.p.reportFailure(c.id, "Repl: its command is done; a REPL is a running program");
        const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        var buf: pardes.Kind.Buf(320) = .{};
        var idbuf: [48]u8 = undefined;
        if (arg.len == 0) {
            if (pane.repl == null) return c.p.setMessage(.at(c.id), "Repl: not bound");
            return c.p.setMessage(.at(c.id), buf.print("Repl: {s}", .{exec.replId(&idbuf, pane)}));
        }
        if (std.mem.eql(u8, arg, "-")) {
            pane.repl = null;
            return c.p.setMessage(.at(c.id), "Repl: unbound");
        }
        const manifest = @import("grammar_manifest.zig");
        const grammars = manifest.all;
        // Named as a code fence names it: `py`, `Python`, `sh`.
        const named: ?u8 = if (manifest.byName(arg)) |i| if (grammars[i].exts.len > 0) @intCast(i) else null else null;
        const lang: u8 = named orelse {
            // A few, whole, and where the rest are: a list cut to fit the
            // row would end mid-word.
            var w = std.Io.Writer.fixed(&buf.bytes);
            list: {
                // A list past the room is cut at its end.
                w.print("Repl: invalid language \"{s}\"; - or one like", .{@import("Messages.zig").clip(arg, 24)}) catch break :list;
                // Those that start as the word does first, a misspelling's
                // likeliest meaning (pithon: python).
                var shown: usize = 0;
                var known: usize = 0;
                for ([2]bool{ true, false }) |alike| for (grammars) |g| if (g.exts.len > 0) {
                    const starts = arg.len > 0 and g.name[0] == std.ascii.toLower(arg[0]);
                    if (starts != alike) continue;
                    known += 1;
                    if (shown < 6) {
                        w.print(" {s}", .{g.name}) catch break :list;
                        shown += 1;
                    }
                };
                w.print(" ({d} more)", .{known - shown}) catch break :list;
            }
            return c.p.reportFailure(c.id, w.buffered());
        };
        if (pane.repl) |r| if (r.lang == lang)
            return c.p.setMessage(.at(c.id), buf.print("Repl: {s}", .{exec.replId(&idbuf, pane)}));
        // The lowest letter no other REPL of the language has: freed ones
        // come back.
        var letter: u8 = 'a';
        while (letter <= 'z') : (letter += 1) {
            const taken = for (c.p.panes) |slot| {
                const other = slot orelse continue;
                if (other != pane) if (other.repl) |r| if (r.lang == lang and r.letter == letter) break true;
            } else false;
            if (!taken) break;
        }
        if (letter > 'z') return c.p.reportFailure(c.id, "Repl: every letter of the language is taken");
        pane.repl = .{ .lang = lang, .letter = letter };
        pane.repl_warned = false;
        c.p.setMessage(.at(c.id), buf.print("Repl: {s}", .{exec.replId(&idbuf, pane)}));
    }
};

/// Fold the keyboard's column into the one on its right, keeping its panes.
///
/// Refused for the last column, and where the joined column could not give
/// each pane its tag and 2 rows.
pub const Joincol = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        // The keyboard's column joins the one to its right; the last has none.
        const col = layout.keyboardColumn(c.p, c.p.view().active) orelse return;
        if (col + 1 >= c.p.view().ncol) return c.p.reportFailure(c.id, "Joincol: no column to the right");
        // As Newcol is refused: a column that could not give each pane its
        // tag and 2 rows would leave a layout `size` refuses as it is.
        if (!layout.joinFits(c.p, col)) return c.p.reportFailure(c.id, "Joincol: no space: the joined column cannot give each pane its tag and 2 rows");
        layout.joinCol(c.p, col);
    }
};

/// Open the tutor, a document to work through.
pub const Tutor = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        const free = c.p.freeSlot() orelse return c.p.reportError(.at(c.id), "Tutor", error.NoPaneSlots);
        _ = panes.openTutorView(c.p, free) catch |err| return c.p.reportError(.at(c.id), "Tutor", err);
        layout.placeNew(c.p, c.id, c.id, free, .doc); // a doc like any other
    }
};

/// Show every builtin with its keys and documentation, or one builtin's alone.
///
/// `Help <name>`: that builtin alone, its keys spelled out, what it acts on
/// and its line for a shell (`Help Diff`); a setting or an addon's word the
/// same. `Help <keys>`: the builtins under SPC and those keys (`Help l`, as
/// `SPC l ?` shows them). Each fills the one +Help: a second Help replaces
/// its text.
pub const Help = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub const output: OutputTraits = .{ .name = config.help_buffer };
    pub fn run(c: Ctx) void {
        const what = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (what.len == 0) return panes.Output.openHelp(c.p, c.id, "") catch |err| c.p.reportError(.at(c.id), "help", err);
        const found = panes.Output.openHelpOn(c.p, c.id, what) catch |err| return c.p.reportError(.at(c.id), "help", err);
        if (found) return;
        var said: pardes.Kind.Buf(128) = .{};
        c.p.reportFailure(c.id, said.print("Help: {s}: no such builtin, nor SPC keys", .{what[0..@min(what.len, 64)]}));
    }
};

/// Show what a key sequence runs: the next keys typed are replayed in the tag.
///
/// The tag shows `Keys` and the keys as they are typed; a sequence that
/// reaches a leaf unrolls its level under the tag with the leaf on the
/// cursor and its documentation beside it, and Enter runs it. Every root
/// answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing
/// is bound to is shown struck, `runs nothing`. Esc leaves it.
pub const Keys = struct {
    pub fn run(c: Ctx) void {
        pardes.TagState.openDescribe(c.p, c.id);
    }
};

/// Open the startup file, `init` in the configuration directory, in a pane.
///
/// Its pane when it is open, else the file; not there yet, a pane of that
/// name, which Save makes, its directory too.
pub const Config = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        const path = c.p.startupPath() orelse
            return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory");
        openConfigFile(c, "Config", path, "");
    }
};

/// A file of the configuration directory's (Config's init, Plumb's
/// plumbing) in a pane: its pane when it is open, else the file, else a
/// pane of that name holding `initial`, for Save to make it and its
/// directory.
fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u8) void {
    var real_buf: [4096]u8 = undefined;
    const real = if (pardes.filesystem.resolveOs(c.p.tape, path, &real_buf)) |r| r.path else null;
    for (c.p.panes, 0..) |slot, id| {
        const pane = slot orelse continue;
        const f = pane.file orelse continue;
        if (f.output != null) continue;
        if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue;
        return look.focusPaneLine(c.p, id, .{}, .keep);
    }
    if (real != null) return look.lookAt(c.p, c.id, path);
    // Not there yet: a pane named for it, which Save makes.
    const free = c.p.freeSlot() orelse return c.p.reportError(.at(c.id), name, error.NoPaneSlots);
    panes.newScratchFor(c.p, c.id, .scratch);
    const made = c.p.panes[free] orelse return;
    @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(.at(c.id), name, err);
    if (initial.len > 0) if (made.file) |*f| {
        _ = panes.File.replace(c.p, f, 0, f.content.len, initial);
    };
    c.p.view().active = free;
}

/// Show the settings in effect in a +DumpConfig, as lines the startup file
/// takes.
///
/// The startup file's path with them; a line run there is that setting.
pub const DumpConfig = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.dump_config_buffer };
    pub fn run(c: Ctx) void {
        panes.Output.openConfig(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "config", err);
    }
};

/// Set how a list's location rows are drawn: `LocationsConfig layout:inline
/// context:2`.
///
/// Its fields: `context:<lines>` around each, `tscontext:on|off`,
/// `tslocations:on|off`, `layout:inline|stacked`; those not given stay. Bare,
/// it shows them in a +LocationsConfig.
pub const LocationsConfig = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub const output: OutputTraits = .{ .name = "+LocationsConfig" };

    pub fn run(c: Ctx) void {
        const argument = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        const next = c.p.locations_config.parse(argument) catch |err| {
            c.p.reportError(.at(c.id), "LocationsConfig", err);
            return;
        };
        c.p.locations_config = next;
        // Bare, it is a question, and the window is the answer. With arguments
        // it is a setting, and a setting that opens a window is noise.
        if (argument.len != 0) return;
        report(c) catch |err| c.p.reportError(.at(c.id), "LocationsConfig", err);
    }

    fn report(c: Ctx) !void {
        var out: std.Io.Writer.Allocating = .init(c.p.gpa);
        errdefer out.deinit();
        try out.writer.writeAll("LocationsConfig ");
        try c.p.locations_config.write(&out.writer);
        try out.writer.writeByte('\n');
        const content = try out.toOwnedSlice();
        const dir = if (c.pane.file) |file| panes.Dir.ofName(file.path) else c.pane.cwdSlice();
        try panes.Output.fillResults(c.p, c.id, dir, .{ .cmd = .LocationsConfig }, "", content, null);
    }
};

/// Act on the message the notice row leads with.
///
/// On a line a message names, its detail not shown yet: that detail, under
/// the line until the caret leaves it. Else an error that names places
/// lands them as a list in the pane's walk, n and N walking them (where jumps do not walk, a +Search the Look walk
/// steps through); a question takes the keyboard in its pane's tag (its
/// answer's key answers it, Esc leaves it waiting); anything else opens the
/// history.
pub const Message = struct {
    pub const quiet = true;
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        pardes.Messages.act(c.p, c.id);
    }
};

/// Show the messages said so far, the newest first, an error's places
/// under it.
///
/// Where jumps walk, a list in the pane's tag: Enter Looks a row (a
/// message's cause, a place), C-q keeps it as a +Messages; else the
/// +Messages.
pub const Messages = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.messages_buffer };
    pub fn run(c: Ctx) void {
        pardes.Messages.history(c.p, c.id);
    }
};

/// Show this build in a +Build: its version, compiler, optimize mode, target
/// and dependencies.
///
/// A stamped build's (a release, or the ~/.local install) commit, jj change
/// and build time too, its platform, its grammars, and whether the addons are
/// compiled in.
pub const Build = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.build_buffer };
    pub fn run(c: Ctx) void {
        panes.Output.openBuild(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "build", err);
    }
};

/// Show this build's version and what changed to reach it, in a +Changelog.
pub const Changelog = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.changelog_buffer };
    pub fn run(c: Ctx) void {
        panes.Output.openChangelog(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "changelog", err);
    }
};

/// Map a file of this pane's directory in braille dots: `Mini notes.txt`.
///
/// A pane of its own, drawn once: a Mini of the same file again draws it
/// anew.
pub const Mini = struct {
    pub const takes_arg = true;
    pub const requires_arg = true; // a file to map: bare, wrong #args (EINVAL)
    pub const output: OutputTraits = .{ .name = "Mini", .doc = true };

    pub fn run(c: Ctx) void {
        panes.mini.open(c.p, c.id, c.arg orelse "") catch |err|
            c.p.reportError(.at(c.id), "Mini", err);
    }
};

// ---- search ----

/// A Find or Grep that finds nothing fails as one, in words 9ns reads as
/// ENOENT (`not found`), the same for both.
const e_search_miss_find = "Find: name not found";
const e_search_miss_grep = "Grep: text not found";

/// List the files below this pane's directory whose names match its argument.
///
/// A query pane under this pane, its line 1 `Find <name>`, the files under it
/// by a fuzzy match of their names: with a word, listed, the keyboard left
/// where it was; bare (`SPC f f`), typed into. Enter or B3 on a row opens
/// that file. A script's Find that finds nothing fails, `not found`.
pub const Find = struct {
    pub const takes_arg = true;
    // A script's Find names what to find (bare, it is a key's prompt).
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        search(c, .find, e_search_miss_find);
    }
};

/// List the lines of the files below this pane's directory that hold its
/// argument.
///
/// The text is matched as it is, not as a pattern, in a query pane under this
/// pane, its line 1 `Grep <text>`: with a word, listed, the keyboard left
/// where it was; bare (`SPC f g`), typed into. Past 2000 lines it stops, and
/// More goes on. A script's Grep that finds nothing fails, `not found`.
pub const Grep = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        search(c, .grep, e_search_miss_grep);
    }
};

/// Find's and Grep's query pane under this pane, line 1 the source's word
/// and the argument: bare (SPC f f) typed into; with a word (B2, a script)
/// listed, the keyboard left where it was. A script's (a 9P write runs it
/// to its end before it answers) that found nothing fails as one, opening
/// nothing: a query pane it made goes as an Esc takes it, one it reused
/// stays, its count 0; the write hears `not found`.
fn search(c: Ctx, source: panes.Query.Source, miss: []const u8) void {
    const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, if (source == .find) .find else .grep, "", pat, "");
    const reused = panes.Query.ofOwner(c.p, c.pane.serial) != null;
    panes.Query.open(c.p, c.id, source, pat, pat.len == 0);
    if (pat.len == 0 or !c.p.fs.serving) return;
    const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return;
    if (c.p.panes[qid].?.query.?.total != 0) return;
    if (!reused) panes.Query.cancel(c.p, qid);
    c.p.reportFailure(c.id, miss);
}

/// Search in a query pane under this pane, its line 1 the argument.
///
/// Line 1's first word names what it searches: `/re` this pane's text,
/// `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All` (every open pane's
/// text), `Refs`, `Def`, `Impl`, `Diagnostics`; a line with none of them is a
/// `/`: `Search lay` is `/lay`. Bare, `/`, typed into. `SPC b b`, `SPC s s`
/// and `SPC /` open it with Panes, Symbols and All.
pub const Search = struct {
    pub const takes_arg = true;
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?;
        // `SPC b b`, `SPC s s`, `SPC /` and the like: a picker in the tag.
        if (pardes.Pick.asked(c.p)) switch (asked.source) {
            inline .find, .grep, .recent, .panes, .symbols, .all => |s| return pardes.Pick.open(c.p, c.id, @field(pardes.Pick.Source, @tagName(s)), "", asked.pat, ""),
            else => {},
        };
        panes.Query.open(c.p, c.id, asked.source, asked.pat, true);
    }
};

/// Let a query pane's Grep stopped at its 2000 lines go on for 2000 more.
pub const More = struct {
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        if (!pardes.Stream.moreFor(c.p, c.id)) c.p.reportFailure(c.id, "More: no search is waiting at its cap");
    }
};

/// Pick a pane by its name, in a query pane under this one.
///
/// The open panes, then those closed this session, `(closed)`: Enter on one
/// goes to it, or brings a closed one back where it was, its text with it.
/// `Panes <name>` narrows them; `SPC b b` opens the same query.
pub const Panes = struct {
    pub const takes_arg = true;
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .panes, "", std.mem.trim(u8, c.arg orelse "", " \t\r\n"), "");
        panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true);
    }
};

// ---- the window group ----

// The headers are above the panes in the same layout: Up from a pane with
// nothing above it reaches its column's tag, then the workspace's, and Down
// comes back the same way. Left and Right walk the column tags.

/// Move the keyboard to the pane, or column tag, to the left.
pub const Left = struct {
    pub fn run(c: Ctx) void {
        if (c.p.view().header != null) {
            if (c.p.headerColumn()) |column| if (column > 0) tagline.enterHeader(c.p, column - 1);
            return;
        }
        _ = layout.focusDir(c.p, c.id, .left);
    }
};

/// Move the keyboard to the pane below, or off a tag onto the pane under it.
pub const Down = struct {
    pub fn run(c: Ctx) void {
        if (c.p.view().header != null) {
            const column = layout.findPane(c.p, c.id);
            if (c.p.headerColumn() == null and layout.columnBarHeight(c.p) > 0)
                return tagline.enterHeader(c.p, if (column) |at| at.col else 0);
            // Onto the top pane of the column the header stands over.
            const col = c.p.headerColumn() orelse if (column) |at| at.col else return;
            // An empty column's tag has nothing below it.
            if (col < c.p.view().ncol and c.p.view().cols[col].n == 0) return;
            tagline.exitHeader(c.p);
            if (col < c.p.view().ncol) c.p.view().active = c.p.view().cols[col].panes[0];
            return;
        }
        _ = layout.focusDir(c.p, c.id, .down);
    }
};

/// Move the keyboard to the pane above, and from a column's top pane to its
/// tag.
pub const Up = struct {
    pub fn run(c: Ctx) void {
        if (c.p.view().header != null) {
            if (c.p.headerColumn() != null and c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null);
            return;
        }
        if (layout.focusDir(c.p, c.id, .up)) return;
        if (layout.columnBarHeight(c.p) > 0) {
            if (layout.findPane(c.p, c.id)) |at| tagline.enterHeader(c.p, at.col);
        } else if (c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null);
    }
};

/// Move the keyboard to the pane, or column tag, to the right.
pub const Right = struct {
    pub fn run(c: Ctx) void {
        if (c.p.view().header != null) {
            if (c.p.headerColumn()) |column| if (column + 1 < c.p.view().ncol) tagline.enterHeader(c.p, column + 1);
            return;
        }
        _ = layout.focusDir(c.p, c.id, .right);
    }
};

/// Show one text across a chain of panes as consecutive pages, scrolled as
/// one.
///
/// As Emacs's follow-mode: each page goes on where the one before ends. Each
/// Follow adds a page, a Zerox of the text, at the end of the column right of
/// the chain's last, or in a new column there; its tag has Unfollow.
pub const Follow = struct {
    pub fn run(c: Ctx) void {
        if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Follow: " ++ @import("edit_cmd.zig").e_busy);
        const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Follow: only a file pane takes it");
        if (f.output != null or f.listing != null or f.mini != null) return c.p.reportFailure(c.id, "Follow: only a file pane takes it");
        // One chain a text: the new page goes after its last, in column order.
        const v = c.p.view();
        var last = c.id;
        for (v.cols[0..v.ncol]) |col| for (col.panes[0..col.n]) |id| {
            const other = if (c.p.panes[id].?.file) |*file| file else continue;
            if (f.twin != 0 and other.twin == f.twin and other.follow) last = id;
        };
        if (!f.follow and last != c.id) return c.p.reportFailure(c.id, "Follow: this text has a chain: Follow on one of its panes");
        const col = (layout.findPane(c.p, last) orelse return c.p.reportFailure(c.id, "Follow: the pane is not laid out")).col;
        const free = c.p.freeSlot() orelse return c.p.reportError(.at(c.id), "Follow", error.NoPaneSlots);
        const made = panes.File.zerox(c.p, c.id, free) catch |err| return c.p.reportError(.at(c.id), "Follow", err);
        const keep = v.active;
        if (col + 1 < v.ncol) {
            c.p.exec_column = col + 1;
            defer c.p.exec_column = null;
            layout.placeNew(c.p, c.id, null, free, .scratch);
            if (c.p.unplaced.isSet(free)) return;
        } else if (!layout.splitColumn(c.p, last, free, false)) {
            c.p.unplaced.set(free);
            return c.p.reportFailure(c.id, "Follow: no space for a column: this one is too narrow to split");
        }
        // The keyboard stays on the page it was on.
        v.active = keep;
        if (layout.findPane(c.p, keep)) |at| c.p.setActiveColumn(at.col);
        f.follow = true;
        made.file.?.follow = true;
        c.pane.follow_scroll = f.scroll;
        made.follow_scroll = made.file.?.scroll;
        made.appendTag(" Unfollow") catch |err| c.p.reportError(.at(c.id), "Follow", err);
    }
};

/// Take this pane out of its Follow chain.
///
/// It stays, a Zerox twin with the scroll it has, and the chain closes up
/// behind it.
pub const Unfollow = struct {
    pub fn run(c: Ctx) void {
        const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Unfollow: this pane is in no Follow chain");
        if (!f.follow) return c.p.reportFailure(c.id, "Unfollow: this pane is in no Follow chain");
        panes.File.unchain(c.pane);
    }
};

/// Window mode: move an outline between the panes and act on the one
/// outlined.
///
/// h/j/k/l move the outline; Enter or Esc focuses the outlined pane, `:` its
/// tag, the letter shown on a pane that one; d is Del on it (then k or j
/// between two), c Collapse.
pub const Window = struct {
    pub fn run(c: Ctx) void {
        tagline.exitHeader(c.p);
        c.p.view().window_pick = if (c.p.panes[c.id] != null) c.id else c.p.view().active;
    }
};

// ---- the jump group ----

/// Go one step back in the jump history.
///
/// A place in a file closed since opens the file again.
pub const Back = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        Jump.jumpBy(c.p, -1);
    }
};

/// Go one step forward again in the jump history, up to where Back started.
pub const Forward = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        Jump.jumpBy(c.p, 1);
    }
};

/// Reopen the last picker as it was: its rows, marks, cursor and query.
///
/// In the tag of the pane its Enter lands in from this one: this pane if it
/// reads, else its reader. `SPC '`; again after its Esc, nothing typed
/// between, the one before it; Ctrl-o and Ctrl-i in it, the older and newer.
pub const Resume = struct {
    pub fn run(c: Ctx) void {
        pardes.Pick.resumeFrom(c.p, c.id);
    }
};

/// Pick from the last pickers kept, newest first: Enter reopens one as it was left.
///
/// A row each: its source, query, cursor and marks, where it last landed at
/// its right. The body previews its current row; beside the rows, its
/// first rows. `SPC f l`, or `'` in a picker's sources (M-h).
pub const Lists = struct {
    pub const scope: Scope = .session;
    pub fn run(c: Ctx) void {
        if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Lists: open a pane to pick from");
        pardes.Pick.open(c.p, c.id, .lists, "", "", "");
    }
};

/// Keep this pane: a reading pane, which a jump steps, is held from now on.
///
/// Its walk leaves its tag (its places, its owner): the next jump from its
/// owner makes a new reader. Editing a reading pane keeps it too.
pub const Keep = struct {
    pub fn run(c: Ctx) void {
        if (!pardes.Trail.reading(c.p, c.pane)) return c.p.setMessage(.at(c.id), "Keep: this pane is held already");
        pardes.Trail.keep(c.pane);
    }
};

/// Select the next thing a Look would open: a place in a list, a word that
/// names a file.
///
/// The walk goes on through the panes in order, the keyboard with it; Enter
/// opens what it selected.
pub const LookNext = struct {
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        look.lookWalk(c.p, 1, true);
    }
};

/// Select the previous thing a Look would open, as LookNext walks forward.
///
/// Enter opens what it selected.
pub const LookPrev = struct {
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        look.lookWalk(c.p, -1, true);
    }
};

/// Go back to the last place jumped from in another pane.
///
/// With none, to the pane beside this one.
pub const Last = struct {
    pub fn run(c: Ctx) void {
        var i = c.p.view().jumps.n;
        while (i > 0) {
            i -= 1;
            const j = c.p.view().jumps.list[i];
            if (j.serial == 0) continue; // a closed file's: Back reopens it, Last goes to a pane
            // Restore the cursor without recentering the pane's retained view.
            if (j.pane != c.id) return look.focusPaneLine(c.p, j.pane, .{ .line = j.line, .col = j.col }, .keep);
        }
        // Nothing on the jumplist to go back to, which is the ordinary case
        // for a pane that opened beside this one and was never focused.
        if (panes.neighbourPane(c.p, c.id)) |next| look.focusPaneLine(c.p, next, .{ .line = 0, .col = 0 }, .keep);
    }
};

/// List the files opened lately, closed ones too, in a query pane under this
/// one.
///
/// `Recent <name>` narrows them by name; bare (`SPC f r`), typed into. Enter
/// opens the current one; B3 on a row, that one.
pub const Recent = struct {
    pub const scope: Scope = .session;
    pub const takes_arg = true;
    pub fn run(c: Ctx) void {
        // The query pane under the pane the keyboard is in, line 1
        // `Recent `, typed into; what follows the word narrows the files.
        if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from");
        if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .recent, "", std.mem.trim(u8, c.arg orelse "", " \t\r\n"), "");
        panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true);
    }
};

/// List the state file's dumps, newest first, each with the Restore that
/// brings it back.
///
/// Those Dump made and those every session's end left, in a +History: each a
/// `Restore <label>` line, its date, size and pane count, the panes' names
/// indented under it. B2 on the Restore, or a Look at its line, is that
/// Restore.
pub const History = struct {
    // A session's end dumps it (dump.dumpExit).
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.history_buffer };
    pub fn run(c: Ctx) void {
        panes.Output.openHistory(c.p, c.id) catch |err| switch (err) {
            error.NoStateFile => c.p.reportFailure(c.id, "History: no state file to list (DumpDir)"),
            error.NoDumps => c.p.reportFailure(c.id, "History: no dumps yet"),
            else => c.p.reportError(.at(c.id), "History", err),
        };
    }
};

/// List the places jumped from in a +Jumps, each a place to go.
pub const Jumplist = struct {
    pub const scope: Scope = .session;
    pub const output: OutputTraits = .{ .name = config.jumps_buffer, .steps = true, .locations = true };
    pub fn run(c: Ctx) void {
        if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .jumplist, "", "", "");
        panes.Output.openJumps(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "jumplist", err);
    }
};

// ---- the language group ----

/// Go to the definition of the symbol under the cursor.
///
/// With an argument (a 2-1 chord's selection), of that symbol, asked at its
/// occurrence nearest the cursor. One answer is a jump; several open a list,
/// the keyboard on its current row; none says so. `g d` does the same.
pub const Def = struct {
    pub const takes_arg = true;
    /// Its answer says what it found, a jump or a list or why not; its
    /// name would only stack above it, as gd never did.
    pub const quiet = true;
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .definition, std.mem.trim(u8, c.arg orelse "", " \t\r\n"));
    }
};

/// List the references to the symbol under the cursor.
///
/// With an argument (a 2-1 chord's selection), to that symbol, asked at its
/// occurrence nearest the cursor; a single reference is a jump. `g r` does
/// the same.
pub const Refs = struct {
    pub const takes_arg = true;
    pub const quiet = true; // as Def
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .references, std.mem.trim(u8, c.arg orelse "", " \t\r\n"));
    }
};

/// Ask the language server about the symbol under the cursor, its answer in a
/// +Hover.
pub const Hover = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .hover, "");
    }
};

/// List the language server's code actions for the cursor, to apply one.
///
/// Typed where jumps walk, they are a picker in the pane's tag, the one
/// under the cursor shown as its edit, applied by Enter or its digit; else
/// a +Lsp lists them.
pub const CodeAction = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .code_action, "");
    }
};

/// Select every reference to the symbol under the cursor.
pub const SelectRefs = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .select_refs, "");
    }
};

/// List this file's symbols in a +Search.
pub const Symbols = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .document_symbols, "");
    }
};

/// List this file's diagnostics in a +Search.
///
/// `] d` and `[ d` step through them in the text, `] D` and `[ D` to the last
/// and the first.
pub const Diagnostics = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .diagnostics, "");
    }
};

/// List the diagnostics of the whole workspace in a +Search.
pub const WsDiagnostics = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .workspace_diagnostics, "");
    }
};

/// Run the file's language indexer at its project root, writing its
/// index.scip.
///
/// The language words ask the nearest index.scip above a file first, and its
/// language server only when the index has nothing to say; an index older
/// than the file still answers, and says so once.
pub const Index = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .index, "");
    }
};

/// Show the callers of the function under the cursor as a tree, outermost
/// first, in a +Callstack.
///
/// Each caller with its place to open and its signature, the line of each
/// call under it; callers named for tests after the rest, a recursion marked
/// `↻`. CallstackDepth sets how many levels (8 by default); a deeper tree
/// says where to go on from. `g c` does the same.
pub const Callstack = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .callstack, "");
    }
};

/// List the functions that call the one under the cursor, one level up; a
/// single one is a jump.
pub const Callers = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .incoming_calls, "");
    }
};

/// List the functions the one under the cursor calls, one level down; a
/// single one is a jump.
pub const Callees = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .outgoing_calls, "");
    }
};

/// List the supertypes of the type under the cursor in a +Search; a single
/// one is a jump.
pub const Supertypes = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .supertypes, "");
    }
};

/// List the subtypes of the type under the cursor in a +Search; a single one
/// is a jump.
pub const Subtypes = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .subtypes, "");
    }
};

/// Rename the symbol under the cursor to its argument, wherever the language
/// server finds it.
///
/// Bare, it asks for the new name. Within this file it is done at once,
/// saying how many places changed; one that reaches other files changes
/// nothing and lists its edits in a +Search to look over.
pub const Rename = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (a.len > 0) return c.p.lspRequest(c.id, .rename, a);
        // From the keyboard, where the walk is on: typed in the pane's own
        // tag, its edits drawn in its body as they are typed (SPEC §3.5).
        if (pardes.Pick.asked(c.p) and c.pane.file != null) return @import("lsp/Ask.zig").openRename(c.p, c.id);
        panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.rename_marker });
    }
};

/// Search the workspace's symbols for its argument, in a +Search; bare, it
/// asks for the name.
pub const WsSymbols = struct {
    pub const takes_arg = true;
    pub const requires_arg = true;
    pub fn run(c: Ctx) void {
        const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
        if (a.len > 0) return c.p.lspRequest(c.id, .workspace_symbols, a);
        panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.symbol_marker });
    }
};

/// Show which index and language server serve this file, and their state, in
/// a +Lsp.
///
/// The index.scip it asks (or the Index that would write one), its server and
/// the server's state (not started yet, failed and waiting to retry), and
/// what answered each query lately.
pub const Lspinfo = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .status, "");
    }
};

/// Explain, step by step in a +Lsp, how the last language server request was
/// answered.
pub const Lspwhy = struct {
    pub fn run(c: Ctx) void {
        c.p.lspRequest(c.id, .explain, "");
    }
};

/// What +Unsaved holds: the list a refusal over unsaved panes keeps.
fn unsavedList(p: *Pardes) []const u8 {
    for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| if (o.from == .unsaved) return f.content;
    return "";
}

/// A dump file that exists, for a Restore to get past reading it.
fn testDump(buf: []u8) ![]const u8 {
    var tmp = std.testing.tmpDir(.{});
    // A real dump: a Restore reads it through before it asks anything.
    const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer source.deinit();
    try pardes.dump.dumpState(source);
    try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = source.dump_out.? });
    var dir: [4096]u8 = undefined;
    const at = dir[0..try tmp.dir.realPath(std.testing.io, &dir)];
    return std.fmt.bufPrint(buf, "Restore {s}/d.zon", .{at});
}

test "a builtin's documentation is the whole `///` block above it, a line a paragraph, its summary first" {
    const Builtin = registry.Builtin();
    const diff = registry.doc(Builtin.Diff);
    try std.testing.expect(std.mem.startsWith(u8, diff.text, diff.summary));
    try std.testing.expect(std.mem.endsWith(u8, diff.summary, "."));
    // Its paragraphs, each its `///` lines joined: the forms in the second.
    var paras = std.mem.splitScalar(u8, diff.text, '\n');
    _ = paras.next();
    try std.testing.expect(std.mem.indexOf(u8, paras.next().?, "`Diff <hash>` (7 to 40 hex digits)") != null);
    try std.testing.expect(paras.next() != null);
    // No note for the code's reader: those are `//` lines in the struct.
    try std.testing.expect(std.mem.indexOf(u8, diff.text, "registration") == null);
    // A setting's is its own doc.
    try std.testing.expectEqualStrings(config.Settings.find("Wrap").?.doc, registry.doc(Builtin.Wrap).text);
    // Every builtin has one, its summary a line (the compiler holds both).
    for (std.enums.values(Builtin)) |b| try std.testing.expect(registry.doc(b).summary.len > 0);
}

test "capabilities exactly gate setting builtins" {
    const Builtin = registry.Builtin();
    for (config.Settings.settings) |setting| {
        const registered = std.meta.stringToEnum(Builtin, setting.word) != null;
        try std.testing.expectEqual(setting.enabled(capabilities), registered);
    }
}

test "a builtin's scope is the pane unless it says session, and every setting is the session's" {
    const Builtin = registry.Builtin();
    try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Del));
    try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Save));
    try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Newcol));
    try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Kill));
    try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Verbose));
    for (comptime settingList()) |setting|
        try std.testing.expectEqual(Scope.session, registry.scope(std.meta.stringToEnum(Builtin, setting.word).?));
}

test "Exit asks once about unsaved text, and quits when asked again" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("saved\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified
    pane.file.?.saved_hash = 0; // edited: what it had is not what it has
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
    try std.testing.expect(!p.quit);
    try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n"));
    // Told once, and nothing edited since: the second Exit quits.
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
    try std.testing.expect(p.quit);
}

test "Exit over a ctl write or a click names every pane it asks about, a second only those edited since, and the next discards them all" {
    for ([_]bool{ false, true }) |clicked| {
        const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
        defer p.deinit();
        const first = try p.setTestFile("saved\n");
        first.file.?.saved_revision = first.file.?.revision -% 1;
        first.file.?.saved_hash = 0; // edited: what it had is not what it has
        p.newScratchBelow(p.view().active);
        const second = p.panes[p.view().active].?;
        panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('x'))));
        try std.testing.expect(second.file.?.revision != second.file.?.saved_revision);
        // A ctl write, or a click through exec (ctl.captured).
        if (clicked) p.fs.capturing = true else p.fs.no_prompt = true;
        defer p.fs.capturing = false;
        defer p.fs.no_prompt = false;
        try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
        try std.testing.expect(!p.quit);
        // Two: counted, never a list cut short; `unsaved` records name them.
        try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]);
        const log = p.fs.log.buf.items;
        var rec: [64]u8 = undefined;
        for ([_]*const Pane{ first, second }) |pane|
            try std.testing.expect(std.mem.indexOf(u8, log, try std.fmt.bufPrint(&rec, "unsaved {d} ", .{pane.serial})) != null);
        // The whole list stays in +Unsaved; the notice is short.
        try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) != null);
        try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), "\nExit again to discard\n"));
        var noticed = false;
        for (p.panes) |slot| if (slot) |pane| {
            noticed = noticed or std.mem.eql(u8, p.messages.saidBy(pane), "2 unsaved panes \u{2014} Exit again to discard");
        };
        try std.testing.expect(noticed);
        // Edited since: only that one is named again (acme's rule).
        p.fs.failure_len = 0;
        panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y'))));
        try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
        try std.testing.expect(!p.quit);
        const again = p.fs.failure[0..p.fs.failure_len];
        try std.testing.expect(std.mem.indexOf(u8, again, first.file.?.path) == null);
        // The one +Unsaved, filled again.
        var kept: usize = 0;
        for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| {
            kept += @intFromBool(o.from == .unsaved);
        };
        try std.testing.expectEqual(@as(usize, 1), kept);
        try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) == null);
        try std.testing.expect(std.mem.startsWith(u8, again, second.file.?.path));
        p.fs.failure_len = 0;
        try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
        try std.testing.expect(p.quit);
    }
}

test "Restore asks about unsaved text as Exit does, and restores when asked again" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("saved\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified
    pane.file.?.saved_hash = 0; // edited: what it had is not what it has
    var line_buf: [4200]u8 = undefined;
    const line = try testDump(&line_buf);
    try std.testing.expect(p.executeBuiltinLine(p.view().active, line));
    try std.testing.expect(p.restore_req == null);
    try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nRestore again to discard\n"));
    try std.testing.expect(p.executeBuiltinLine(p.view().active, line));
    try std.testing.expectEqualStrings(line["Restore ".len..], p.restore_req.?);
}

test "a Restore of a dump that cannot be read says so, before the unsaved-text warning" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("saved\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified
    pane.file.?.saved_hash = 0; // edited: what it had is not what it has
    p.fs.no_prompt = true;
    defer p.fs.no_prompt = false;
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Restore /nope/missing.zon"));
    try std.testing.expect(p.restore_req == null);
    try std.testing.expectEqualStrings("Restore: /nope/missing.zon: no such file", p.fs.failure[0..p.fs.failure_len]);
    // No warning spent: the Exit after it still asks.
    try std.testing.expect(pane.discard_warned == null);
}

test "a Restore's warning is not an Exit's: each word is warned on its own" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("saved\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified
    pane.file.?.saved_hash = 0; // edited: what it had is not what it has
    var line_buf: [4200]u8 = undefined;
    try std.testing.expect(p.executeBuiltinLine(p.view().active, try testDump(&line_buf)));
    try std.testing.expect(p.restore_req == null);
    // The Restore warned; an Exit after it has not been, and asks.
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
    try std.testing.expect(!p.quit);
    try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n"));
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
    try std.testing.expect(p.quit);
}

test "Kill stops the commands pardes typed, bare all and by name those that match, and never quits" {
    if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    while (p.nextEffect()) |_| {}
    const term = p.view().active;
    try std.testing.expect(p.panes[term].?.isTerminal());
    const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
    p.update(.{ .output = .{ .pane = .at(term), .bytes = prompt } });
    while (p.nextEffect()) |_| {}
    // The host the core asks: how many it was asked to stop, and whether
    // their shells run jobs in groups of their own.
    const killed = struct {
        var asked: usize = 0;
        var job_control = true;
        const vtable: pardes.Host.VTable = .{ .kill_job = answer };
        fn answer(_: ?*anyopaque, _: pardes.Pane.Id) bool {
            asked += 1;
            return job_control;
        }
        fn count(pp: *Pardes, line: []const u8) usize {
            asked = 0;
            _ = pp.executeBuiltinLine(pp.view().active, line);
            return asked;
        }
    };
    p.host = .{ .vtable = &killed.vtable };
    // Nothing running: nothing to stop, and never the shell; said.
    try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill"));
    try std.testing.expectEqualStrings("Kill: nothing running", p.messages.saidBy(p.panes[term].?));
    _ = exec.execute(p, term, "make -j8");
    while (p.nextEffect()) |_| {}
    // Typed but not started yet (no C mark): not running.
    try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill"));
    p.update(.{ .output = .{ .pane = .at(term), .bytes = "\x1b]133;C;aid=pardes\x07" } });
    while (p.nextEffect()) |_| {}
    try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill ls"));
    try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill ls make"));
    try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill"));
    try std.testing.expect(!p.quit);
    // With job control off there is no job apart from the shell: said, and
    // over ctl the write fails with it.
    killed.job_control = false;
    p.fs.no_prompt = true;
    try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill"));
    try std.testing.expectStringStartsWith(p.fs.failure[0..p.fs.failure_len], "Kill: no job to signal");
    p.fs.no_prompt = false;
    p.fs.failure_len = 0;
    killed.job_control = true;
    // Ended (a D mark): nothing to stop again.
    p.update(.{ .output = .{ .pane = .at(term), .bytes = "\x1b]133;D;143;aid=pardes\x07" ++ prompt } });
    while (p.nextEffect()) |_| {}
    try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill"));
}

test "Look does not announce itself on the message row; Del still does" {
    const Builtin = registry.Builtin();
    try std.testing.expect(!registry.announces(Builtin.Look));
    try std.testing.expect(registry.announces(Builtin.Del));
}

test "Exit and Restore name a modified +New scratch as well as files" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const file = try p.setTestFile("saved\n");
    file.file.?.saved_revision = file.file.?.revision -% 1; // modified
    file.file.?.saved_hash = 0; // edited: what it had is not what it has
    p.newScratchBelow(p.view().active);
    const scratch = &p.panes[p.view().active].?.file.?;
    scratch.content = try p.gpa.realloc(scratch.content, 120);
    @memset(scratch.content, 'n'); // past acme's 100 bytes, where it whines
    scratch.revision +%= 1; // typed into, never saved
    scratch.saved_hash = 0; // edited: what it had is not what it has
    p.fs.no_prompt = true;
    defer p.fs.no_prompt = false;
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit"));
    try std.testing.expect(!p.quit);
    // Each pane's message row names it; the write's refusal counts them.
    try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]);
    try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "test.txt: Modified") != null);
    const scratch_pane = p.panes[p.view().active].?;
    var named: [64]u8 = undefined;
    try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), try std.fmt.bufPrint(&named, "{s} (pane {d})", .{ config.scratch_buffer, scratch_pane.serial })) != null);
    // Delcol, Restore and Exit name it the same way.
    p.fs.failure_len = 0;
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Delcol"));
    try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "Delcol again to discard") == null);
    try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), named[0 .. config.scratch_buffer.len + 7]) != null);
}

test "Del and Delcol refuse a pane with unsaved text once, as acme's do, and close on the second" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("saved\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified
    pane.file.?.saved_hash = 0; // edited: what it had is not what it has
    const serial = pane.serial;
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Delcol"));
    try std.testing.expect(p.paneBySerial(serial) != null);
    // A refused Delcol changes nothing: no +Unsaved (its records say it).
    try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "Delcol") == null);
    // Each word is warned on its own: Del asks too, then closes.
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Del"));
    try std.testing.expect(p.paneBySerial(serial) != null);
    try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nDel again to discard\n"));
    try std.testing.expect(p.executeBuiltinLine(p.view().active, "Del"));
    try std.testing.expect(p.paneBySerial(serial) == null);
}

test "a pane renamed but never edited has no text to lose: Del closes it at once" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    p.newScratchBelow(p.view().active);
    const pane = try p.setTestFile("loaded\n");
    pane.file.?.saved_revision = pane.file.?.revision -% 1; // dirty by the rename alone
    const serial = pane.serial;
    try std.testing.expect(p.executeBuiltinLine(0, "Del"));
    try std.testing.expect(p.paneBySerial(serial) == null);
}