summaryrefslogtreecommitdiff
path: root/core/Pick.zig
blob: c05ed084e805f042a3fab7c7b8b60ff59451a772 (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
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
//! A picker (pick-ui SPEC.md §5, direction E): a list of places, panes or
//! names unrolled in the tag of the pane its Enter lands in (§3.5): the
//! asking pane when it reads, else its reader, made for the picker when it
//! has none and taken away again by Esc. Its query is typed in that tag's
//! field (TagState.field), its rows hang in the band under it (Band.zig)
//! eleven at a time around the cursor, and that pane's body is the preview:
//! the current row's file at its line, its own text set aside meanwhile and
//! put back when the picker rolls up.
//!
//! The rows are Query.zig's producers', re-presented: names scored by
//! Names.zig a frame's count at a time (Find's listing from the disk
//! engine's worker, Recent, Panes, the asking text's declarations, the
//! rows a language server answered, the jump list), Grep's lines from the
//! disk engine's worker (Stream.zig: its pause, its cap). A frame makes
//! only the rows it shows, in its arena.
//!
//! A picker is the session's, named by a serial drawn from the panes'
//! counter (`id`), so the disk engine's `target` names it as it names a
//! pane; one is live in a view's tag (TagState.pick), and the last
//! `max_lists` are kept after they roll up.
const Pick = @This();

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

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

/// Each source's word in the tag and its key cells (`␣ f Find`); a
/// source whose Backspace leaves it (`back`) goes back to the SPC level of
/// those keys: a group's.
const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 }).init(.{
    .find = .{ .word = "Find", .keys = "f" },
    .grep = .{ .word = "Grep", .keys = "f" },
    .recent = .{ .word = "Recent", .keys = "f" },
    .panes = .{ .word = "Panes", .keys = "b" },
    .symbols = .{ .word = "Symbols", .keys = "s" },
    .all = .{ .word = "All", .keys = "" },
    .jumplist = .{ .word = "Jumplist", .keys = "j" },
    .list = .{ .word = "List", .keys = "l" },
    .messages = .{ .word = "Messages", .keys = "h" },
    .themes = .{ .word = "Themes", .keys = "t" },
    .actions = .{ .word = "Actions", .keys = "la" },
    .lists = .{ .word = "Lists", .keys = "f" },
});

/// The pickers kept after they roll up, for their list words, Resume and
/// Lists (Lists itself never one of them: Pardes.picks has one more).
pub const max_lists = 8;
/// Refinements a picker stacks (C-SPC).
pub const max_refine = 3;

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

/// Its serial: the disk engine's target, a list word's index.
id: u32,
source: Source,
/// Its word, `Find`, or a list's own (`Refs`).
word: Kind.Buf(24) = .{},
/// The leader keys under which its builtin is, drawn as key cells.
keys: Kind.Buf(4) = .{},
/// Where Find and Grep look; what the rows' paths are relative to.
dir: Kind.Buf(4096) = .{},
/// The pane that asked, and the one its Enter lands in, by serial.
owner: u32 = 0,
landing: u32 = 0,
/// The landing pane was made for it: Esc takes it away.
made: bool = false,
/// Its band's rows at most: 40 % of its host pane's rows at open (UX D6),
/// fixed: the layout that borrows the host's body from its column reads
/// it, and a pane laid out again changes it no more than typing does.
cap: u16 = 0,
/// Unrolled in a view's tag now.
unrolled: bool = false,
names: Names = .{},
/// A Grep's lines, as the disk engine sends them (Query.take).
found: std.ArrayList(Query.Found) = .empty,
found_bytes: std.ArrayList(u8) = .empty,
/// A list's rows, as they were handed over (`path:line:col text`); code
/// actions' each followed by its edit's records (lsp_client actionEdits).
rows: []u8 = &.{},
/// The revision of the asking text its actions' edits are of.
revision: u32 = 0,
/// The query and the cursor as it rolled up (live, they are its view's
/// field and cursor).
query: Kind.Buf(256) = .{},
at: u32 = 0,
/// The landing pane's own text while its body previews (a reading pane:
/// put back when the picker rolls up), and its caret and top then (put
/// back too when it previewed its own file, with nothing set aside).
aside: ?File.State = null,
aside_row: i32 = 0,
aside_col: i32 = 0,
aside_top: usize = 0,
/// What the row the preview shows is (`idOf`; `no_row`: none yet): asked
/// again on the frame after the cursor moves to another, never on the key
/// that moved it, and on the frame a row first comes under it.
shown: u32 = no_row,
/// A place shown in its landing pane's body since it unrolled: the band
/// takes its rows from that body (`previewing`).
previewed: bool = false,
/// The preview on (M-p).
previews: bool = true,
/// Marked rows (Tab), by what each is (`idOf`), in order.
marks: std.ArrayList(u32) = .empty,
/// The queries refined from (C-SPC), each with the names it listed then:
/// Backspace on an empty field goes back to them.
refined: [max_refine]Refined = undefined,
nrefined: u8 = 0,
/// The band's second step: the sources to switch to (M-h), the acts on
/// the picked rows (M-l, M-Enter), its source's earlier queries (C-r);
/// `edit`: the field is the act Edit's command, the query kept in `query`.
spine: enum(u8) { rows, sources, acts, edit, history } = .rows,
/// The line of its source's history the cursor of it unrolled is on
/// (Prompt.historyAt: 0 the newest holding the field).
recall: u8 = 0,
/// The act step's cursor, among the acts offered.
act_at: u8 = 0,
/// The places Walk queued (C-i steps them in the landing pane): each a
/// path in `queue_bytes`, its line and column.
queue: std.ArrayList(Queued) = .empty,
queue_bytes: std.ArrayList(u8) = .empty,
queue_at: u32 = 0,
/// Where it last landed, `@p2 › words.zig:16` (Lists' meta, UX L'3).
landed: Kind.Buf(80) = .{},
/// Where it stands among the kept pickers, the newest the highest
/// (`touch`): Resume's order (`nth`), and the oldest goes for a new one.
used: u32 = 0,
/// The step of its landing pane's trail a walk reopened it at (Ctrl-o,
/// UX L'1): its Ctrl-o and Ctrl-i walk on from that word, and its Enter
/// lands as that word's, the steps after it dropped.
walking: ?u8 = null,

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

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

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

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

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

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

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

/// Whether pane `id`'s body is the live picker's preview: a place shown in
/// it. Its band then takes its rows from the body, which starts under the
/// band (Pardes.sync), as a file's first lines could not be put under it
/// otherwise (UX DESIGN I1's "a picker's landing line at a third below
/// the band" for Find's line 1: W1's reading); before that, and at rest
/// again, the pane's own text stays where it was under the band.
pub fn previewing(p: *const Pardes, id: usize) bool {
    const pk = live(p) orelse return false;
    const pane = p.panes[id] orelse return false;
    return pk.previewed and pane.serial == pk.landing;
}

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

/// The work tree `dir` is in: the nearest directory at or above it that
/// holds a `.jj` or a `.git` (a git worktree's is a file); `dir` itself
/// when none does. Find and Grep search from it, their rows' paths
/// relative to it, wherever in the tree the asking pane is.
fn workTree(p: *Pardes, dir: []const u8) []const u8 {
    var d = dir;
    while (true) {
        var buf: [4096]u8 = undefined;
        for ([_][]const u8{ ".jj", ".git" }) |name| {
            const marker = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, d, "/"), name }) catch return dir;
            if (exec.kindOf(p.tape, marker) != null) return d;
        }
        d = std.Io.Dir.path.dirname(d) orelse return dir;
    }
}

/// Where a Grep's query `q` searches and for what (SPEC §5.1): a leading
/// directory, the root's or absolute, then a blank, narrows it to that
/// directory (`src/torque Macro`), the rest the pattern; else all of it
/// from the root. The directory joined in `buf`.
fn grepScope(p: *Pardes, pk: *const Pick, q: []const u8, buf: *[4096]u8) struct { dir: []const u8, pat: []const u8 } {
    const root = pk.dir.slice();
    const sp = std.mem.indexOfScalar(u8, q, ' ') orelse return .{ .dir = root, .pat = q };
    const lead = q[0..sp];
    const dir = if (lead[0] == '/') lead else std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.trimEnd(u8, root, "/"), lead }) catch return .{ .dir = root, .pat = q };
    if (exec.kindOf(p.tape, dir) != .directory) return .{ .dir = root, .pat = q };
    return .{ .dir = dir, .pat = std.mem.trimStart(u8, q[sp + 1 ..], " ") };
}

/// A new picker in the ring, the oldest kept one dropped for it.
fn make(p: *Pardes, source: Source) !*Pick {
    var slot: ?usize = null;
    // Lists is never kept (UX L'3): the one it had goes, and it drops none
    // of the kept for its room.
    for (p.picks, 0..) |s, i| if (s) |pk| if (source == .lists and pk.source == .lists) {
        pk.deinit(p.gpa);
        p.gpa.destroy(pk);
        p.picks[i] = null;
        slot = i;
        break;
    };
    if (slot == null and (source == .lists or nkept(p) < max_lists)) for (p.picks, 0..) |s, i| if (s == null) {
        slot = i;
        break;
    };
    if (slot == null) {
        // The oldest not live.
        var oldest: ?usize = null;
        for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and pk.source != .lists and (oldest == null or rank(pk) < rank(p.picks[oldest.?].?))) {
            oldest = i;
        };
        const i = oldest orelse return error.NoPickerSlots;
        p.picks[i].?.deinit(p.gpa);
        p.gpa.destroy(p.picks[i].?);
        p.picks[i] = null;
        slot = i;
    }
    const pk = try p.gpa.create(Pick);
    p.next_serial += 1;
    pk.* = .{ .id = p.next_serial, .source = source };
    p.picks[slot.?] = pk;
    touch(p, pk);
    return pk;
}

/// Picker `pk` the newest kept (UX L': made, landed, reopened by a walk).
fn touch(p: *Pardes, pk: *Pick) void {
    var top: u32 = 0;
    for (p.picks) |slot| if (slot) |o| {
        top = @max(top, o.used);
    };
    pk.used = top +| 1;
}

/// Where picker `pk` stands among the kept ones, newer higher: its `used`,
/// then its serial (pickers a dump made before `used` was kept).
fn rank(pk: *const Pick) u64 {
    return @as(u64, pk.used) << 32 | pk.id;
}

/// The `k`th newest kept picker, the newest 1.
fn nth(p: *const Pardes, k: usize) ?*Pick {
    var below: u64 = std.math.maxInt(u64);
    var found: ?*Pick = null;
    for (0..k) |_| {
        found = null;
        for (p.picks) |slot| if (slot) |pk| if (pk.source != .lists and rank(pk) < below and (found == null or rank(pk) > rank(found.?))) {
            found = pk;
        };
        below = rank(found orelse return null);
    }
    return found;
}

/// The pickers kept: not Lists.
fn nkept(p: *const Pardes) usize {
    var n: usize = 0;
    for (p.picks) |slot| if (slot) |pk| {
        n += @intFromBool(pk.source != .lists);
    };
    return n;
}

/// Picker `pk` asked from pane `from`: the pane it lands in is `from` when
/// it reads; its reader when it is held and has one; else an untouched
/// pane, `from` itself first (UX J1), which previews as a reading pane does
/// and is given back as it was on Esc; else a pane made where its reader
/// would go, empty until the preview fills it. The keyboard stays where it
/// was: the landing pane is the tag's host.
fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void {
    const asker = p.panes[from].?;
    pk.owner = asker.serial;
    pk.made = false;
    // A theme is no place: its list is the asking pane's own tag (§3.5),
    // and its preview the whole window; an action's is that text's edit.
    if (pk.source == .themes or pk.source == .actions) {
        pk.landing = asker.serial;
        p.view().active = from;
        return;
    }
    var reader = if (Trail.reading(p, asker)) from else Trail.readerOf(p, asker);
    if (reader == null) if (layout.freeSpace(p, from, .reader)) |free| if (free == .pane) {
        reader = free.pane;
    };
    pk.landing = p.panes[reader orelse try landingFor(p, from)].?.serial;
    pk.made = reader == null;
    p.view().active = from;
}

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

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

/// Its source begun: the names gathered, a listing started.
fn start(p: *Pardes, pk: *Pick) void {
    pk.names.reset();
    pk.found.clearRetainingCapacity();
    pk.found_bytes.clearRetainingCapacity();
    const dir = pk.dir.slice();
    switch (pk.source) {
        .find => {
            Stream.query(p, pk.id, .files, "", dir, .now) catch |err| return p.reportError(.at(p.view().active), "pick", err);
            if (p.fs.serving) Stream.step(p);
        },
        .grep, .all => {},
        .recent => Query.gather(p, &pk.names, .recent, dir, null, null),
        .panes => Query.gather(p, &pk.names, .panes, dir, null, null),
        .symbols => Query.gather(p, &pk.names, .symbols, dir, null, p.paneBySerial(pk.owner)),
        .jumplist => {
            var out: std.Io.Writer.Allocating = .init(p.gpa);
            defer out.deinit();
            Output.jumpsText(p, &out.writer) catch return;
            addRows(p, pk, out.written());
        },
        .list => addRows(p, pk, pk.rows),
        // The kept pickers, newest first, each by its list word.
        .lists => for (1..max_lists + 1) |k| {
            const kp = nth(p, k) orelse break;
            var word: Kind.Buf(Trail.max_text) = .{};
            const text = wordOf(p, kp, &word);
            pk.names.add(p.gpa, text, 0, text.len, 0, kp.id) catch return;
        },
        .messages => {
            var out: std.Io.Writer.Allocating = .init(p.gpa);
            defer out.deinit();
            Output.messagesText(p, &out.writer) catch return;
            addRows(p, pk, out.written());
        },
        .themes => for (pardes.colors.themes, 0..) |t, i| {
            pk.names.add(p.gpa, t.name, 0, t.name.len, 0, @intCast(i)) catch return;
        },
        // Each action by its title, its digit before it (the first nine,
        // which `1`-`9` apply), the title what the query matches.
        .actions => {
            var lines = std.mem.splitScalar(u8, pk.rows, '\n');
            var i: u32 = 0;
            while (lines.next()) |ln| {
                if (ln.len == 0 or ln[0] == '@') continue;
                const title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " ");
                var buf: [2 + 512]u8 = undefined;
                const cut = title[0..@min(title.len, 512)];
                const text = if (i < 9) std.fmt.bufPrint(&buf, "{d} {s}", .{ i + 1, cut }) catch unreachable else cut; // 2 + 512 fit
                pk.names.add(p.gpa, text, text.len - cut.len, cut.len, 0, i) catch return;
                i += 1;
            }
        },
    }
}

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

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

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

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

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

/// The disk engine's rows for picker `target` (Stream.receive).
pub fn take(p: *Pardes, target: u32, kind: Stream.Kind, rows: []const u8) bool {
    const pk = byId(p, target) orelse return false;
    // A Grep narrowed to a directory (grepScope): its rows' paths from the
    // root, as an unnarrowed one's are.
    var buf: [4096]u8 = undefined;
    const searched = p.stream.dir.items;
    const under = if (kind == .grep and !std.mem.eql(u8, searched, pk.dir.slice())) std.fmt.bufPrint(&buf, "{s}/", .{relative(searched, pk.dir.slice())}) catch "" else "";
    Query.take(p, pk, kind, rows, under);
    // A listing's names, scored as they come.
    if (kind == .files) pk.names.rescore(p.gpa);
    return true;
}

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

/// The live picker's cursor on its best match, wherever its group puts it
/// (UX DESIGN N3: a Symbols list stays grouped while typed), its rows
/// sorted as far as the band shows past it.
fn toBest(p: *Pardes, pk: *Pick) void {
    const at = pk.names.bestRow();
    pk.names.reachTo(at + Band.Cursor.shown);
    p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16)));
}

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

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

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

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

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

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

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

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

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

fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) std.mem.Allocator.Error!Row {
    const dir = pk.dir.slice();
    if (!fuzzy(pk) and pk.source == .all) {
        var order: [pardes.MAX_PANES]usize = undefined;
        var k = i;
        for (allPanes(p, pk, &order)) |id| {
            const tp = p.panes[id].?;
            const hits = tp.places.hits.items;
            if (k >= hits.len) {
                k -= hits.len;
                continue;
            }
            const f = &tp.file.?;
            const h = hits[k];
            const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), h.start);
            const ls = File.lineStart(p.gpa, f, line);
            const le = std.mem.indexOfScalarPos(u8, f.content, h.start, '\n') orelse f.content.len;
            const whole = f.content[ls..le];
            const lead = whole.len - std.mem.trimStart(u8, whole, " \t").len;
            const name = if (f.output == null) std.Io.Dir.path.basename(f.path) else "";
            const pre = try std.fmt.allocPrint(arena, config.pane_addr ++ "{d} {s}:{d}", .{ tp.serial, name, line + 1 });
            const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, whole[lead..@min(whole.len, lead + 240)] });
            var marks: std.ArrayList(u16) = .empty;
            var c = h.start - ls;
            while (c < h.end - ls and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead));
            const target: Target = if (f.output == null) .{ .place = .{ .path = f.path, .at = .{ .line = line + 1, .col = h.start - ls + 1 } } } else .{ .pane = tp.serial };
            return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = target };
        }
        return .{ .text = "" };
    }
    if (!fuzzy(pk)) {
        const fd = pk.found.items[i];
        const name = pk.found_bytes.items[fd.path..][0..fd.path_len];
        const code = pk.found_bytes.items[fd.code..][0..fd.code_len];
        const lead = code.len - std.mem.trimStart(u8, code, " \t").len;
        const pre = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(name), fd.line });
        const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, code[lead..] });
        var marks: std.ArrayList(u16) = .empty;
        var c = fd.col;
        while (c < fd.end and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead));
        // (Under an absolute leading directory, grepScope's, an absolute path.)
        const path = if (name.len > 0 and name[0] == '/') name else try std.Io.Dir.path.join(arena, &.{ dir, name });
        return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = .{ .place = .{ .path = path, .at = .{ .line = fd.line, .col = fd.col + 1 } } } };
    }
    var marks: [Names.max_query * 4]u16 = undefined;
    var nmarks: usize = 0;
    const text = pk.names.row(i, &marks, &nmarks);
    const cand = pk.names.cands.items[pk.names.hits.items[i].cand];
    var row: Row = .{ .text = text, .marks = try arena.dupe(u16, marks[0..nmarks]) };
    switch (pk.source) {
        .find => {
            var namebuf: [4096]u8 = undefined;
            const name = if (text.len > 1 and text[0] == '"' and text[text.len - 1] == '"') look.unquoted(&namebuf, text[1 .. text.len - 1]) else text;
            row.faint = @intCast(if (std.mem.lastIndexOfScalar(u8, text, '/')) |k| k + 1 else 0);
            // A text at its first line; a kind's file whole, as a Look of
            // its name opens it (a place in it is its kind's address).
            const at: look.Spot = if (p.kinds.forPath(name) != null) .{} else .{ .line = 1, .col = 1 };
            row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = at } };
        },
        .panes => {
            row.pre = cand.key -| 1;
            row.dim = p.paneBySerial(cand.ref) == null;
            row.target = .{ .pane = cand.ref };
        },
        // `    12  m Counts.lines  : usize = 0` (Query.gather): the line its
        // meta, the mark in the keyword's ink, the qualifier and what
        // follows the name dim (UX DESIGN N4).
        .symbols => {
            const line = 8;
            if (text.len <= line or cand.key < line) return row;
            row.text = text[line..];
            row.meta = std.mem.trimStart(u8, text[0..6], " ");
            const marks_in = try arena.alloc(u16, row.marks.len);
            for (marks_in, row.marks) |*m, at| m.* = at -| line;
            row.marks = marks_in;
            const name_at = cand.key - line;
            row.kind = @intCast(name_at - 1);
            row.pre = @intCast(name_at);
            row.faint = cand.base;
            if (name_at + cand.key_len < row.text.len) row.quiet = .{ @intCast(name_at + cand.key_len), @intCast(row.text.len) };
            const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row;
            const f = owner.file orelse return row;
            row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } };
        },
        // A kept picker: where it last landed, its current row's place the
        // preview (UX L'3).
        .lists => {
            const kp = byId(p, cand.ref) orelse return row;
            row.meta = kp.landed.slice();
            const n = count(p, kp);
            if (n > 0) row.target = (try rowAt(p, kp, arena, @min(kp.at, n - 1))).target;
        },
        // The theme in use says so, whichever the window wears (POLISH 12).
        .themes => if (p.custom_theme == null and cand.ref == p.settings.theme) {
            row.meta = "in use";
        },
        // An action: its digit a key; its place the first line its edit
        // changes, which the body is moved to while it is previewed.
        .actions => {
            row.key = @intFromBool(cand.ref < 9);
            const act = action(pk, cand.ref) orelse return row;
            // One Enter cannot apply (apply's refusals): dim, saying why
            // (UX E5 12).
            if (act.records.len == 0 or std.mem.eql(u8, act.records, "@elsewhere\n")) {
                row.dim = true;
                row.meta = if (act.records.len == 0) "command" else "other files";
                return row;
            }
            const owner = p.panes[p.paneBySerial(pk.landing) orelse return row].?;
            // With the `Changes` layer's lines shown the body stays where it is.
            const f = if (owner.file) |*file| file else return row;
            if (f.layer.lines.len > 0 or f.revision != pk.revision) return row;
            const edits = pardes.lsp.Ask.parseLspEdits(arena, act.records, null) orelse return row;
            if (edits[0].start > f.content.len) return row;
            const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), edits[0].start);
            row.target = .{ .place = .{ .path = f.path, .at = .{ .line = line + 1 } } };
        },
        .recent, .jumplist, .list, .grep, .all => {
            const t = look.parsePathLine(text);
            row.pre = @intCast(t.end);
            if (t.path.len == 0) return row;
            const path = if (t.path[0] == '/' or t.path[0] == '@') t.path else try std.Io.Dir.path.join(arena, &.{ dir, t.path });
            row.target = .{ .place = .{ .path = path, .at = t.at } };
        },
        // A message (`✗ 3: words`, Output.messagesText): its cause's pane
        // while it is open; a place under it (indented): that place.
        .messages => {
            const lead = text.len - std.mem.trimStart(u8, text, " ").len;
            if (lead == 0) {
                const sp = std.mem.indexOfScalar(u8, text, ' ') orelse return row;
                const digits = text[sp + 1 ..];
                const n = std.mem.indexOfNone(u8, digits, "0123456789") orelse return row;
                if (n == 0 or digits[n] != ':') return row;
                const serial = std.fmt.parseInt(u32, digits[0..n], 10) catch return row;
                if (p.paneBySerial(serial) != null) row.target = .{ .pane = serial };
                return row;
            }
            const t = look.parsePathLine(text[lead..]);
            row.pre = @intCast(lead + t.end);
            if (t.path.len == 0) return row;
            row.target = .{ .place = .{ .path = t.path, .at = t.at } };
        },
    }
    return row;
}

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

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

/// The band's rows (UX D6): as many as the list will show, from what the
/// source has (not what the query keeps: typing never moves the body),
/// four at least, eleven at most, and its `cap` at most (the host pane's
/// 40 % at open: the layout asks this while it lays the column out, when
/// no pane has its rows yet).
pub fn bandRows(p: *const Pardes) u16 {
    const pk = live(p) orelse return 0;
    const have = if (!fuzzy(pk)) Band.Cursor.shown else pk.names.cands.items.len;
    const rows: usize = @max(1, @min(Band.Cursor.shown, @max(4, have), pk.cap));
    // Its second step's rows too: the sources, the acts and what they act on.
    return @intCast(switch (pk.spine) {
        .sources => @max(rows, spine_rows.len),
        .acts => acts: {
            var n: usize = 1;
            for (acts) |act| n += @intFromBool(offered(pk, act));
            break :acts @max(rows, n);
        },
        .history => @max(rows, pardes.Prompt.historyRows(p.prompt_history.pick.getPtrConst(pk.source), p.view().tag_state.field.text())),
        .rows, .edit => rows,
    });
}

/// The band's steps: the rows around the cursor.
pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step {
    const pk = live(p) orelse return &.{};
    const s = &p.view().tag_state;
    const n = count(p, pk);
    const out = try arena.alloc(Band.Step, if (pk.spine == .sources or pk.spine == .acts or pk.spine == .history or pk.source == .lists) 2 else 1);
    if (pk.spine == .history) _ = try pardes.Prompt.historyStep(arena, p.prompt_history.pick.getPtrConst(pk.source), s.field.text(), pk.recall, &out[1]);
    if (pk.spine == .acts) out[1] = try actStep(p, pk, arena);
    if (pk.source == .lists) out[1] = try listedStep(p, pk, arena);
    if (pk.spine == .sources) {
        const rows = try arena.alloc(Band.Row, spine_rows.len);
        for (spine_rows, rows, 0..) |src, *row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{c} {s}", .{ src.key, src.word }), .key = 1, .index = @intCast(i), .dim = src.source == pk.source };
        out[1] = .{ .rows = rows };
    }
    if (n == 0) {
        const none = try arena.alloc(Band.Row, 1);
        none[0] = .{ .text = if (pk.names.busy() or p.stream.busyFor(pk.id)) "⋯" else if (s.field.len == 0 and pk.source == .grep) "type to search" else "nothing matches", .dim = true };
        out[0] = .{ .rows = none };
        return out;
    }
    const w = s.rows.window(@intCast(@min(n, std.math.maxInt(u16))));
    const rows = try arena.alloc(Band.Row, w.hi - w.lo);
    for (rows, w.lo..) |*row, i| {
        const r = try rowAt(p, pk, arena, i);
        row.* = .{ .text = r.text, .key = r.key, .kind = r.kind, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .quiet = r.quiet, .marks = r.marks, .index = @intCast(i), .meta = r.meta };
    }
    // A place's text (a Grep's line, a list's): its `path:line` in the dim
    // ink and the text after it in one column, the widest place shown
    // before it (UX E7 2b: the old +Search's column). Bounded by the rows
    // shown.
    if (pk.source == .grep or pk.source == .all or pk.source == .list) {
        var widest: usize = 0;
        for (rows) |row| if (row.pre > 0 and row.pre < row.text.len) {
            widest = @max(widest, File.displayWidth(p.settings.tab, row.text[0 .. std.mem.indexOfScalarPos(u8, row.text, row.pre, ' ') orelse row.text.len]));
        };
        for (rows) |*row| if (row.pre > 0 and row.pre < row.text.len) {
            // The place up to its blank: a column (`:3:1`) and the `:` a
            // compiler's `path:line:col: words` puts after it are its.
            const end = std.mem.indexOfScalarPos(u8, row.text, row.pre, ' ') orelse row.text.len;
            row.quiet = .{ 0, @intCast(end) };
            const pad = widest - File.displayWidth(p.settings.tab, row.text[0..end]);
            if (pad == 0) continue;
            const blanks = try arena.alloc(u8, pad);
            @memset(blanks, ' ');
            row.text = try std.mem.concat(arena, u8, &.{ row.text[0..end], blanks, row.text[end..] });
            const marks = try arena.alloc(u16, row.marks.len);
            for (marks, row.marks) |*m, at| m.* = if (at >= end) at + @as(u16, @intCast(pad)) else at;
            row.marks = marks;
        };
    }
    out[0] = .{ .rows = rows };
    return out;
}

/// Lists' second step (UX L'3): the kept picker under its cursor, its
/// rows around its own cursor, which is marked `▶`; read, never a list.
fn listedStep(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator) !Band.Step {
    const kp = byId(p, @intCast(refAt(p, pk) orelse return .{ .doc = true })) orelse return .{ .doc = true };
    const n = count(p, kp);
    const lo = if (kp.at < Band.Cursor.shown) 0 else kp.at + 1 - Band.Cursor.shown;
    const hi = @min(n, lo + Band.Cursor.shown);
    const rows = try arena.alloc(Band.Row, hi -| lo);
    for (rows, lo..) |*row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{s}{s}", .{ if (i == kp.at) "▶ " else "  ", (try rowAt(p, kp, arena, i)).text }) };
    return .{ .rows = rows, .doc = true };
}

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

/// The line (from 0) pane `pane`'s body lands the live picker's cursor row
/// on, while it is that picker's landing pane previewing that row's file
/// (UX D7: drawn on the hit ground, body_layer.zig); null else.
pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *const Pane) ?usize {
    const pk = live(p) orelse return null;
    // A theme or an action lands nowhere: the window wearing it, its
    // edit on the Changes grounds are their previews.
    if (!pk.previews or pk.landing != pane.serial or pk.source == .themes or pk.source == .actions) return null;
    const s = &p.view().tag_state;
    if (s.rows.at >= count(p, pk) or pk.shown != idOf(pk, s.rows.at)) return null;
    const row = rowAt(p, pk, arena, s.rows.at) catch return null;
    const place = switch (row.target) {
        .place => |t| t,
        else => return null,
    };
    const f = pane.file orelse return null;
    if (!std.mem.eql(u8, f.path, place.path)) return null;
    return @intCast(@max(0, pane.body.cur_row));
}

/// The notice row's sentence while a picker previews (UX D7), written to
/// `w`: where Enter lands (`here`, or the owner's reader by its address,
/// a word to Look at), that the body is the preview, and Shift-Enter's new
/// pane; the address's bytes in what was written, or null with no picker
/// previewing.
pub fn sentence(p: *const Pardes, w: *std.Io.Writer) ?[2]usize {
    const pk = live(p) orelse return null;
    if (!pk.previews or pk.source == .themes or pk.source == .actions or pk.source == .lists) return null;
    if (pk.landing == pk.owner) {
        w.writeAll("⏎ lands here") catch return null;
    } else {
        w.writeAll("⏎ lands in ") catch return null;
    }
    const lo = w.end;
    if (pk.landing != pk.owner) w.print("@p{d}", .{pk.owner}) catch return null;
    const hi = w.end;
    if (pk.landing != pk.owner) w.writeAll("'s reader") catch return null;
    w.writeAll(" · its text is the preview · S-⏎ a new pane") catch return null;
    return .{ lo, hi };
}

/// The landing pane's body showing the current row's place (SPEC §5.3):
/// a file at its line, the query's matches lit for a Grep. Its own text is
/// set aside the first time, put back when the picker rolls up. A file an
/// open pane shows is taken from it; any other is read. A file a kind
/// takes (an addon's: a picture, a PDF), as a Look would open it
/// (look.resolve), shows through that kind (showKind); any other that is
/// not text (a NUL in its first 8000 bytes) as one line naming it,
/// `blob.bin · binary · 3.0 kB`, never its bytes.
fn preview(p: *Pardes, pk: *Pick) void {
    const s = &p.view().tag_state;
    // No row yet: none shown, so the first to come is (a Find's listing
    // and a Grep's lines come frames after the field asked).
    if (!pk.previews or s.rows.at >= count(p, pk)) return;
    if (pk.shown == idOf(pk, s.rows.at)) return;
    pk.shown = idOf(pk, s.rows.at);
    var frame = std.heap.ArenaAllocator.init(p.gpa);
    defer frame.deinit();
    const row = rowAt(p, pk, frame.allocator(), s.rows.at) catch return;
    const place = switch (row.target) {
        .place => |t| t,
        else => return,
    };
    const id = p.paneBySerial(pk.landing) orelse return;
    const pane = p.panes[id].?;
    const f = if (pane.file) |*file| file else return;
    if (f.twin != 0) return;
    const showing = if (pane.addon) |k| k.path else f.path;
    if (!std.mem.eql(u8, showing, place.path)) {
        if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return;
        const read = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return);
        if (pane.addon != null) Kind.close(p, pane);
        if (p.kinds.forPath(place.path)) |k| {
            defer p.gpa.free(read);
            return showKind(p, pk, id, k, place.path, read);
        }
        const bytes = if (std.mem.indexOfScalar(u8, read[0..@min(read.len, 8000)], 0) == null) read else named: {
            defer p.gpa.free(read);
            break :named nameLine(p.gpa, place.path, "binary", read.len, "") catch return;
        };
        showText(p, pk, id, place.path, bytes);
    }
    if (pane.addon != null) return;
    // The body under the band from the first place it shows (previewing):
    // laid out again before the place is put in its rows.
    if (!pk.previewed) {
        pk.previewed = true;
        p.layOut();
    }
    const keyboard = p.view().active;
    defer p.view().active = keyboard;
    look.clearNavigationSelection(p, pane);
    const pf = &pane.file.?;
    const at = place.at;
    if (at.line == 0 or at.line > File.nlines(p.gpa, pf)) {
        pf.scroll = 0;
        pf.scroll_row = 0;
        pane.body.cur_row = 0;
        pane.body.cur_col = 0;
        return;
    }
    look.focusPaneLine(p, id, at, .third);
    // A Grep's matches in the file lit, as its own pane would have them.
    if (pk.source == .grep) {
        var buf: [4096]u8 = undefined;
        pane.places.search(p, pane, .list, pk.id, grepScope(p, pk, std.mem.trim(u8, s.field.text(), " "), &buf).pat, true, null, false);
    }
}

/// Landing pane `id`'s text `bytes` (taken) as `path`: its own text set
/// aside the first time, a preview's text after that changed in place.
fn showText(p: *Pardes, pk: *Pick, id: usize, path_: []const u8, bytes: []u8) void {
    const pane = p.panes[id].?;
    const path = p.gpa.dupe(u8, path_) catch {
        p.gpa.free(bytes);
        return;
    };
    if (pk.aside == null and !pk.made) {
        const history = File.History.create(p.gpa) catch {
            p.gpa.free(bytes);
            p.gpa.free(path);
            return;
        };
        pk.aside = pane.file;
        pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history };
    } else {
        const pf = &pane.file.?;
        p.gpa.free(pf.path);
        pf.path = path;
        File.setContent(p, pf, bytes);
        pf.saved_revision = pf.revision;
        pf.scroll = 0;
        pf.scroll_row = 0;
        pf.syntax_dirty = true;
        pane.places.clear(p.gpa);
    }
    pane.hscroll = 0;
    pk.previewed = true;
    p.layOut();
}

/// Landing pane `id` showing the file at `path` through kind `k`, as a
/// Look would open it in a pane of its own: a slot of that kind over the
/// pane's text, which stays under it, unseen, until the next row or the
/// roll-up takes the slot away (Kind.close). Its kind does the work it
/// does for its own pane (an image decoded on a worker; a draw of a row
/// passed by dropped, Kind.Slot.drawn_from), and nothing more: what it
/// says, looks at or runs is not done while it previews (Kind.Call.end).
/// Until its picture is drawn, the line naming it (draw.zig); one its kind
/// refuses is that line as text, saying why.
fn showKind(p: *Pardes, pk: *Pick, id: usize, k: u8, path: []const u8, bytes: []const u8) void {
    const pane = p.panes[id].?;
    const slot = Kind.newSlot(p, k, path) catch |err| return p.reportError(.at(id), "pick", err);
    slot.size = bytes.len;
    pane.addon = slot;
    pk.previewed = true;
    if (!Kind.reopen(p, id, slot, bytes) and slot.refused.len > 0) {
        const line = nameLine(p.gpa, path, slot.nameOf(), bytes.len, slot.refused.slice()) catch return Kind.close(p, pane);
        Kind.close(p, pane);
        return showText(p, pk, id, path, line);
    }
    p.layOut();
}

/// The one line a file shows while a picker previews it and none of its
/// text is shown: its name, what it is (`binary`, a kind's name), its size
/// and why when it says why: `photo.png · image · 1.2 MB`.
pub fn nameLine(gpa: std.mem.Allocator, path: []const u8, what: []const u8, size: u64, why: []const u8) ![]u8 {
    var out: std.Io.Writer.Allocating = .init(gpa);
    errdefer out.deinit();
    const w = &out.writer;
    try w.print("{s} · {s} · ", .{ std.Io.Dir.path.basename(path), what });
    if (size < 1000) try w.print("{d} B", .{size}) else {
        const units = [_][]const u8{ "kB", "MB", "GB", "TB", "PB", "EB" };
        var unit: u64 = 1000;
        var u: usize = 0;
        while (size / unit >= 1000 and u + 1 < units.len) : (u += 1) unit *= 1000;
        const tenths = size / (unit / 10);
        try w.print("{d}.{d} {s}", .{ tenths / 10, tenths % 10, units[u] });
    }
    if (why.len > 0) try w.print(" · {s}", .{why});
    return out.toOwnedSlice();
}

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

/// The landing pane as the picker found it: its own text back, or the
/// pane made for the picker taken away; the places it lit put out.
fn restore(p: *Pardes, pk: *Pick) void {
    if (pk.source == .themes) return pardes.colors.previewTheme(p, null);
    const id = p.paneBySerial(pk.landing) orelse return;
    for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa);
    if (pk.made) {
        // A kind's file shown: its slot closed first, as a pane's text
        // closing is no file closed (no Recent row).
        if (p.panes[id].?.addon != null) Kind.close(p, p.panes[id].?);
        pk.made = false;
        p.removePane(id, p.paneBySerial(pk.owner)) catch |err| p.reportError(.at(id), "pick", err);
        return;
    }
    putBack(p, pk);
}

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

/// The live picker rolled up (Esc, or the tag put to rest by anything):
/// its query and cursor kept for its list word and Resume, every body as
/// it was (TagState.toRest).
pub fn rollUp(p: *Pardes) void {
    const pk = live(p) orelse return;
    const s = &p.view().tag_state;
    if (pk.spine != .edit) pk.query.set(s.field.text());
    // Its query its source's history's (UX L2's C-r): Lists keeps none.
    if (pk.source != .lists) p.prompt_history.pick.getPtr(pk.source).add(pk.query.slice());
    pk.spine = .rows;
    pk.recall = 0;
    pk.at = s.rows.at;
    pk.unrolled = false;
    pk.walking = null;
    if (p.stream.target == pk.id) _ = p.stream.stop();
    restore(p, pk);
}

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

// ---- code actions ----

/// Action `index` of a code actions picker's rows: its title and its edit's
/// records (the `@put` lines after its row, `@elsewhere` for an edit that
/// reaches other files, none for a command's); null past the last.
fn action(pk: *const Pick, index: usize) ?struct { title: []const u8, records: []const u8 } {
    var lines = std.mem.splitScalar(u8, pk.rows, '\n');
    var n: usize = 0;
    while (lines.next()) |ln| {
        if (ln.len == 0 or ln[0] == '@') continue;
        if (n < index) {
            n += 1;
            continue;
        }
        const from = lines.index orelse pk.rows.len;
        var to = from;
        while (lines.peek()) |next| {
            if (next.len == 0 or next[0] != '@') break;
            _ = lines.next();
            to = lines.index orelse pk.rows.len;
        }
        return .{ .title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " "), .records = pk.rows[from..to] };
    }
    return null;
}

/// Action `index` of the live actions picker applied to the text it was
/// asked of as one undo step, the tag put to rest first (its caret back
/// where it was, then moved with the edit); one with no edit here (a
/// command's, or one reaching other files) said and not applied.
fn apply(p: *Pardes, pk: *Pick, index: usize) void {
    const act = action(pk, index) orelse return;
    const id = p.paneBySerial(pk.landing) orelse return TagState.toRest(p);
    TagState.toRest(p);
    var said: Kind.Buf(256) = .{};
    if (std.mem.eql(u8, act.records, "@elsewhere\n")) return p.reportFailure(id, said.print("Actions: {s}: its edit reaches other files, not applied", .{act.title}));
    if (act.records.len == 0) return p.reportFailure(id, said.print("Actions: {s}: no edit to apply", .{act.title}));
    if (!pardes.lsp.Ask.applyAction(p, p.panes[id].?, pk.revision, act.records)) return p.reportFailure(id, said.print("Actions: {s}: not applied, the text is not what it was asked of", .{act.title}));
    p.setMessage(.at(id), said.print("Actions: {s}", .{act.title}));
}

/// The live code actions picker's preview in its body (SPEC §5.1, the
/// coordinator's R3): the edit of the action under the cursor, the lines it
/// changes on the deleted ground and what they become after them as ghost
/// rows on the added ground, the rows below pushed down and the last off
/// the view. Drawn, never written; the rows shown alone.
pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: pardes.Rect, body_h: u16) !void {
    const pk = live(p) orelse return;
    if (pk.source != .actions or !pk.previews or pk.landing != pane.serial) return;
    const f = if (pane.file) |*file| file else return;
    if (f.revision != pk.revision) return;
    const records = (action(pk, refAt(p, pk) orelse return) orelse return).records;
    const edits = pardes.lsp.Ask.parseLspEdits(arena, records, null) orelse return;
    const text = f.content;
    const index = try File.lineIndex(p.gpa, f);
    // The edits by the lines they touch: each run of them its old lines
    // [lo, hi) and their new text, which goes before line hi.
    const Group = struct { lo: usize, hi: usize, new: []const u8 };
    var groups: std.ArrayList(Group) = .empty;
    var k: usize = 0;
    while (k < edits.len) {
        const begin = File.bufferOffset(f, edits[k].start, false);
        if (begin > text.len) return;
        const lo = Places.lineOf(index, begin);
        var new: std.ArrayList(u8) = .empty;
        try new.appendSlice(arena, text[index[lo]..begin]);
        var hi = lo;
        var at = begin;
        while (k < edits.len) : (k += 1) {
            const from = File.bufferOffset(f, edits[k].start, false);
            const to = File.bufferOffset(f, edits[k].end, edits[k].end > edits[k].start);
            if (from < at or to < from or to > text.len) return;
            if (from > begin and Places.lineOf(index, from) >= hi) break;
            try new.appendSlice(arena, text[at..from]);
            try new.appendSlice(arena, edits[k].text);
            at = to;
            const line = Places.lineOf(index, to);
            // Up to a line's start, from one or past its own text: that
            // line is not changed.
            hi = if (to == index[line] and (to > begin or begin == index[lo])) line else line + 1;
        }
        try new.appendSlice(arena, text[at..if (hi < index.len) index[hi] else text.len]);
        try groups.append(arena, .{ .lo = lo, .hi = hi, .new = new.items });
    }
    const tab = p.settings.tab;
    const y0 = p.bodyTop(pane, r);
    const rows: usize = @min(body_h, s.rows -| y0);
    const first: usize = pane.context_rows;
    if (rows <= first) return;
    const w: usize = s.cols;
    const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]);
    const chrome = p.chrome();
    const ink = chrome.page.text;
    const x0 = r.x + config.GUTTER + File.gutterWidth(pane);
    const width = r.w -| (x0 - r.x);
    var out: usize = first;
    var g: usize = 0;
    var vr: usize = first;
    while (vr < rows and out < rows) : (vr += 1) {
        const shown = pane.wrapAt(tab, @intCast(vr)).line;
        const line: usize = if (shown < 0) index.len else @intCast(shown);
        if (vr == first or pane.wrapAt(tab, @intCast(vr - 1)).line != shown) {
            while (g < groups.items.len and groups.items[g].hi < line) g += 1;
            while (g < groups.items.len and groups.items[g].hi == line) : (g += 1) {
                var news = std.mem.splitScalar(u8, std.mem.trimEnd(u8, groups.items[g].new, "\n"), '\n');
                if (groups.items[g].new.len > 0) while (news.next()) |l| {
                    if (out >= rows) break;
                    const y: u16 = @intCast(y0 + out);
                    s.fill(0, y, @intCast(s.cols), 1, .{});
                    s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = chrome.add.row } });
                    _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = chrome.add.row } });
                    out += 1;
                };
            }
        }
        if (out >= rows) break;
        @memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]);
        if (g < groups.items.len and line >= groups.items[g].lo and line < groups.items[g].hi) s.tint(x0, @intCast(y0 + out), width, chrome.del.row, null);
        out += 1;
    }
}

// ---- keys ----

/// A key in the live picker (keys.zig tagStateKey, SPEC §5.4). Esc is
/// the tag's: TagState.toRest rolls it up.
pub fn key(p: *Pardes, k: Key) void {
    const pk = live(p) orelse return TagState.toRest(p);
    const s = &p.view().tag_state;
    const n: u16 = @intCast(@min(count(p, pk), std.math.maxInt(u16)));
    const plain = !k.ctrl and !k.alt;
    const ctrl = k.ctrl and !k.alt;
    const alt = k.alt and !k.ctrl;
    if (pk.spine == .sources) {
        pk.spine = .rows;
        for (spine_rows) |src| if (plain and k.cp == src.key) return switchTo(p, pk, src.source);
        return;
    }
    if (pk.spine == .acts) return actKey(p, pk, k);
    // Its source's earlier queries unrolled (C-r, UX L2): Down and Up
    // move their cursor, Enter puts the one under it in the field, C-r
    // and Esc (closeHistory) roll them up; anything else is the field's,
    // which filters both.
    if (pk.spine == .history) {
        const r = p.prompt_history.pick.getPtr(pk.source);
        if (pardes.Prompt.historyKey(r, s.field.text(), &pk.recall, k)) return;
        if (plain and k.cp == Key.enter) {
            const at = pardes.Prompt.historyAt(r, s.field.text(), pk.recall);
            pk.spine = .rows;
            pk.recall = 0;
            if (at == 0) return;
            s.field.set(r.get(at).?);
            return filter(p, pk);
        }
        if (ctrl and k.cp == 'r') {
            pk.spine = .rows;
            return;
        }
        pk.recall = 0;
        if (s.field.key(k)) filter(p, pk);
        return;
    }
    // Themes: Enter wears the one under the cursor; actions: Enter, or an
    // action's digit with the field empty, applies it; the rows and the
    // field.
    if (pk.source == .themes or pk.source == .actions or pk.source == .lists) {
        if (plain and k.cp == Key.enter and pk.source == .lists) return reopenListed(p, pk);
        if (plain and k.cp == Key.enter and pk.source == .themes) {
            const at = refAt(p, pk) orelse return;
            TagState.toRest(p);
            pardes.colors.setThemeIndex(p, at);
            return;
        }
        if (plain and k.cp == Key.enter) return apply(p, pk, refAt(p, pk) orelse return);
        if (pk.source == .actions and plain and s.field.len == 0 and k.cp >= '1' and k.cp <= '9') return apply(p, pk, k.cp - '1');
        if (s.rows.key(k, n)) {
            pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown);
            return;
        }
        if (s.field.key(k)) filter(p, pk);
        return;
    }
    if (pk.spine == .edit) {
        if (plain and k.cp == Key.enter) return editRows(p, pk);
        if (plain and k.cp == Key.backspace and s.field.len == 0 or alt and k.cp == 'h') {
            s.field.set(pk.query.slice());
            pk.spine = .rows;
            return;
        }
        _ = s.field.key(k);
        return;
    }
    // A list a walk reopened (UX L'1): Ctrl-o and Ctrl-i walk on from its
    // word, the list rolled up unlanded. Ctrl-i is Tab where the terminal
    // cannot tell them apart: a mark, as Tab.
    if (pk.walking) |at| if (ctrl and (k.cp == 'o' or k.cp == 'i')) return walkOn(p, pk, at, if (k.cp == 'o') -1 else 1);
    // One Resume opened: the next older or newer kept one (UX L'2).
    if (p.resume_at != 0 and ctrl and (k.cp == 'o' or k.cp == 'i')) return resumeAt(p, p.paneBySerial(pk.owner) orelse p.view().active, if (k.cp == 'o') p.resume_at + 1 else p.resume_at - 1);
    if (alt and (k.cp == Key.enter or k.cp == 'l')) {
        pk.spine = .acts;
        pk.act_at = 0;
        return;
    }
    if (plain and k.cp == Key.enter) return land(p, if (k.shift) .below else .walk);
    if (ctrl and k.cp == 's') return land(p, .below);
    if (ctrl and k.cp == 'v') return land(p, .column);
    if (plain and k.cp == Key.tab) {
        if (n == 0) return;
        toggle(p, pk, idOf(pk, s.rows.at));
        _ = s.rows.key(.{ .cp = if (k.shift) Key.up else Key.down }, n);
        return;
    }
    if (alt and k.cp == 'a') return markAll(p, pk);
    if (alt and k.cp == 'h') {
        pk.spine = .sources;
        return;
    }
    if (ctrl and (k.cp == ' ' or k.cp == '@')) return refine(p, pk, false);
    if (ctrl and k.cp == 'q') return keep(p, pk);
    if (ctrl and k.cp == 'r') {
        pk.spine = .history;
        pk.recall = 0;
        return;
    }
    if (alt and k.cp == 'p') {
        pk.previews = !pk.previews;
        pk.shown = no_row;
        if (!pk.previews) putBack(p, pk);
        return;
    }
    if (plain and k.cp == Key.backspace and s.field.len == 0) return back(p, pk);
    // A cursor gone past the rows sorted sorts as far (Names.reach).
    if (s.rows.key(k, n)) {
        if (fuzzy(pk)) pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown);
        return;
    }
    if (s.field.key(k)) filter(p, pk);
}

/// Esc with the live picker's history unrolled (keys.tagStateKey): that
/// rolled up alone, the picker as it was; false with none.
pub fn closeHistory(p: *Pardes) bool {
    const pk = live(p) orelse return false;
    if (pk.spine != .history) return false;
    pk.spine = .rows;
    pk.recall = 0;
    return true;
}

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

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

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

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

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

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

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

/// Ctrl-o (`delta` < 0) or Ctrl-i in a list a walk reopened at step `at`
/// of its landing pane's trail (UX L'1): the list rolled up unlanded, the
/// pane as it was, and the walk on from the list's word; past the last
/// word, the jump list's step.
fn walkOn(p: *Pardes, pk: *Pick, at: u8, delta: i32) void {
    const id = p.paneBySerial(pk.landing) orelse return TagState.toRest(p);
    TagState.toRest(p);
    if (!Trail.walkFrom(p, id, at, delta)) pardes.Jump.listBy(p, delta);
}

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

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

/// Enter: the current row, or the marked ones, looked at from the asking
/// pane (look.open, the walk's way: a reading pane steps, a held one's
/// reader does), the first as `how` says, the others each in a pane below.
/// The list rolls into the landing pane's trail as its word (item 4). From
/// an untouched pane S-Enter and C-v are Enter: it is the free space a new
/// pane would take (UX J1).
fn land(p: *Pardes, wanted: How) void {
    const pk = live(p) orelse return;
    var arena = std.heap.ArenaAllocator.init(p.gpa);
    defer arena.deinit();
    const a = arena.allocator();
    const picked = pickedRows(p, pk, a) catch return;
    if (picked.len == 0) return;
    const walking = pk.walking;
    touch(p, pk);
    p.resume_at = 0;
    // Walk: the first now, the others queued for C-i.
    pk.queue.clearRetainingCapacity();
    pk.queue_bytes.clearRetainingCapacity();
    pk.queue_at = 0;
    if (wanted == .queue) for (picked[1..]) |t| switch (t) {
        .place => |at| {
            const q: Queued = .{ .path = @intCast(pk.queue_bytes.items.len), .len = @intCast(@min(at.path.len, std.math.maxInt(u16))), .line = std.math.lossyCast(u32, at.at.line), .col = std.math.lossyCast(u32, at.at.col) };
            pk.queue_bytes.appendSlice(p.gpa, at.path[0..q.len]) catch break;
            pk.queue.append(p.gpa, q) catch break;
        },
        else => {},
    };
    TagState.toRest(p);
    const v = p.view();
    const owner = p.paneBySerial(pk.owner) orelse v.active;
    const how: How = if ((wanted == .below or wanted == .column) and Trail.untouched(p, p.panes[owner].?)) .walk else wanted;
    // A step from the pane it lands in when that reads (its owner's reader
    // or itself), else from its owner, whose reader the place opens as:
    // where the pane made for the picker was, or in the untouched pane it
    // previewed in (UX J1), given back now.
    const landing = p.paneBySerial(pk.landing) orelse owner;
    const from = if ((how == .walk or how == .queue) and Trail.reading(p, p.panes[landing].?)) landing else owner;
    v.active = from;
    v.jumps.force = true;
    for (picked, 0..) |t, k| switch (t) {
        .none => {},
        .pane => |serial| if (p.paneBySerial(serial)) |tid| {
            v.active = tid;
            if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col);
        } else {
            _ = p.store.reopen(p, serial, from);
        },
        .place => |at| if (k == 0 and (how == .walk or how == .queue)) {
            // A list a walk reopened lands as its word's (UX L'1): a step
            // from that word, the steps after it dropped.
            const word: ?u8 = if (walking) |i| (if (from == landing and isWord(p.panes[from].?, i, pk.id)) i else null) else null;
            if (word) |i| {
                const trail = &p.panes[from].?.trail;
                trail.n = i + 1;
                trail.cur = i;
            }
            switch (look.open(p, from, at.path, at.at, .replace)) {
                .none => {},
                else => listed(p, pk, word),
            }
        } else if (k == 0 and how == .column) {
            // A column made only where there is no free space (UX J1).
            if (layout.freeSpace(p, from, .doc) == null) {
                layout.newColumn(p, from);
                p.exec_column = layout.activeColumn(p) orelse continue;
            }
            defer p.exec_column = null;
            pardes.tagline.exitHeader(p);
            _ = look.open(p, from, at.path, at.at, .below);
        } else if (how != .queue) {
            _ = look.open(p, from, at.path, at.at, .below);
        },
    };
    if (picked[0] == .place) if (p.panes[v.active]) |at| if (at.file) |f| {
        _ = pk.landed.print(config.pane_addr ++ "{d} › {s}:{d}", .{ at.serial, std.Io.Dir.path.basename(f.path), at.body.cur_row + 1 });
    };
    if (how == .queue and pk.queue.items.len > 0) {
        var said: Kind.Buf(64) = .{};
        p.setMessage(.at(v.active), said.print("Walk: {d} more places here, C-i for the next", .{pk.queue.items.len}));
    }
}

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

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

/// Whether step `i` of pane `pane`'s trail is picker `id`'s word.
fn isWord(pane: *const Pane, i: u8, id: u32) bool {
    const t = &pane.trail;
    return i < t.n and t.steps[i] == .list and t.steps[i].list.index == id;
}

/// The list rolled into the trail of the reading pane it landed in, its
/// word before the place: the list `n` and `N` walk there; a list a walk
/// reopened at step `at` says where it is now in that word. The notice row
/// says what Ctrl-o goes back to (UX L'1).
fn listed(p: *Pardes, pk: *const Pick, at: ?u8) void {
    const id = p.view().active;
    const pane = p.panes[id] orelse return;
    if (!Trail.reading(p, pane)) return;
    defer Trail.sayBack(p, id);
    if (at) |i| if (isWord(pane, i, pk.id)) {
        _ = wordOf(p, pk, &pane.trail.steps[i].list.text);
        return;
    };
    var w: Trail.Word = .{ .index = pk.id };
    _ = wordOf(p, pk, &w.text);
    Trail.through(&pane.trail, .{ .list = w });
    // The newest list or search is the word n and N walk (SPEC §6.3): a
    // search's tints go with it (§7.3: lit while it is n's).
    if (pane.places.provenance == .search) pane.places.clear(p.gpa);
}

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

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

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

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

/// Resume (`SPC '`): the newest kept picker reopened as it was, from pane
/// `from`, in the tag of the pane its Enter lands in; again after an Esc
/// from it, nothing typed between, the one before it (UX L'2).
pub fn resumeFrom(p: *Pardes, from: usize) void {
    if (p.resume_at == 0 and nkept(p) == 0) return p.setMessage(.at(from), "Resume: no picker yet");
    if (p.panes[from] == null) return;
    resumeAt(p, from, p.resume_at + 1);
}

/// The `k`th newest kept picker reopened as it was, asked from pane
/// `from`, in the tag of the pane its Enter lands in.
fn resumeAt(p: *Pardes, from: usize, k: usize) void {
    const pk = (if (k > 0) nth(p, k) else null) orelse
        return p.setMessage(.at(from), if (k == 0) "Resume: the newest picker" else "Resume: no picker before it: the last 8 are kept");
    TagState.toRest(p);
    hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "Resume", err);
    unroll(p, pk, pk.query.slice());
    unrollRows(p, pk);
    p.resume_at = @intCast(k);
}

/// A key the tag at rest takes (keys.handleKey): any but the leader and
/// Resume's after it ends a Resume walk, so that `SPC '` opens the newest
/// again (UX L'2).
pub fn keyAtRest(p: *Pardes, k: Key) void {
    const v = p.view();
    if (p.resume_at == 0) return;
    if (v.prefix == .none and pardes.hit(k, config.leader)) return;
    if (v.prefix == .leader and v.leader_n == 0 and !k.ctrl and !k.alt and k.cp == config.leader_path.get(.Resume).?[0]) return;
    p.resume_at = 0;
}

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

/// Enter in Lists (UX L'3): the kept picker under its cursor unrolled again
/// as it was left, where Lists was asked from, and the newest now.
fn reopenListed(p: *Pardes, pk: *Pick) void {
    const kp = byId(p, @intCast(refAt(p, pk) orelse return)) orelse return;
    const from = p.paneBySerial(pk.owner) orelse p.view().active;
    TagState.toRest(p);
    touch(p, kp);
    hostIn(p, kp, from) catch |err| return p.reportError(.at(from), "Lists", err);
    unroll(p, kp, kp.query.slice());
    unrollRows(p, kp);
}

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

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

// ---- acts ----

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

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

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

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

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

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

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

fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 {
    // The directory a work tree of its own, as a project is: Find and Grep
    // search it, not the tree the test runs in.
    tmp.dir.createDir(std.testing.io, ".git", .default_dir) catch |err| if (err != error.PathAlreadyExists) return err;
    try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text });
    var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)];
    return std.Io.Dir.path.join(p.gpa, &.{ dir, name });
}

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

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

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

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

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

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

test "a picker's band is capped once at open at 40 % of its host pane's rows; the host borrows from its column for a body of 60 % before the band gives way: a Grep from a held pane at 100x30 previews 8 rows at least" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var text: std.ArrayList(u8) = .empty;
    defer text.deinit(std.testing.allocator);
    for (0..40) |i| try text.print(std.testing.allocator, "pub fn f{d}() void {{}}\n", .{i});
    const a_path = try testFile(p, &tmp, "alpha.zig", text.items);
    defer p.gpa.free(a_path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" });
    p.stream.engine = .walk;
    p.sync();
    open(p, asker, .grep, "", "", "");
    const reader = p.paneBySerial(live(p).?.landing).?;
    const at_open = p.view().rects[reader].h;
    for ("pub fn") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    p.update(.{ .key = .{ .cp = Key.down } });
    p.sync();
    const pane = p.panes[reader].?;
    const r = p.view().rects[reader];
    const at = Band.covered(p, pane, reader);
    try std.testing.expectEqual(@min(Band.Cursor.shown, at_open * 2 / 5), at.band);
    // The rows under the band, the preview's (no row previewed yet: the
    // band over the reader's text, UX DESIGN I1).
    const under = r.h - @max(pane.tag_rows, at.text + at.band);
    try std.testing.expect(under >= 8);
    try std.testing.expect(@as(u32, under) * 5 >= @as(u32, r.h) * 3);
}

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

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

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

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

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

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

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

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

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

test "code actions: a picker in the asking pane's tag, the one under the cursor its edit in the body (the lines it changes on the deleted ground, what they become after them), Enter or its digit applies it as one undo step, a command's said" {
    const Key_ = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    p.settings.jumps = .walk;
    const pane = try p.setTestFile("one\ntwo add\nthree\n");
    const id = p.view().active;
    // `add` is bytes 8..11.
    const rows = "x:1:1 extract\nx:1:1 add a line\n@put 0 0 //%20top%0A\nx:1:1 rename add to sum\n@put 8 11 sum\n";
    open(p, id, .actions, "", "", rows);
    live(p).?.revision = pane.file.?.revision;
    const s = &p.view().tag_state;
    try std.testing.expectEqual(Source.actions, live(p).?.source);
    try std.testing.expectEqual(pane.serial, s.host);
    try std.testing.expectEqual(@as(usize, 3), count(p, live(p).?));
    // The rename: `two add` on the deleted ground, `two sum` after it.
    p.update(.{ .key = .{ .cp = Key_.down } });
    p.update(.{ .key = .{ .cp = Key_.down } });
    settle(p);
    p.sync();
    var shot = try p.render(frame.allocator());
    const r = p.view().rects[id];
    const x = r.x + config.GUTTER + File.gutterWidth(pane);
    const y = p.bodyTop(pane, r);
    const chrome = p.chrome();
    for ([_][]const u8{ "o", "t", "t", "t" }, [_][]const u8{ "n", "w", "w", "h" }, 0..) |c0, c1, row| {
        try std.testing.expectEqualStrings(c0, shot.at(x, y + @as(u16, @intCast(row))).grapheme());
        try std.testing.expectEqualStrings(c1, shot.at(x + 1, y + @as(u16, @intCast(row))).grapheme());
    }
    try std.testing.expectEqualStrings("a", shot.at(x + 4, y + 1).grapheme());
    try std.testing.expectEqualStrings("s", shot.at(x + 4, y + 2).grapheme());
    try std.testing.expectEqual(pardes.Color{ .rgb = chrome.del.row }, shot.at(x, y + 1).style.bg);
    try std.testing.expectEqual(pardes.Color{ .rgb = chrome.add.row }, shot.at(x, y + 2).style.bg);
    try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content);
    // An action lands nowhere: no landing line, no `▸` before the line it
    // changes, no sentence of where Enter lands (UX D7's are a jump's; an
    // action's preview is its edit on the Changes grounds).
    try std.testing.expect(landingLine(p, frame.allocator(), pane) == null);
    try std.testing.expect(!std.mem.eql(u8, "▸", shot.at(x - 1, y + 1).grapheme()));
    var notice: [pardes.Messages.notice_row_cap]u8 = undefined;
    try std.testing.expect(!pardes.Messages.noticeRow(p, 100, &notice).quiet_left);
    // Up: the line put in at the top, before line 1, nothing deleted.
    p.update(.{ .key = .{ .cp = Key_.up } });
    settle(p);
    p.sync();
    frame.deinit();
    frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    shot = try p.render(frame.allocator());
    try std.testing.expectEqualStrings("/", shot.at(x, y).grapheme());
    try std.testing.expectEqual(pardes.Color{ .rgb = chrome.add.row }, shot.at(x, y).style.bg);
    try std.testing.expectEqualStrings("o", shot.at(x, y + 1).grapheme());
    try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = chrome.del.row }, shot.at(x, y + 1).style.bg));
    try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.chrome().hit }, shot.at(x, y + 1).style.bg));
    // `3`: the rename applied, the tag at rest; one undo takes it back.
    p.update(.{ .key = .{ .cp = '3', .text = "3" } });
    try std.testing.expectEqual(TagState.Kind.rest, s.kind);
    try std.testing.expectEqualStrings("one\ntwo sum\nthree\n", pane.file.?.content);
    p.update(.{ .key = .{ .cp = 'u', .text = "u" } });
    try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content);
    // Enter on a command's: said, nothing changed.
    open(p, id, .actions, "", "", rows);
    live(p).?.revision = pane.file.?.revision;
    p.update(.{ .key = .{ .cp = Key_.enter } });
    try std.testing.expectEqual(TagState.Kind.rest, s.kind);
    try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content);
    try std.testing.expectEqualStrings("Actions: extract: no edit to apply", p.messages.saidBy(pane));
}

test "the themes picker marks the theme in use: `in use` at its row's right end in the dim ink, the cursor on it when it opens, the mark staying on it while the window wears another (POLISH 12, UX A15)" {
    const Key_ = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const was = p.settings.theme;
    for (" tt") |c| p.update(.{ .key = .{ .cp = c } });
    const s = &p.view().tag_state;
    try std.testing.expectEqual(@as(u16, @intCast(was)), s.rows.at);
    // The band's spines hang from the head's first `cells` spans: its key
    // cells (`␣ t`), never its dim hint.
    const h = (try head(p, a, pane)).?;
    try std.testing.expectEqual(@as(u8, 2), h.cells);
    for (h.spans[0..h.cells]) |span| try std.testing.expectEqual(TagState.Style.key, span.style);
    const Find = struct {
        fn row(band: Band, text: []const u8) ?Band.Row {
            for (band.steps[0..band.nsteps]) |step| for (step.rows) |r| if (std.mem.eql(u8, r.text, text)) return r;
            return null;
        }
    };
    var band = (try Band.of(p, a, pane, id)).?;
    const worn = Find.row(band, pardes.colors.themes[was].name).?;
    try std.testing.expectEqualStrings("in use", worn.meta);
    try std.testing.expect(worn.on);
    // One row says it.
    var said: usize = 0;
    for (band.steps[0..band.nsteps]) |step| for (step.rows) |r| {
        said += @intFromBool(r.meta.len > 0);
    };
    try std.testing.expectEqual(@as(usize, 1), said);
    // Drawn at the row's right end, in the dim ink of the selection it is on.
    _ = try p.render(a);
    const layer = &p.surface.tag_layers[pardes.BAND_LAYER];
    const roles = &p.chromeTheme().roles;
    const on = roles.selectedOn(if (pardes.Trail.reading(p, pane)) .reading_focused else .focused);
    var found = false;
    for (0..layer.rows) |row| {
        const cells = layer.cells[row * layer.cols ..][0..layer.cols];
        var at: usize = 0;
        while (at + 6 <= cells.len) : (at += 1) {
            if (!std.mem.eql(u8, cells[at].grapheme(), "i") or !std.mem.eql(u8, cells[at + 1].grapheme(), "n") or !std.mem.eql(u8, cells[at + 3].grapheme(), "u")) continue;
            try std.testing.expectEqual(pardes.Color{ .rgb = on.dim }, cells[at].style.fg);
            found = true;
        }
    }
    try std.testing.expect(found);
    // The window wearing the next: the mark stays on the theme in use.
    p.update(.{ .key = .{ .cp = if (was + 1 < pardes.colors.themes.len) Key_.down else Key_.up } });
    band = (try Band.of(p, a, pane, id)).?;
    try std.testing.expectEqualStrings("in use", Find.row(band, pardes.colors.themes[was].name).?.meta);
}

test "a picker's preview is legible as one (UX D7): its landing line on the hit ground with `▸` in the gutter, a third of the body above it, and the notice row saying where Enter lands" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var text: std.ArrayList(u8) = .empty;
    defer text.deinit(std.testing.allocator);
    for (1..81) |i| try text.print(std.testing.allocator, "line {d} of the file\n", .{i});
    const path = try testFile(p, &tmp, "long.zig", text.items);
    defer p.gpa.free(path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:40:6 line 40 of the file\n", .{path});
    defer std.testing.allocator.free(rows);
    open(p, asker, .list, "Refs", "", rows);
    const pk = live(p).?;
    const reader = p.paneBySerial(pk.landing).?;
    p.update(.tick);
    const pane = p.panes[reader].?;
    try std.testing.expectEqualStrings(path, pane.file.?.path);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const s = try p.render(frame.allocator());
    const r = p.view().rects[reader];
    const body_y = p.bodyTop(pane, r);
    // Line 40 a third of the way down: ⌈rows/3⌉ rows of context above it.
    var at: ?u16 = null;
    for (0..pane.rows) |row| if (pane.wrapAt(p.settings.tab, @intCast(row)).line == 39) {
        at = @intCast(row);
        break;
    };
    try std.testing.expectEqual(@as(?u16, @intCast((pane.rows + 2) / 3)), at);
    const y = body_y + at.?;
    const c = p.chrome();
    const tx = r.x + pardes.config.GUTTER;
    const gutter = File.gutterWidth(pane);
    // Its text on the hit ground across the row; the row above as it was.
    for (gutter..r.w - pardes.config.GUTTER) |x| try std.testing.expectEqual(pardes.Color{ .rgb = c.hit }, s.at(tx + @as(u16, @intCast(x)), y).style.bg);
    try std.testing.expect(!std.meta.eql(s.at(tx + gutter + 2, y - 1).style.bg, pardes.Color{ .rgb = c.hit }));
    // `▸` in the key ink in the gutter's cell after the number.
    const mark = s.at(tx + gutter - 1, y);
    try std.testing.expectEqualStrings("▸", mark.grapheme());
    try std.testing.expectEqual(pardes.Color{ .rgb = c.page.key }, mark.style.fg);
    // The notice row: where Enter lands, the owner's address a word in it.
    var buf: [pardes.Messages.notice_row_cap]u8 = undefined;
    const said = pardes.Messages.noticeRow(p, 120, &buf);
    const want = try std.fmt.allocPrint(frame.allocator(), "⏎ lands in @p{d}'s reader · its text is the preview · S-⏎ a new pane", .{p.panes[asker].?.serial});
    try std.testing.expect(std.mem.startsWith(u8, said.text, want));
    try std.testing.expect(said.quiet_left);
    try std.testing.expectEqualStrings(try std.fmt.allocPrint(frame.allocator(), "@p{d}", .{p.panes[asker].?.serial}), said.text[said.word[0]..said.word[1]]);
    // At rest: no ground, no mark, the row back to its own.
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expect(!pardes.Messages.noticeRow(p, 120, &buf).quiet_left);
}

test "a list of places (a Grep's, a list's) shows each row's `path:line` in the dim ink and its text after it in one column, the widest place shown before it (UX E7 2b)" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "a.zig", "one\ntwo\nconst x = 1;\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "a_longer_name.zig", "fn y() void {}\n");
    defer p.gpa.free(b_path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:3:1 const x = 1;\n{s}:1:4 fn y() void {{}}\n", .{ a_path, b_path });
    defer std.testing.allocator.free(rows);
    open(p, asker, .list, "Refs", "", rows);
    p.update(.tick);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const got = (try steps(p, frame.allocator()))[0].rows;
    try std.testing.expectEqual(@as(usize, 2), got.len);
    const code = [2][]const u8{ "const x = 1;", "fn y() void {}" };
    var col: [2]usize = undefined;
    for (got, code, &col) |row, text, *c| {
        const at = std.mem.indexOf(u8, row.text, text).?;
        c.* = File.displayWidth(8, row.text[0..at]);
        // The place dim up to its blank (`path:3:1`); the text after it not.
        try std.testing.expect(row.pre > 0);
        try std.testing.expectEqual(@as(u16, 0), row.quiet[0]);
        try std.testing.expectEqual(':', row.text[row.quiet[1] - 2]);
        try std.testing.expectEqual(' ', row.text[row.quiet[1]]);
    }
    try std.testing.expectEqual(col[0], col[1]);
    // One cell after the widest place.
    try std.testing.expectEqual(File.displayWidth(8, b_path) + ":1:4 ".len, col[1]);
    // As the band draws them, its last step the band's width (UX E3): the
    // text still in one column.
    const host = TagState.hostOf(p).?;
    const band = (try Band.of(p, frame.allocator(), p.panes[host].?, host)).?;
    const last = band.steps[band.nsteps - 1];
    try std.testing.expectEqual(band.columns, last.x + last.width);
    for (code, &col, 0..) |text, *c, y| {
        const ln = try band.line(frame.allocator(), p.settings.tab, @intCast(y));
        c.* = File.displayWidth(p.settings.tab, ln.text[0..std.mem.indexOf(u8, ln.text, text).?]);
    }
    try std.testing.expectEqual(col[0], col[1]);
}

test "code actions: a row that cannot be applied (a command's, an edit reaching other files) is dim, its meta `command` or `other files`; the edit under the cursor a third of the way down the body (UX E5 12, D7)" {
    const Key_ = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    p.settings.jumps = .walk;
    var text: std.ArrayList(u8) = .empty;
    defer text.deinit(std.testing.allocator);
    for (1..81) |i| try text.print(std.testing.allocator, "line {d}\n", .{i});
    const pane = try p.setTestFile(text.items);
    const id = p.view().active;
    // Line 50 starts after lines 1-49.
    var at: usize = 0;
    for (1..50) |i| at += std.fmt.count("line {d}\n", .{i});
    const rows = try std.fmt.allocPrint(frame.allocator(), "x:1:1 extract\nx:1:1 move to a new file\n@elsewhere\nx:1:1 rename\n@put {d} {d} LINE\n", .{ at, at + 4 });
    open(p, id, .actions, "", "", rows);
    live(p).?.revision = pane.file.?.revision;
    const got = (try steps(p, frame.allocator()))[0].rows;
    try std.testing.expectEqual(@as(usize, 3), got.len);
    try std.testing.expect(got[0].dim);
    try std.testing.expectEqualStrings("command", got[0].meta);
    try std.testing.expect(got[1].dim);
    try std.testing.expectEqualStrings("other files", got[1].meta);
    try std.testing.expect(!got[2].dim);
    try std.testing.expectEqualStrings("", got[2].meta);
    // As the band draws it, its step the band's width (UX E3): the meta
    // at the band's right end.
    const band = (try Band.of(p, frame.allocator(), pane, TagState.hostOf(p).?)).?;
    const ln = try band.line(frame.allocator(), p.settings.tab, 0);
    try std.testing.expect(std.mem.endsWith(u8, ln.text, "  command"));
    try std.testing.expectEqual(@as(usize, band.columns), File.displayWidth(p.settings.tab, ln.text));
    // The rename's: its line (50) a third of the way down the body.
    p.update(.{ .key = .{ .cp = Key_.down } });
    p.update(.{ .key = .{ .cp = Key_.down } });
    settle(p);
    p.sync();
    var row_at: ?u16 = null;
    for (0..pane.rows) |row| if (pane.wrapAt(p.settings.tab, @intCast(row)).line == 49) {
        row_at = @intCast(row);
        break;
    };
    try std.testing.expectEqual(@as(?u16, @intCast((pane.rows + 2) / 3)), row_at);
}

test "a picker previews the row under its cursor from the frame its rows come, when a frame with none came first: a Find's listing, a Grep's lines after their pause (UX D7)" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\npub fn a() void {}\n");
    defer p.gpa.free(a_path);
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" });
    p.stream.engine = .walk;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    // Find, its field empty: a frame before the listing comes (a host's
    // worker sends it by an input of its own, after the step that asked).
    open(p, asker, .find, "", "", "");
    const reader = p.paneBySerial(live(p).?.landing).?;
    produceAll(p, true);
    try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?));
    // No rows: no frame owed for a preview.
    try std.testing.expect(!busy(p));
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?));
    try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path);
    try std.testing.expectEqual(@as(?usize, 0), landingLine(p, frame.allocator(), p.panes[reader].?));
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Grep: its lines come once the typing pauses, frames with none before.
    open(p, asker, .grep, "", "", "");
    const greader = p.paneBySerial(live(p).?.landing).?;
    for ("pub") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    p.update(.tick);
    try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?));
    try std.testing.expect(!busy(p));
    p.clock.now_ns = p.stream.due_ns.?;
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?));
    try std.testing.expectEqualStrings(a_path, p.panes[greader].?.file.?.path);
    try std.testing.expectEqual(@as(?usize, 1), landingLine(p, frame.allocator(), p.panes[greader].?));
}

test "Backspace on a Messages picker's empty field goes back to the level it was run from, SPC h, unrolled and drawn: its keys are its level's, as every other picker's are" {
    const Key_ = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    _ = try p.setTestFile("one\ntwo\n");
    for (" hm") |c| p.update(.{ .key = .{ .cp = c } });
    try std.testing.expectEqual(Source.messages, live(p).?.source);
    p.sync();
    _ = try p.render(frame.allocator());
    p.update(.{ .key = .{ .cp = Key_.backspace } });
    try std.testing.expect(p.view().prefix == .leader and p.view().tag_state.unrolled);
    try std.testing.expectEqualStrings("h", p.view().leader_keys[0..p.view().leader_n]);
    p.sync();
    _ = try p.render(frame.allocator());
}

test "a picker started in an untouched +New previews in it (UX J1): no pane made, Esc gives it back empty, Enter lands in it, the same pane by its number, reading, its trail starting at the list word; S-Enter there is Enter" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n");
    defer p.gpa.free(b_path);
    const rows = try std.fmt.allocPrint(p.gpa, "{s}:3:1 three\n", .{b_path});
    defer p.gpa.free(rows);
    _ = try p.setTestFile("first\n");
    for ([_]bool{ false, true }) |shift| {
        exec.runBuiltin(p, .New, 0, "New", null);
        p.sync();
        const scratch = p.view().active;
        const serial = p.panes[scratch].?.serial;
        const top = p.view().rects[scratch].y;
        const npanes = paneCount(p);
        try std.testing.expect(Trail.untouched(p, p.panes[scratch].?));
        open(p, scratch, .list, "Refs", "", rows);
        settle(p);
        p.update(.tick);
        try std.testing.expect(!live(p).?.made);
        try std.testing.expectEqual(serial, live(p).?.landing);
        try std.testing.expectEqual(npanes, paneCount(p));
        try std.testing.expectEqualStrings(b_path, p.panes[scratch].?.file.?.path);
        // Esc: the +New as it was, still free space.
        p.update(.{ .key = .{ .cp = Key.escape } });
        try std.testing.expectEqual(npanes, paneCount(p));
        try std.testing.expect(Trail.untouched(p, p.panes[scratch].?));
        try std.testing.expectEqual(serial, p.panes[scratch].?.serial);
        // Enter (or S-Enter): the file in it.
        open(p, scratch, .list, "Refs", "", rows);
        settle(p);
        p.update(.{ .key = .{ .cp = Key.enter, .shift = shift } });
        p.sync();
        try std.testing.expect(live(p) == null);
        const here = p.panes[p.view().active].?;
        try std.testing.expectEqual(serial, here.serial);
        try std.testing.expectEqualStrings(b_path, here.file.?.path);
        try std.testing.expectEqual(@as(i32, 2), here.body.cur_row);
        try std.testing.expectEqual(npanes, paneCount(p));
        try std.testing.expectEqual(top, p.view().rects[p.view().active].y);
        try std.testing.expect(Trail.reading(p, here));
        try std.testing.expectEqual(@as(u8, 2), here.trail.n);
        try std.testing.expect(here.trail.steps[0] == .list and here.trail.steps[1] == .place);
    }
}

test "a picker from a held pane previews in an untouched +New (UX J1): Esc gives it back empty, Enter makes it the held pane's reader by its number; C-v lands in an empty column rather than making one" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n");
    defer p.gpa.free(b_path);
    const rows = try std.fmt.allocPrint(p.gpa, "{s}:3:1 three\n", .{b_path});
    defer p.gpa.free(rows);
    _ = try p.setTestFile("held\n");
    const held = p.view().active;
    Trail.keep(p.panes[held].?);
    exec.runBuiltin(p, .New, held, "New", null);
    p.sync();
    const scratch = p.view().active;
    const serial = p.panes[scratch].?.serial;
    p.view().active = held;
    const npanes = paneCount(p);
    open(p, held, .list, "Refs", "", rows);
    settle(p);
    p.update(.tick);
    try std.testing.expect(!live(p).?.made);
    try std.testing.expectEqual(serial, live(p).?.landing);
    try std.testing.expectEqualStrings(b_path, p.panes[scratch].?.file.?.path);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(npanes, paneCount(p));
    try std.testing.expect(Trail.untouched(p, p.panes[scratch].?));
    open(p, held, .list, "Refs", "", rows);
    settle(p);
    p.update(.{ .key = .{ .cp = Key.enter } });
    p.sync();
    const reader = Trail.readerOf(p, p.panes[held].?).?;
    try std.testing.expectEqual(serial, p.panes[reader].?.serial);
    try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path);
    try std.testing.expectEqual(p.panes[held].?.serial, p.panes[reader].?.trail.steps[0].owner);
    try std.testing.expectEqual(npanes, paneCount(p));
    // C-v with an empty column there: the place goes in it.
    Trail.keep(p.panes[reader].?);
    const c = layout.insertColumn(p, layout.findPane(p, held).?.col, false).?;
    p.sync();
    const ncol = p.view().ncol;
    open(p, held, .list, "Refs", "", rows);
    settle(p);
    p.update(.{ .key = .{ .cp = 'v', .ctrl = true } });
    p.sync();
    try std.testing.expectEqual(ncol, p.view().ncol);
    try std.testing.expectEqual(c, layout.findPane(p, p.view().active).?.col);
    try std.testing.expectEqualStrings(b_path, p.panes[p.view().active].?.file.?.path);
}

test "a picker's preview starts under its band: its landing line ⌈visible/3⌉ rows below the band's last row, a file's line 1 on the row right under it; before its first row and after Esc the pane's own text where it was at rest (UX DESIGN I1, W1's reading)" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var text: std.ArrayList(u8) = .empty;
    defer text.deinit(std.testing.allocator);
    for (1..121) |i| try text.print(std.testing.allocator, "line {d} of the file\n", .{i});
    const path = try testFile(p, &tmp, "long.zig", text.items);
    defer p.gpa.free(path);
    var own: std.ArrayList(u8) = .empty;
    defer own.deinit(std.testing.allocator);
    for (1..81) |i| try own.print(std.testing.allocator, "own {d}\n", .{i});
    const pane = try p.setTestFile(own.items);
    const id = p.view().active;
    pane.focus = .body;
    for ("75j") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    p.sync();
    const r = p.view().rects[id];
    const rest = .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) };
    try std.testing.expect(rest[2] > 0);
    const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:60:1 line 60 of the file\n{s}:1:1 line 1 of the file\n", .{ path, path });
    defer std.testing.allocator.free(rows);
    open(p, id, .list, "Refs", "", rows);
    p.sync();
    // In the pane itself (it reads), no row shown yet: its text stays.
    try std.testing.expectEqual(id, p.paneBySerial(live(p).?.landing).?);
    try std.testing.expect(!previewing(p, id));
    try std.testing.expectEqual(rest, .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) });
    try std.testing.expect(Band.covered(p, pane, id).over > 0);
    // The first row shown: the body under the band, line 60 a third of
    // its rows down.
    p.update(.tick);
    try std.testing.expect(previewing(p, id));
    try std.testing.expectEqualStrings(path, pane.file.?.path);
    const at = Band.covered(p, pane, id);
    try std.testing.expectEqual(@as(u16, 0), at.over);
    try std.testing.expectEqual(p.tagTop(pane, r) + at.text + at.band, p.bodyTop(pane, r));
    try std.testing.expectEqual(@as(usize, 59 - (pane.rows + 2) / 3), pane.file.?.scroll);
    // Line 1: on the row right under the band.
    p.update(.{ .key = .{ .cp = Key.down } });
    p.update(.tick);
    try std.testing.expectEqual(@as(usize, 0), pane.file.?.scroll);
    try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
    // Esc: the pane's own text, where it was at rest.
    p.update(.{ .key = .{ .cp = Key.escape } });
    p.sync();
    try std.testing.expect(live(p) == null);
    try std.testing.expectEqual(rest, .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) });
    try std.testing.expect(std.mem.startsWith(u8, pane.file.?.content, "own 1\n"));
}

test "SPC ' steps back through the kept pickers (UX L'2): again after an Esc, nothing typed between, the one before; Ctrl-o and Ctrl-i in it the next older and newer, its head `Resume 2/3`; a key between, the newest again; a list word naming a picker no longer kept says so and the walk passes it by" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "base.zig", "text\n");
    const base = try p.setTestFile("text\n");
    p.gpa.free(base.file.?.path);
    base.file.?.path = b_path;
    const id = p.view().active;
    const row = try std.fmt.allocPrint(p.gpa, "{s}:2:1 two\n", .{a_path});
    defer p.gpa.free(row);
    // Three lists kept, C the newest.
    for ([_][]const u8{ "A", "B", "C" }) |word| {
        open(p, id, .list, word, "", row);
        p.update(.{ .key = .{ .cp = Key.escape } });
    }
    try std.testing.expect(live(p) == null);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const Shown = struct {
        /// The live picker's word and its head's `Resume k/N`, as `2/3 B`.
        fn of(pp: *Pardes, a: std.mem.Allocator) ![]const u8 {
            const pk = live(pp) orelse return "none";
            const h = (try head(pp, a, pp.panes[pp.paneBySerial(pk.landing).?].?)).?;
            const at = std.mem.indexOf(u8, h.text, "Resume ") orelse return pk.word.slice();
            const end = std.mem.indexOfScalarPos(u8, h.text, at + "Resume ".len, ' ').?;
            return std.fmt.allocPrint(a, "{s} {s}", .{ h.text[at + "Resume ".len .. end], pk.word.slice() });
        }
    };
    const Step = struct { keys: []const u8, want: []const u8 };
    for ([_]Step{
        .{ .keys = " '", .want = "1/3 C" },
        .{ .keys = "\x1b '", .want = "2/3 B" },
        .{ .keys = "o", .want = "3/3 A" },
        .{ .keys = "o", .want = "3/3 A" },
        .{ .keys = "i", .want = "2/3 B" },
        .{ .keys = "i", .want = "1/3 C" },
        .{ .keys = "\x1bj '", .want = "1/3 C" },
        .{ .keys = "\x1b '", .want = "2/3 B" },
    }, 0..) |step, n| {
        for (step.keys) |c| switch (c) {
            0x1b => p.update(.{ .key = .{ .cp = Key.escape } }),
            // Ctrl-o and Ctrl-i alone in a step: in the picker.
            'o', 'i' => p.update(.{ .key = .{ .cp = c, .ctrl = true } }),
            else => p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }),
        };
        errdefer std.debug.print("step {d}\n", .{n});
        try std.testing.expectEqualStrings(step.want, try Shown.of(p, frame.allocator()));
        if (n == 3) try std.testing.expect(std.mem.indexOf(u8, p.messages.headline().?.words(), "no picker before it") != null);
    }
    // Its Enter lands as any list's: the walk over, it the newest.
    p.update(.{ .key = .{ .cp = Key.enter } });
    p.sync();
    p.update(.{ .key = .{ .cp = ' ', .text = " " } });
    p.update(.{ .key = .{ .cp = '\'', .text = "'" } });
    try std.testing.expectEqualStrings("1/3 B", try Shown.of(p, frame.allocator()));
    p.update(.{ .key = .{ .cp = Key.escape } });
    // A list word naming a picker no longer kept: said, and passed by.
    const reader = p.view().active;
    const t = &p.panes[reader].?.trail;
    try std.testing.expect(t.n == 3 and t.cur == 2 and t.steps[1] == .list);
    t.steps[1].list.index = 999_999;
    p.update(.{ .key = .{ .cp = 'o', .ctrl = true } });
    p.sync();
    try std.testing.expect(std.mem.indexOf(u8, p.messages.headline().?.words(), "that list is gone: the last 8 are kept") != null);
    try std.testing.expect(live(p) == null);
    try std.testing.expectEqualStrings("base.zig", std.Io.Dir.path.basename(p.panes[p.view().active].?.file.?.path));
    try std.testing.expectEqual(@as(u8, 0), p.panes[p.view().active].?.trail.cur);
}

test "Lists (UX L'3): a picker of the kept pickers, newest first, each its list word and where it last landed; the body previews the one under the cursor at its current row, its rows beside, its cursor's marked; Enter reopens it as it was left, the newest now; Lists is never kept and drops none of the eight for its room" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\n");
    defer p.gpa.free(a_path);
    const b_path = try testFile(p, &tmp, "beta.zig", "b1\nb2\n");
    defer p.gpa.free(b_path);
    const base = try p.setTestFile("text\n");
    p.gpa.free(base.file.?.path);
    base.file.?.path = try testFile(p, &tmp, "base.zig", "text\n");
    const rows = try std.fmt.allocPrint(p.gpa, "{s}:2:1 two\n{s}:2:1 b2\n", .{ a_path, b_path });
    defer p.gpa.free(rows);
    // Eight kept: A to F, G left on its second row, H landed, the newest.
    for ("ABCDEFG") |c| {
        open(p, p.view().active, .list, &[_]u8{c}, "", rows);
        if (c == 'G') p.update(.{ .key = .{ .cp = Key.down } });
        p.update(.{ .key = .{ .cp = Key.escape } });
    }
    open(p, p.view().active, .list, "H", "", rows);
    p.update(.{ .key = .{ .cp = Key.enter } });
    p.sync();
    const at = p.view().active;
    var ids: [max_lists]u32 = undefined;
    for (&ids, 1..) |*id, k| id.* = nth(p, max_lists + 1 - k).?.id;
    exec.runBuiltin(p, .Lists, at, "", null);
    const lists = live(p).?;
    try std.testing.expectEqual(Source.lists, lists.source);
    // None dropped for it, and it is none of the kept.
    try std.testing.expectEqual(@as(usize, max_lists), nkept(p));
    for (ids) |id| try std.testing.expect(byId(p, id) != null);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    try std.testing.expectEqual(@as(usize, max_lists), count(p, lists));
    var buf: [64]u8 = undefined;
    for ("HGFEDCBA", 0..) |c, i| {
        const row = try rowAt(p, lists, a, i);
        try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{c} {d}/2", .{ c, @as(u8, if (c == 'G') 2 else 1) }), row.text);
        if (c == 'H') try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "@p{d} › alpha.zig:2", .{p.panes[at].?.serial}), row.meta);
    }
    // On G: the body previews its current row, beta.zig's line 2; its rows
    // beside, its cursor's marked.
    p.update(.{ .key = .{ .cp = Key.down } });
    settle(p);
    const host = p.panes[p.paneBySerial(lists.landing).?].?;
    try std.testing.expectEqualStrings(b_path, host.file.?.path);
    try std.testing.expectEqual(@as(i32, 1), host.body.cur_row);
    const band = try steps(p, a);
    try std.testing.expect(band.len == 2 and band[1].doc and band[1].rows.len == 2);
    try std.testing.expect(std.mem.startsWith(u8, band[1].rows[1].text, "▶ ") and std.mem.startsWith(u8, band[1].rows[0].text, "  "));
    // Enter: G as it was left, the newest now; Lists rolled up.
    p.update(.{ .key = .{ .cp = Key.enter } });
    const g = live(p).?;
    try std.testing.expectEqualStrings("G", g.word.slice());
    try std.testing.expectEqual(@as(u16, 1), p.view().tag_state.rows.at);
    try std.testing.expect(nth(p, 1).? == g);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // A ninth picker drops the oldest kept, never for Lists' room.
    open(p, p.view().active, .list, "I", "", rows);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(@as(usize, max_lists), nkept(p));
    try std.testing.expect(byId(p, ids[0]) == null and byId(p, ids[1]) != null);
    // `'` among a picker's sources (M-h): Lists, from where it was asked.
    open(p, p.view().active, .list, "J", "", rows);
    p.update(.{ .key = .{ .cp = 'h', .alt = true } });
    p.update(.{ .key = .{ .cp = '\'', .text = "'" } });
    try std.testing.expectEqual(Source.lists, live(p).?.source);
    try std.testing.expectEqualStrings("J 1/2", (try rowAt(p, live(p).?, a, 0)).text);
    p.update(.{ .key = .{ .cp = Key.escape } });
}

test "Ctrl-r in a picker unrolls its source's earlier queries (UX L2's last line): recorded as a picker lands and as it is left with its field typed; the band's rows filtered by the field, Enter puts one in the field, Esc closes the band; each source its own; Lists none; as many as a prompt's history keeps" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    p.stream.engine = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const w_path = try testFile(p, &tmp, "words.zig", "in_word\n");
    defer p.gpa.free(w_path);
    const base = try p.setTestFile("text\n");
    p.gpa.free(base.file.?.path);
    base.file.?.path = try testFile(p, &tmp, "main.zig", "text\n");
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const History = struct {
        /// The history band's rows, joined by `|`; "" with none shown.
        fn rows(pp: *Pardes, a: std.mem.Allocator) ![]const u8 {
            const band = try steps(pp, a);
            if (band.len < 2) return "";
            var out: std.ArrayList(u8) = .empty;
            for (band[1].rows, 0..) |row, i| try out.print(a, "{s}{s}", .{ if (i > 0) "|" else "", row.text });
            return out.items;
        }
    };
    const ctrl_r: Key = .{ .cp = 'r', .ctrl = true };
    const Type = struct {
        fn keys(pp: *Pardes, text: []const u8) void {
            for (text) |c| pp.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
        }
    };
    // SPC f f words, Enter: `words` is Find's.
    Type.keys(p, " ffwords");
    settle(p);
    p.update(.{ .key = .{ .cp = Key.enter } });
    p.sync();
    try std.testing.expect(live(p) == null);
    // A Grep left with its field typed: `in_w` is Grep's.
    Type.keys(p, " fgin_w");
    p.update(.{ .key = .{ .cp = Key.escape } });
    // SPC f f, Ctrl-r: Find's alone.
    Type.keys(p, " ff");
    p.update(.{ .key = ctrl_r });
    try std.testing.expectEqualStrings("words", try History.rows(p, frame.allocator()));
    // Esc closes the band, back to the picker; Ctrl-r again, Enter: the
    // line in the field, the rows filtered by it.
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(live(p) != null);
    try std.testing.expectEqualStrings("", try History.rows(p, frame.allocator()));
    p.update(.{ .key = ctrl_r });
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expect(live(p) != null);
    try std.testing.expectEqualStrings("words", p.view().tag_state.field.text());
    try std.testing.expectEqualStrings("", try History.rows(p, frame.allocator()));
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?));
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Grep's: its own line.
    Type.keys(p, " fg");
    p.update(.{ .key = ctrl_r });
    try std.testing.expectEqualStrings("in_w", try History.rows(p, frame.allocator()));
    p.update(.{ .key = .{ .cp = Key.escape } });
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Lists keeps none: left with its field typed, nothing recorded.
    Type.keys(p, " flzz");
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(@as(u8, 0), p.prompt_history.pick.get(.lists).n);
    // The bound: a prompt's history's, the oldest gone, newest first; the
    // rows filtered by the field.
    for (0..pardes.Prompt.Ring.max + 1) |i| {
        Type.keys(p, " ff");
        var q: [8]u8 = undefined;
        Type.keys(p, try std.fmt.bufPrint(&q, "q{d}", .{i}));
        p.update(.{ .key = .{ .cp = Key.escape } });
    }
    const find = p.prompt_history.pick.get(.find);
    try std.testing.expectEqual(@as(u8, pardes.Prompt.Ring.max), find.n);
    try std.testing.expectEqualStrings("q16", find.get(1).?);
    try std.testing.expectEqualStrings("q1", find.get(pardes.Prompt.Ring.max).?);
    Type.keys(p, " ffq1");
    p.update(.{ .key = ctrl_r });
    const shown = try History.rows(p, frame.allocator());
    try std.testing.expect(std.mem.startsWith(u8, shown, "q16|q15|q14|q13|q12|q11|q10|q1"));
    try std.testing.expect(std.mem.indexOf(u8, shown, "words") == null);
    p.update(.{ .key = .{ .cp = Key.escape } });
    p.update(.{ .key = .{ .cp = Key.escape } });
}

/// A Symbols picker opened from a file pane whose path is `name` and text
/// `text`, its symbols parsed (small: here and now), and the pane.
fn openSymbols(p: *Pardes, name: []const u8, text: []const u8) !*Pane {
    const pane = try p.setTestFile(text);
    p.gpa.free(pane.file.?.path);
    pane.file.?.path = try p.gpa.dupe(u8, name);
    open(p, p.view().active, .symbols, "", "", "");
    settle(p);
    return pane;
}

/// The live picker's rows, `meta text` a line each.
fn rowLines(p: *Pardes, a: std.mem.Allocator) ![]const u8 {
    const pk = live(p).?;
    var out: std.ArrayList(u8) = .empty;
    for (0..count(p, pk)) |i| {
        const r = try rowAt(p, pk, a, i);
        try out.print(a, "{s: >2} {s}\n", .{ r.meta, r.text });
    }
    return out.items;
}

const counts_zig =
    \\const std = @import("std");
    \\pub const Counts = struct {
    \\    lines: usize = 0,
    \\    words: usize = 0,
    \\    pub const zero: Counts = .{};
    \\    pub fn add(c: *Counts, text: []const u8) void {
    \\        const local = text.len;
    \\        c.lines += local;
    \\    }
    \\};
    \\const Mode = enum { fast, slow };
    \\var hits: u32 = 0;
    \\pub fn count(text: []const u8) Counts {
    \\    return .{ .lines = text.len };
    \\}
    \\test "count.add" {}
    \\
;

test "Symbols (UX DESIGN N): a Zig file's rows types, functions, fields, then the rest, each in the text's order with the field empty; a row its kind's mark, its name qualified, what its first line says after it, its line the meta; the mark in the keyword's ink, the qualifier and the rest dim" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    _ = try openSymbols(p, "/w6/counts.zig", counts_zig);
    try std.testing.expectEqualStrings(
        \\ 2 t Counts  = struct
        \\11 t Mode  = enum { fast, slow }
        \\ 6 f Counts.add  (c: *Counts, text: []const u8) void
        \\13 f count  (text: []const u8) Counts
        \\ 3 m Counts.lines  : usize = 0
        \\ 4 m Counts.words  : usize = 0
        \\11 m Mode.fast
        \\11 m Mode.slow
        \\ 1 n std  = @import("std")
        \\ 5 c Counts.zero  : Counts = .{}
        \\12 v hits  : u32 = 0
        \\16 · "count.add"
        \\
    , try rowLines(p, a));
    // The qualifier dim, `Counts.`; a name holding a `.` none of it.
    try std.testing.expectEqual(@as(u16, "Counts.".len), (try rowAt(p, live(p).?, a, 4)).faint);
    try std.testing.expectEqual(@as(u16, 0), (try rowAt(p, live(p).?, a, 11)).faint);
    // Drawn: `m Counts.lines  : usize = 0` (not the cursor's row).
    const pane = p.panes[p.paneBySerial(live(p).?.landing).?].?;
    _ = try p.render(a);
    const layer = &p.surface.tag_layers[pardes.BAND_LAYER];
    const roles = &p.chromeTheme().roles;
    const inks = roles.on(if (Trail.reading(p, pane)) .reading_focused else .focused);
    var found = false;
    for (0..layer.rows) |y| {
        const cells = layer.cells[y * layer.cols ..][0..layer.cols];
        var text: std.ArrayList(u8) = .empty;
        var at: std.ArrayList(usize) = .empty;
        for (cells, 0..) |c, x| {
            try at.append(a, text.items.len);
            try text.appendSlice(a, c.grapheme());
            _ = x;
        }
        const from = std.mem.indexOf(u8, text.items, "m Counts.lines") orelse continue;
        var x: usize = 0;
        while (at.items[x] < from) x += 1;
        try std.testing.expectEqual(pardes.Color{ .rgb = p.chrome().on(.focus).kind }, cells[x].style.fg);
        try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 2].style.fg);
        try std.testing.expectEqual(pardes.Color{ .rgb = inks.text }, cells[x + 9].style.fg);
        try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 16].style.fg);
        // Its line at the row's right end, dim.
        const three = std.mem.lastIndexOfScalar(u8, text.items, '3').?;
        var m: usize = 0;
        while (at.items[m] < three) m += 1;
        try std.testing.expect(m > x + 30);
        try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[m].style.fg);
        found = true;
    }
    try std.testing.expect(found);
}

test "Symbols (UX DESIGN N3): typed, the rows stay grouped, scored within each group, and the cursor starts on the best match wherever its group puts it; the name alone is matched, never the signature" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const pane = try openSymbols(p, "/w6/counts.zig", counts_zig);
    for ("count") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    const rows = try rowLines(p, a);
    try std.testing.expect(std.mem.startsWith(u8, rows,
        \\ 2 t Counts  = struct
        \\13 f count  (text: []const u8) Counts
        \\ 6 f Counts.add  (c: *Counts, text: []const u8) void
        \\ 3 m Counts.lines  : usize = 0
        \\ 4 m Counts.words  : usize = 0
        \\
    ));
    // `count` matched best: the cursor on it, not on the first row, and
    // the count says where it is.
    const s = &p.view().tag_state;
    try std.testing.expectEqual(@as(u16, 1), s.rows.at);
    const h = (try head(p, a, p.panes[p.paneBySerial(live(p).?.landing).?].?)).?;
    try std.testing.expect(std.mem.indexOf(u8, h.text, "2/7") != null);
    // Enter lands on its line.
    _ = pane;
    // `u8` is in signatures only: nothing matches.
    for (0..5) |_| p.update(.{ .key = .{ .cp = pardes.Key.backspace } });
    for ("u8") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?));
}

test "Symbols (UX DESIGN N): a C++ file's rows by its kind table, members named in their class and namespace, a function's locals none" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    _ = try openSymbols(p, "/w6/parser.cc",
        \\#define LIMIT 4
        \\namespace torque {
        \\class Parser : public Base {
        \\ public:
        \\  Parser();
        \\  int Parse(int depth) const { return depth; }
        \\  int depth_;
        \\};
        \\enum class Kind { kA, kB };
        \\int Parser::Run(int n) { int local = n; return local; }
        \\static int counter = 0;
        \\const int limit = 4;
        \\using Alias = int;
        \\}
        \\
    );
    try std.testing.expectEqualStrings(
        \\ 3 t torque.Parser  : public Base
        \\ 9 t torque.Kind
        \\13 t torque.Alias  = int
        \\ 5 f torque.Parser.Parser  ()
        \\ 6 f torque.Parser.Parse  (int depth) const
        \\10 f torque.Parser::Run  (int n)
        \\ 7 m torque.Parser.depth_
        \\ 9 m torque.Kind.kA
        \\ 9 m torque.Kind.kB
        \\ 1 · LIMIT  4
        \\ 2 n torque
        \\11 v torque.counter  = 0
        \\12 c torque.limit  = 4
        \\
    , try rowLines(p, frame.allocator()));
}

test "Symbols: every row is ordinary text: no header rows, the cursor steps onto each in turn, the band shows each row's text, and C-q keeps them in a +Search with the mark a word" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
    defer p.deinit();
    p.settings.jumps = .walk;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    _ = try openSymbols(p, "/w6/counts.zig", counts_zig);
    const pk = live(p).?;
    const n = count(p, pk);
    try std.testing.expectEqual(@as(usize, 12), n);
    const s = &p.view().tag_state;
    for (0..n) |i| {
        try std.testing.expectEqual(@as(u16, @intCast(i)), s.rows.at);
        const r = try rowAt(p, pk, a, i);
        const host = p.paneBySerial(pk.landing).?;
        const band = (try Band.of(p, a, p.panes[host].?, host)).?;
        var shown = false;
        for (0..band.height) |y| {
            const ln = try band.line(a, p.settings.tab, @intCast(y));
            shown = shown or std.mem.indexOf(u8, ln.text, r.text) != null;
        }
        try std.testing.expect(shown);
        p.update(.{ .key = .{ .cp = pardes.Key.down } });
    }
    p.update(.{ .key = .{ .cp = 'q', .ctrl = true } });
    var kept: ?[]const u8 = null;
    for (p.panes) |slot| if (slot) |tp| if (tp.file) |f| if (std.mem.startsWith(u8, f.content, "Symbols ")) {
        kept = f.content;
    };
    try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:3 m Counts.lines  : usize = 0\n") != null);
    try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:2 t Counts  = struct\n") != null);
}

test "Find and Grep search the work tree (W8): from a pane deep in a repo Find lists the files from its root and `sub/name` narrows it, a leading directory narrows Grep, and outside a repo they search the pane's directory" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    p.settings.jumps = .walk;
    p.stream.engine = .walk;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    for ([_][]const u8{ "src/deep", "sub", "other" }) |d| try tmp.dir.createDirPath(std.testing.io, d);
    const deep = try testFile(p, &tmp, "src/deep/x.txt", "deep\n");
    defer p.gpa.free(deep);
    for ([_][2][]const u8{ .{ "sub/name.txt", "needle one\n" }, .{ "other/name.txt", "needle two\n" } }) |f| p.gpa.free(try testFile(p, &tmp, f[0], f[1]));
    const root = std.Io.Dir.path.dirname(std.Io.Dir.path.dirname(std.Io.Dir.path.dirname(deep).?).?).?;
    _ = try p.setTestFile("held\n");
    const asker = p.view().active;
    Trail.keep(p.panes[asker].?);
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try p.gpa.dupe(u8, deep);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    // Find from src/deep: the root's files, by their paths from it.
    open(p, asker, .find, "", "", "");
    var pk = live(p).?;
    try std.testing.expectEqualStrings(root, pk.dir.slice());
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), count(p, pk));
    for ("sub/name") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, pk));
    try std.testing.expectEqualStrings("sub/name.txt", (try rowAt(p, pk, a, 0)).text);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Grep: the whole tree, then `sub needle` in sub/ alone, its row's
    // path from the root, landing on the file there.
    open(p, asker, .grep, "", "", "");
    pk = live(p).?;
    for ("needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    // (Its typing paused: the search starts.)
    p.clock.now_ns = p.stream.due_ns.?;
    settle(p);
    try std.testing.expectEqual(@as(usize, 2), count(p, pk));
    p.update(.{ .key = .{ .cp = Key.escape } });
    open(p, asker, .grep, "", "", "");
    pk = live(p).?;
    for ("sub needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    // (Its typing paused: the search starts.)
    p.clock.now_ns = p.stream.due_ns.?;
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), count(p, pk));
    const row = try rowAt(p, pk, a, 0);
    try std.testing.expect(std.mem.startsWith(u8, row.text, "sub/name.txt:1 needle one"));
    try std.testing.expectEqualStrings(try std.Io.Dir.path.join(a, &.{ root, "sub/name.txt" }), row.target.place.path);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // Outside a repo (`/`, the test text's directory, holds no .jj nor
    // .git): the pane's directory, as before.
    p.gpa.free(p.panes[asker].?.file.?.path);
    p.panes[asker].?.file.?.path = try p.gpa.dupe(u8, "/held.txt");
    open(p, asker, .find, "", "", "");
    try std.testing.expectEqualStrings("/", live(p).?.dir.slice());
    p.update(.{ .key = .{ .cp = Key.escape } });
}