summaryrefslogtreecommitdiff
path: root/src/Query.zig
blob: 11db85798d789c6e7e060f833164432e43945276 (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
//! The query pane: the one pane search is. A +Search attached under the
//! pane that asked (its owner, layout.zig "Attached panes"), born at a
//! fixed height, whose body's line 1 is the query, editable text, and
//! whose rows below are made live from a source, read-only while live.
//! Line 1's first word names the source: `/pat` the owner's text (smart-
//! case regex), `Find pat` the files under its directory, `Grep pat` the
//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the
//! owner's declarations), `All pat` (every open pane's text), and the
//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are
//! matched fuzzy (Names.zig), text by regex. Editing the word changes
//! the source.
//!
//! The rows look like a Callstack's: the hit line with the match tinted
//! under a gutter line number, under the declaration it is in (when the
//! owner's parse exists: never made here on the loop), under its file
//! (Grep) or under `@pN name (count)` (All). They are addresses, all text:
//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into
//! an open pane's text, that pane's places (Places.zig) show the set:
//! tints, rail ticks, the current one selected. A row pointing at a file
//! no pane shows is shown in the +Preview attached under this pane; Enter
//! promotes the preview to the file's pane where it stands.
//!
//! Nothing moves while you type: the pane never closes, resizes or
//! rewrites line 1 on its own; zero hits is a state (`0` in the tag).
//! Enter lands on the current hit and freezes the rows into ordinary text;
//! Esc while typing puts every view back and closes the pane (or brings a
//! reused pane's frozen rows back); Del closes it. One per owner, reused
//! (SearchPane reuse|new).
const Query = @This();

const std = @import("std");
const pardes = @import("pardes.zig");
const panes = @import("panes.zig");
const config = @import("config.zig");
const edit = @import("edit.zig");
const exec = @import("exec.zig");
const layout = @import("layout.zig");
const locations = @import("locations.zig");
const look = @import("look.zig");
const modal = @import("modal.zig");
const normal = @import("normal.zig");
const syntax = @import("syntax.zig");
const tagline = @import("tagline.zig");
const filesystem = @import("fs.zig");
const colors = @import("colors.zig");
const memory = @import("memory.zig");
const Names = @import("Names.zig");
const Places = @import("Places.zig");
const Stream = @import("Stream.zig");
const Surface = @import("surface.zig").Surface;
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const File = panes.File;
const Output = panes.Output;
const Key = pardes.Key;
const hit = pardes.hit;

pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics };

/// Line 1's words, each the source it names. `/` is vim's spelling, no
/// space after it; the others take one.
pub const words = [_]struct { word: []const u8, source: Source }{
    .{ .word = "Find", .source = .find },
    .{ .word = "Grep", .source = .grep },
    .{ .word = "Recent", .source = .recent },
    .{ .word = "Panes", .source = .panes },
    .{ .word = "Symbols", .source = .symbols },
    .{ .word = "All", .source = .all },
    .{ .word = "Refs", .source = .refs },
    .{ .word = "Def", .source = .defs },
    .{ .word = "Impl", .source = .impls },
    .{ .word = "Diagnostics", .source = .diagnostics },
};

/// What a line 1 asks: its source and what follows its word. Null when it
/// starts with no word this knows (the user rewrote it): the rows say so.
pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } {
    if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] };
    for (words) |w| {
        if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' '))
            return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") };
    }
    return null;
}

/// The word line 1 starts with for `source`, as typed after it.
pub fn wordOf(source: Source) []const u8 {
    if (source == .text) return "/";
    for (words) |w| if (w.source == source) return w.word;
    unreachable;
}

/// A source whose rows can point at files no pane shows: its group is
/// made with a +Preview from the start, so nothing moves later.
fn previews(source: Source) bool {
    return switch (source) {
        .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true,
        .text, .panes, .symbols, .all => false,
    };
}

/// The most rows of hits a frozen list keeps: the rest are counted, and
/// said in a row.
pub const max_rows = 2000;
/// While typed, the rows are a window of this many around the current
/// place: the pane shows a few, and a row is two allocations a refill.
pub const live_rows = 100;

/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit,
/// a header (a declaration, a file, a pane) or a note. Where a row points
/// is in its locations.Row (path, at); a hit in an open pane's text also
/// knows its places there, `hit` and the `n` of them on its line.
pub const Item = struct {
    kind: enum { hit, header, note },
    /// The pane whose text it is in (by serial), 0 when it is a file's.
    serial: u32 = 0,
    hit: usize = 0,
    n: usize = 0,
    /// A Panes row's pane, a Symbols row's line: Names.Cand.ref.
    ref: u32 = 0,
};

/// A line a Grep found: its path and code in `found_bytes`.
pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 };

/// The pane it answers for, by serial.
owner: u32,
/// Line 1 as the rows were last made for (gpa).
asked: []u8 = &.{},
source: Source = .text,
/// Enter answered it: its rows are ordinary text from here, nothing remade.
frozen: bool = false,
items: std.ArrayList(Item) = .empty,
/// The current item, which Enter lands on and the places show.
current: ?usize = null,
/// The tag's `k/N`: how many places or names the rows are of, and where
/// the current one is among them (1-based; 0, none); `more` while counting.
total: usize = 0,
k: usize = 0,
more: bool = false,
/// What the rows were made of: the places' or names' generation and the
/// owner's text, so that a frame with nothing new makes nothing.
made_gen: u64 = std.math.maxInt(u64),
made_rev: u32 = 0,
/// The owner's revision seen last tick: rows follow an edit of the owner
/// once it has stood a frame (the rows refresh on idle frames).
seen_rev: u32 = 0,
/// The body cursor's row as last seen: j or k onto a row makes it current
/// (a caret B1 put there is only a caret).
seen_row: i32 = 0,
/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits.
window: struct { lo: usize = 0, hi: usize = 0 } = .{},
/// Ticks the rows waited while the places are still being found: they are
/// made every third, the frame's time going to the finding.
waited: u8 = 0,
names: Names = .{},
/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`), and
/// the current one's index among them.
found: std.ArrayList(Found) = .empty,
grep_at: usize = 0,
found_bytes: std.ArrayList(u8) = .empty,
grep_gen: u32 = 0,
/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave
/// them (`path:line:col text`, gpa), filtered by what follows the word.
lsp_rows: []u8 = &.{},
/// The +Preview under this pane, by serial; 0, none.
preview: u32 = 0,
/// Its disk search waits at its cap: the tag says More.
capped: bool = false,
/// A reused pane's frozen rows when a new query began in it: Esc brings
/// them back.
saved: ?Saved = null,

pub const Saved = struct {
    content: []u8,
    rows: []locations.Row,
    asked: []u8,
    source: Source,
    items: []Item,
    current: ?usize,
    total: usize,
    k: usize,
};

pub fn deinit(q: *Query, gpa: std.mem.Allocator) void {
    gpa.free(q.asked);
    q.items.deinit(gpa);
    q.names.deinit(gpa);
    q.found.deinit(gpa);
    q.found_bytes.deinit(gpa);
    gpa.free(q.lsp_rows);
    if (q.saved) |s| freeSaved(gpa, s);
    q.* = undefined;
}

fn freeSaved(gpa: std.mem.Allocator, s: Saved) void {
    gpa.free(s.content);
    locations.freeRows(gpa, s.rows);
    gpa.free(s.asked);
    gpa.free(s.items);
}

/// The query pane `pane` is, if it is one.
pub fn of(pane: *Pane) ?*Query {
    return pane.query;
}

/// The owner's query pane (attached to it, or left where it was by
/// SearchPane new): the one a later search from it reuses.
pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize {
    var found: ?usize = null;
    for (p.panes, 0..) |slot, i| {
        const pane = slot orelse continue;
        const q = pane.query orelse continue;
        if (q.owner != owner_serial) continue;
        // the attached one first: an unattached one is a kept result
        if (pane.attached_to == owner_serial) return i;
        found = found orelse i;
    }
    return found;
}

fn lineOne(content: []const u8) []const u8 {
    return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len];
}

// ---- opening ----

/// A search from pane `from`: its owner's query pane, made under the owner
/// (with a +Preview when `source` can need one) or reused, line 1 the
/// source's word and `arg`. With `focus` the keyboard goes to line 1's end
/// in insert mode, as to a prompt; without (`*`), it stays where it is.
pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void {
    const asker = p.panes[from] orelse return;
    // Asked from a query pane (`/` in it, its own SPC f g): its own line 1;
    // from a +Preview, its query pane's.
    var owner_id = from;
    if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| {
        owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from;
    }
    const owner = p.panes[owner_id] orelse return;
    if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) {
        // Back to typing the query it has.
        if (focus) toLineOne(p, from);
        return;
    }
    const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return;
    var id: usize = undefined;
    const existing = ofOwner(p, owner.serial);
    if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) {
        id = existing.?;
        const rp = p.panes[id].?;
        const q = rp.query.?;
        // Its frozen rows, kept for an Esc to bring back.
        if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null;
        q.frozen = false;
        const f = &rp.file.?;
        const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return;
        File.setContent(p, f, new);
        q.reset(p);
        if (p.finder.column(p)) |fc| if (layout.findPane(p, id)) |at| if (at.col == fc) p.finder.raise(p, id);
        if (rp.collapsed) layout.toggleCollapse(p, id);
        // A source that previews gets its +Preview now, at the key that
        // asked, not under the typing later.
        if (previews(source) and previewOf(p, id) == null)
            _ = makePreview(p, id, @max(pardes.BOX_H, rp.tag_rows) + p.settings.search_rows, layout.groupRoot(p, id));
    } else {
        if (existing) |old| {
            // SearchPane new: the last one stays where it is, a result of
            // its own; its places are the new one's to feed.
            p.panes[old].?.attached_to = null;
        }
        id = create(p, owner_id, line, source) orelse return;
    }
    // Every view as the search found it, for Esc to put back.
    owner.places.remember(p, owner);
    // Before the first key: a names source lists every candidate at once.
    produce(p, id, false, false);
    // What a 9P exec reads back: the pane it filled (ninep/ctl.zig).
    p.fs.refilled = p.panes[id].?.serial;
    if (focus) toLineOne(p, id) else p.active = from;
}

/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the
/// SearchRows setting), its +Preview under it when `source` can need one.
fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize {
    const owner = p.panes[owner_id] orelse return null;
    const free = p.freeSlot() orelse {
        p.reportError(owner_id, "search", error.NoPaneSlots);
        return null;
    };
    const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner);
    const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null;
    const np = Output.open(p, free, dir, .search, "", content) catch |err| {
        p.gpa.free(content);
        p.reportError(owner_id, "search", err);
        return null;
    };
    const q = p.gpa.create(Query) catch {
        p.reportError(owner_id, "search", error.OutOfMemory);
        return null;
    };
    q.* = .{ .owner = owner.serial };
    np.query = q;
    const body: u16 = 1 + p.settings.search_rows;
    const tag = @max(pardes.BOX_H, np.tag_rows);
    const with_preview = previews(source);
    // The preview, made right after, takes its own rows from the owner:
    // when the owner has not the rows for both, they share what it has, so
    // the group is whole from the first key and nothing moves later.
    var want: u16 = tag + body;
    var preview_rows: u16 = tag + p.settings.search_rows;
    if (with_preview) {
        layout.compute(p);
        const spare = p.rects[owner_id].h -| layout.minRows(p, owner_id);
        if (spare < want + preview_rows) {
            const both = want + preview_rows;
            want = @max(tag + 2, @as(u16, @intCast(@as(u32, spare) * want / both)));
            preview_rows = spare -| want;
        }
    }
    if (p.settings.search_place == .column) {
        // On top of the finder column at the right edge (Finder.zig), the
        // older query panes folded under it; its preview under it there.
        if (!p.finder.place(p, free) and !layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc);
        if (with_preview) _ = makePreview(p, free, p.rects[free].h / 2, free);
        return free;
    } else if (!layout.attach(p, owner_id, free, want)) {
        // An owner too short to give a query pane its rows: placed as any
        // new pane is, the one place a search moves another pane.
        exec.placeNew(p, owner_id, owner_id, free, .doc);
    }
    if (with_preview) _ = makePreview(p, free, preview_rows, owner_id);
    return free;
}

/// The keyboard to the end of line 1 of query pane `id`, in insert mode.
pub fn toLineOne(p: *Pardes, id: usize) void {
    const rp = p.panes[id] orelse return;
    tagline.exitHeader(p);
    p.active = id;
    if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col);
    rp.focus = .body;
    const t = &rp.body;
    if (t.mode == .insert) edit.exitInsert(p, t);
    t.cur_row = 0;
    t.cur_col = @intCast(lineOne(rp.file.?.content).len);
    t.vsel.active = false;
    t.nsel = 0;
    t.cur_pinned = true;
    rp.query.?.seen_row = 0;
    edit.enterInsert(p, t, .line_end, 1);
    showCurrent(rp);
}

/// The rows' state for a new question: nothing found yet.
fn reset(q: *Query, p: *Pardes) void {
    q.items.clearRetainingCapacity();
    q.current = null;
    q.total = 0;
    q.k = 0;
    q.more = false;
    q.made_gen = std.math.maxInt(u64);
    p.gpa.free(q.asked);
    q.asked = &.{};
}

fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved {
    const f = &rp.file.?;
    const content = try p.gpa.dupe(u8, f.content);
    errdefer p.gpa.free(content);
    const rows = try p.gpa.alloc(locations.Row, f.location_rows.len);
    var made: usize = 0;
    errdefer {
        for (rows[0..made]) |r| {
            p.gpa.free(r.path);
            p.gpa.free(r.colors);
        }
        p.gpa.free(rows);
    }
    for (f.location_rows, 0..) |r, i| {
        rows[i] = r;
        rows[i].path = try p.gpa.dupe(u8, r.path);
        rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| {
            p.gpa.free(rows[i].path);
            return err;
        };
        made += 1;
    }
    const asked = try p.gpa.dupe(u8, q.asked);
    errdefer p.gpa.free(asked);
    return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k };
}

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

/// After every step: each live query pane whose line 1 changed, or whose
/// source has something new, has its rows made again. A walk takes a slice
/// on a tick. Nothing here is synchronous with an edit of the owner: its
/// places shift (Places.shift) and the rows follow once it stands a frame.
pub fn produceAll(p: *Pardes, tick: bool, keyed: bool) void {
    for (p.panes, 0..) |slot, id| {
        const pane = slot orelse continue;
        if (pane.query == null) continue;
        produce(p, id, tick, keyed);
    }
}

/// The frames a query pane still owes (a walk, scoring): nextWake's.
pub fn busy(p: *const Pardes) bool {
    for (p.panes) |slot| {
        const pane = slot orelse continue;
        const q = pane.query orelse continue;
        if (q.frozen) continue;
        if (q.names.busy() or p.stream.busyFor(pane.serial) or q.made_rev != q.seen_rev) return true;
    }
    return false;
}

/// `keyed`: this step was a key, so a caret moved onto a row (j, k) makes
/// it current; a caret B1 placed is only a caret.
fn produce(p: *Pardes, id: usize, tick: bool, keyed: bool) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    const f = if (rp.file) |*file| file else return;
    const line = lineOne(f.content);
    const changed = !std.mem.eql(u8, line, q.asked);
    if (q.frozen and !changed) return;
    if (q.frozen) {
        // Line 1 of a frozen pane edited: it is a live query again.
        if (q.saved) |s| freeSaved(p.gpa, s);
        q.saved = null;
        q.frozen = false;
    }
    const owner_id = p.paneBySerial(q.owner);
    const asked = parse(line);
    if (changed) {
        const was = q.source;
        const new_asked = p.gpa.dupe(u8, line) catch return;
        p.gpa.free(q.asked);
        q.asked = new_asked;
        q.made_gen = std.math.maxInt(u64);
        if (asked) |a| {
            if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id);
            q.source = a.source;
        }
        // The places this fed are another question's now.
        if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked);
    }
    const a = asked orelse return noteRows(p, id, "  line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n");
    // A row stepped onto (j, k): current, and shown. One B1 put the caret
    // on is not: B1 places the caret and selects, nothing else, as on any
    // text; no other pane moves.
    if (rp.body.cur_row != q.seen_row) {
        q.seen_row = rp.body.cur_row;
        if (keyed and rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) {
            const i: usize = @intCast(rp.body.cur_row - 1);
            if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true);
        }
    }
    switch (a.source) {
        .text => {
            const oid = owner_id orelse return noteRows(p, id, "  the pane this searched is gone: Del, or / in another\n");
            const owner = p.panes[oid].?;
            const of_ = owner.file orelse return noteRows(p, id, "  a terminal's text is not searched here yet: / in a file\n");
            const set = &owner.places;
            if (changed) {
                if (a.pat.len == 0) {
                    if (set.from == rp.serial) set.clear(p.gpa);
                    set.restore(p, owner);
                } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id);
            }
            // The owner edited: its places shifted at once; the rows follow
            // once its text has stood a frame.
            if (!changed and of_.revision != q.made_rev) {
                if (!tick or of_.revision != q.seen_rev) {
                    q.seen_rev = of_.revision;
                    return;
                }
            }
            q.seen_rev = of_.revision;
            const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision;
            if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id);
            if (a.pat.len > 0 and set.from != rp.serial) return;
            if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) {
                q.waited += 1;
                return showPlacesCurrent(p, id);
            }
            q.waited = 0;
            q.made_gen = gen;
            q.made_rev = of_.revision;
            makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err);
        },
        .all => {
            if (changed) for (p.panes) |slot| {
                const tp = slot orelse continue;
                if (!searchable(tp)) continue;
                if (a.pat.len == 0) {
                    if (tp.places.from == rp.serial) tp.places.clear(p.gpa);
                    continue;
                }
                tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false);
            };
            var gen: u64 = 0;
            for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) {
                gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20);
            };
            if (gen == q.made_gen and !changed) return;
            if (!changed and !tick) return;
            q.made_gen = gen;
            makeAllRows(p, id) catch |err| p.reportError(id, "search", err);
        },
        .find, .recent, .panes, .symbols => {
            if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa);
            if (q.names.gen == q.made_gen and !changed) return;
            q.made_gen = q.names.gen;
            makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err);
        },
        .grep => {
            const dir = std.fs.path.dirname(f.path) orelse "/";
            if (changed) {
                q.found.clearRetainingCapacity();
                q.found_bytes.clearRetainingCapacity();
                q.grep_gen +%= 1;
                q.grep_at = 0;
                q.current = null;
                // On the disk engine's worker, once the typing pauses.
                // A script's (a 9P write): run to its end before it answers.
                if (a.pat.len > 0) {
                    Stream.query(p, rp.serial, .grep, a.pat, dir, if (p.fs.serving) .now else .typed);
                    if (p.fs.serving) Stream.step(p);
                } else if (p.stream.target == rp.serial) {
                    _ = p.stream.stop();
                }
                feedGrepPlaces(p, q, rp.serial, a.pat);
            }
            const searching = p.stream.target == rp.serial and p.stream.state != .done and p.stream.state != .stopped and p.stream.state != .failed and p.stream.state != .idle;
            const gen: u64 = (@as(u64, q.grep_gen) << 32) | (q.found.items.len << 1) | @intFromBool(searching);
            if (gen == q.made_gen and !changed) return;
            q.made_gen = gen;
            makeGrepRows(p, id, false) catch |err| p.reportError(id, "search", err);
        },
        .refs, .defs, .impls, .diagnostics => {
            if (changed and q.lsp_rows.len == 0) {
                // Typed, not answered: asked of the language server at the
                // owner's cursor; its answer fills these rows (fillList).
                // An answer opening the pane is no typing.
                if (p.active != id) return;
                if (owner_id) |oid| p.lspRequest(oid, switch (a.source) {
                    .refs => .references,
                    .defs => .definition,
                    .impls => .implementation,
                    else => .diagnostics,
                }, "");
                return noteRows(p, id, "  asked of the language server...\n");
            }
            if (!changed) return;
            makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err);
        },
    }
}

/// Whether pane `tp`'s text is one 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;
}

/// A source begun: its candidates gathered (names), its walk started.
fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void {
    const rp = p.panes[id].?;
    q.names.reset();
    q.found.clearRetainingCapacity();
    q.found_bytes.clearRetainingCapacity();
    const dir = std.fs.path.dirname(rp.file.?.path) orelse "/";
    const gpa = p.gpa;
    switch (source) {
        // The files under the directory, listed once on the disk engine's
        // worker (rg --files, else the walk); each keystroke scores them.
        .find => {
            Stream.query(p, rp.serial, .files, "", dir, .now);
            if (p.fs.serving) Stream.step(p);
        },
        .recent => {
            // Every window's files: what the others wrote since, read.
            p.store.refresh(p);
            var out: std.Io.Writer.Allocating = .init(gpa);
            defer out.deinit();
            Output.recentText(p, &out.writer, true) catch {};
            var lines = std.mem.splitScalar(u8, out.written(), '\n');
            while (lines.next()) |ln| {
                if (ln.len == 0) continue;
                const rel = Names.relative(ln, dir);
                const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len;
                q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break;
            }
        },
        .panes => {
            for (p.panes) |slot| {
                const other = slot orelse continue;
                if (other == rp or other.query != null) continue;
                var buf: [4096 + 32]u8 = undefined;
                const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice();
                const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue;
                const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1;
                const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len];
                q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break;
            }
            // Then the panes this session closed, the latest first, each
            // `(closed)` and dimmer (makeNameRows): Enter brings one back
            // where it was. Its name alone is matched, not the word.
            var i = p.store.closed.items.len;
            while (i > 0) : (i -= 1) {
                const c = p.store.closed.items[i - 1];
                var buf: [4096 + 48]u8 = undefined;
                const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue;
                const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1;
                const key_len = row.len - closed_word.len - key_at;
                q.names.add(gpa, row, key_at, key_len, Names.baseOf(row[key_at..][0..key_len]), c.serial) catch break;
            }
        },
        .symbols => {
            const oid = owner_id orelse return;
            const owner = p.panes[oid].?;
            const f = if (owner.file) |*file| file else return;
            const decls = ownerDecls(p, f, false) orelse {
                // Parsed on the worker; listed when it is done (declsArrived).
                Stream.parseFor(p, oid);
                return;
            };
            for (decls) |d| {
                const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)];
                const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r");
                var buf: [256 + 16]u8 = undefined;
                const row = std.fmt.bufPrint(&buf, "{d: >6}  {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue;
                q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break;
            }
        },
        else => {},
    }
}

/// What a Panes row of a closed pane ends with.
const closed_word = " (closed)";

/// The owner's declarations, from a parse that already exists: its sticky
/// headers' (TreeContext) at this revision, or the locations cache's. None
/// is made here, on the loop, unless `small` and the text is small: a
/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build.
/// ponytail: no grouping for a big file until the disk engine's worker
/// parses it (phase 4).
fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration {
    if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations;
    const cache = &p.locations_cache;
    for (cache.entries[0..cache.len]) |entry| {
        if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations;
    }
    if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null;
    var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null;
    if (got.owned) {
        got.deinit(p.tree_sitter_gpa);
        return null;
    }
    return got.analysis.declarations;
}

/// A text this small is parsed on the loop for its declarations when a
/// Symbols query asks (about 40 ms in a Debug build).
const small_parse_bytes = 64 << 10;

/// The rows as `note` says, and nothing else: no hits.
fn noteRows(p: *Pardes, id: usize, note: []const u8) void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    q.items.clearRetainingCapacity();
    q.items.append(p.gpa, .{ .kind = .note }) catch return;
    q.current = null;
    q.total = 0;
    q.k = 0;
    q.more = false;
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return;
    setRows(p, rp, &out, &rows);
}

/// One row: its text and its metadata, the path copied.
fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void {
    try out.appendSlice(p.gpa, text);
    try out.append(p.gpa, '\n');
    var m = meta;
    m.path = try p.gpa.dupe(u8, meta.path);
    errdefer p.gpa.free(m.path);
    // Coloured whole (zeros where nothing coloured it): the pane's syntax
    // pass then parses no fragment of it, per refill.
    const code = text[@min(meta.code_start, text.len)..];
    m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: {
        const c = try p.gpa.alloc(u8, code.len);
        @memset(c, 0);
        @memcpy(c[0..meta.colors.len], meta.colors);
        break :blk c;
    };
    rows.append(p.gpa, m) catch |err| {
        p.gpa.free(m.path);
        p.gpa.free(m.colors);
        return err;
    };
}

/// The rows made into the pane: line 1 as it is (the user's), then `out`,
/// with `rows` their metadata. The keyboard's place is left where it was.
fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void {
    defer locations.freeRowList(p.gpa, rows);
    const f = &rp.file.?;
    const line = lineOne(f.content);
    const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return;
    const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch {
        p.gpa.free(content);
        return;
    };
    meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 };
    @memcpy(meta[1..], rows.items);
    rows.clearRetainingCapacity();
    const kept_row = rp.body.cur_row;
    const kept_col = rp.body.cur_col;
    if (std.mem.eql(u8, content, f.content)) {
        // Same text: the metadata alone, no undo step, no syntax pass.
        p.gpa.free(content);
        if (locations.equalRows(f.location_rows, meta)) {
            locations.freeRows(p.gpa, meta);
        } else {
            locations.freeRows(p.gpa, f.location_rows);
            f.location_rows = meta;
            f.syntax_dirty = true;
        }
    } else {
        File.setContent(p, f, content);
        locations.freeRows(p.gpa, f.location_rows);
        f.location_rows = meta;
        f.saved_revision = f.revision;
    }
    gpa_free_pager(p, f);
    // The cursor stays where it was typing; on a row that went, the last.
    const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1);
    rp.body.cur_row = @min(kept_row, last);
    rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0;
    if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len);
    rp.query.?.seen_row = rp.body.cur_row;
}

fn gpa_free_pager(p: *Pardes, f: *File.State) void {
    if (f.pager_spans.len == 0) return;
    p.gpa.free(f.pager_spans);
    f.pager_spans = &.{};
}

/// The gutter a file of `nlines` lines numbers its rows in: two spaces,
/// the number right-aligned, two spaces.
fn gutterWidth(nlines: usize) usize {
    var digits: usize = 1;
    var n = nlines;
    while (n >= 10) : (n /= 10) digits += 1;
    return 2 + @max(3, digits) + 2;
}

fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void {
    var lead: usize = 0;
    while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1;
    const code = std.mem.trimEnd(u8, whole[lead..], "\r");
    var buf: [4096 + 32]u8 = undefined;
    var num: [24]u8 = undefined;
    const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch "";
    const pad = width -| 2 -| number.len;
    if (pad + number.len + 2 + code.len > buf.len) return;
    @memset(buf[0..pad], ' ');
    @memcpy(buf[pad..][0..number.len], number);
    @memcpy(buf[pad + number.len ..][0..2], "  ");
    @memcpy(buf[pad + number.len + 2 ..][0..code.len], code);
    const text = buf[0 .. pad + number.len + 2 + code.len];
    const gutter = pad + number.len + 2;
    try writeRow(p, out, rows, text, .{
        .kind = .match,
        .source_column = lead,
        .path = @constCast(path),
        .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) },
        .location_end = gutter,
        .code_start = gutter,
        .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}),
    });
}

/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a
/// text that is no file (a list, a scratch).
fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 {
    const f = tp.file orelse return "";
    if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path;
    return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch "";
}

/// Rows from pane `tp`'s places: one a line with any (two on a line are
/// one row: everywhere's bug), the declaration they are in over them when
/// its parse exists, from place `from` on, `budget` rows at most. The
/// place it stopped before.
fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize {
    const f = &tp.file.?;
    const set = &tp.places;
    const hits = set.hits.items;
    const index = try File.lineIndex(p.gpa, f);
    const width = gutterWidth(index.len);
    const path = addressOf(p.scratch.allocator(), tp);
    const decls = ownerDecls(p, f, false) orelse &.{};
    var decl_now: ?usize = null;
    var i: usize = @min(from, hits.len);
    // the line of the first, found in the index
    var line: usize = if (i < hits.len) blk: {
        var lo: usize = 0;
        var hi = index.len;
        while (lo < hi) {
            const mid = lo + (hi - lo) / 2;
            if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid;
        }
        break :blk lo -| 1;
    } else 0;
    // a window begins at a line's first place
    while (i > 0 and hits[i - 1].start >= index[line]) i -= 1;
    while (i < hits.len) {
        while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1;
        // the places on this line
        var n: usize = 1;
        const ls = index[line];
        const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len;
        while (i + n < hits.len and hits[i + n].start <= le) n += 1;
        if (budget.* == 0) {
            q.more = true;
            break;
        }
        budget.* -= 1;
        // the innermost declaration around it, its first line once
        var inner: ?usize = null;
        for (decls, 0..) |d, di| {
            if (d.start_line > line) break;
            if (d.end_line < line) continue;
            inner = di;
        }
        if (inner != decl_now) {
            decl_now = inner;
            if (inner) |di| if (decls[di].start_line != line) {
                const head_ls = index[decls[di].start_line];
                const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len;
                const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r");
                var hb: [600]u8 = undefined;
                const text = std.fmt.bufPrint(&hb, "  {s}", .{head[0..@min(head.len, 560)]}) catch "";
                try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial });
                try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 });
            };
        }
        const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{};
        try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n });
        try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade);
        i += n;
    }
    return i;
}

/// The rows of a `/`: while typed, a window of `live_rows` around the
/// current place; `full` (frozen), the whole list up to `max_rows`.
fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    const owner = p.panes[oid].?;
    const set = &owner.places;
    q.items.clearRetainingCapacity();
    q.more = false;
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    var budget: usize = if (full) max_rows else live_rows;
    // Grouped once a parse of the text exists: asked of the worker now.
    if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid);
    const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0);
    // While typed, a window of rows from just before the current place, so
    // it sits under line 1.
    const from = if (full) 0 else at -| 2;
    q.window = .{ .lo = from, .hi = from };
    if (set.started and set.from == rp.serial) {
        if (from > 0) {
            var hb: [64]u8 = undefined;
            try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, "  ... {d} places before these", .{from}) catch "  ...");
        }
        q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget);
        q.window.lo = @min(from, q.window.hi);
    }
    if (q.more) try noteRow(p, q, &out, &rows, "  ... and more: the count says how many");
    setRows(p, rp, &out, &rows);
    showPlacesCurrent(p, id);
}

fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void {
    try q.items.append(p.gpa, .{ .kind = .note });
    try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 });
}

/// The current row from the places of the pane its rows are in, the count
/// with them: for `/`, the owner's.
fn showPlacesCurrent(p: *Pardes, id: usize) void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    const owner = p.panes[p.paneBySerial(q.owner) orelse return].?;
    const set = &owner.places;
    q.total = if (set.from == rp.serial) set.hits.items.len else 0;
    // still counting: the places not all found yet (the rows' own cut is
    // said in a row of theirs)
    q.more = set.from == rp.serial and !set.complete();
    q.k = if (set.current) |c| c + 1 else 0;
    if (set.from != rp.serial) q.k = 0;
    q.current = null;
    // By line, not by the rows' place indices: the rows may lag the places
    // a tick while they are still being found.
    if (set.current) |c| if (c < set.hits.items.len) {
        const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1;
        const rows = rp.file.?.location_rows;
        for (q.items.items, 0..) |it, i| {
            if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue;
            if (rows[i + 1].at.line == at) {
                q.current = i;
                break;
            }
        }
    };
    // Stepped out of the window the live rows are: made again around it.
    if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64);
    showCurrent(rp);
}

/// Every open pane's rows for All, grouped under `@pN name (count)` in
/// the order of the panes' serials (everywhere's other bug: it went by
/// column).
fn makeAllRows(p: *Pardes, id: usize) !void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    q.items.clearRetainingCapacity();
    q.more = false;
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    var order: [pardes.MAX_PANES]usize = undefined;
    var n: usize = 0;
    for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) {
        order[n] = i;
        n += 1;
    };
    std.mem.sort(usize, order[0..n], p, struct {
        fn lt(pp: *Pardes, a: usize, b: usize) bool {
            return pp.panes[a].?.serial < pp.panes[b].?.serial;
        }
    }.lt);
    var budget: usize = max_rows;
    q.total = 0;
    for (order[0..n]) |tid| {
        const tp = p.panes[tid].?;
        const set = &tp.places;
        if (!set.shows(tp) or set.hits.items.len == 0) {
            q.more = q.more or !set.complete();
            continue;
        }
        q.total += set.hits.items.len;
        q.more = q.more or !set.complete();
        var hb: [600]u8 = undefined;
        const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else "";
        const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch "";
        try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial });
        try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 });
        _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget);
    }
    if (budget == 0) try noteRow(p, q, &out, &rows, "  ... and more: the count says how many");
    setRows(p, rp, &out, &rows);
    // The current one: the first hit row, until a step moves it.
    if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q);
    countCurrent(q);
    showCurrent(rp);
}

fn firstHit(q: *const Query) ?usize {
    for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i;
    return null;
}

/// `k` from the current row: the hits on the rows before it, and its own.
fn countCurrent(q: *Query) void {
    if (q.source == .grep) return countGrepCurrent(q);
    q.k = 0;
    const c = q.current orelse return;
    for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0;
    q.k += 1;
}

/// The names the query matches, best first, `Names.max_rows` of them: each
/// a row as its source has it, the matched bytes tinted.
fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void {
    _ = pat;
    const rp = p.panes[id].?;
    const q = rp.query.?;
    const dir = std.fs.path.dirname(rp.file.?.path) orelse "/";
    const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null;
    _ = was_current;
    q.items.clearRetainingCapacity();
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    var spans: std.ArrayList(pardes.pager.Span) = .empty;
    errdefer spans.deinit(p.gpa);
    const chrome = p.bodyChrome();
    const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true };
    const shown = @min(q.names.hits.items.len, Names.max_rows);
    var marks: [Names.max_query * 4]u16 = undefined;
    const base = lineOne(rp.file.?.content).len + 1;
    for (0..shown) |i| {
        var nmarks: usize = 0;
        const row = q.names.row(i, &marks, &nmarks);
        const cand = q.names.cands.items[q.names.hits.items[i].cand];
        const at = base + out.items.len;
        // Where it points: a path (Find, Recent), a pane (Panes), a line
        // of the owner (Symbols).
        var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false };
        var pathbuf: [4096 + 32]u8 = undefined;
        switch (q.source) {
            .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row),
            .recent => {
                const t = look.parsePathLine(row);
                meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path);
                meta.at = t.at;
            },
            .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""),
            .symbols => {
                const owner = p.panes[p.paneBySerial(q.owner) orelse 0];
                meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else "");
                meta.at = .{ .line = cand.ref };
            },
            else => {},
        }
        try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref });
        try writeRow(p, &out, &rows, row, meta);
        // A closed pane's row is dimmer, the gutter's colour, between its
        // marks (spans are walked in order, never overlapping).
        const dim = q.source == .panes and p.paneBySerial(cand.ref) == null;
        const dimmed: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.lineno } };
        var gap: usize = 0;
        var k: usize = 0;
        while (k < nmarks) {
            var e = k + 1;
            while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1;
            if (dim and marks[k] > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + marks[k]), .style = dimmed });
            try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint });
            gap = marks[e - 1] + 1;
            k = e;
        }
        if (dim and row.len > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + row.len), .style = dimmed });
    }
    if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, "  ... and more: type more of the name");
    if (q.source == .find) try skippedRow(p, q, rp, &out, &rows);
    setRows(p, rp, &out, &rows);
    const f = &rp.file.?;
    f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{};
    q.total = q.names.hits.items.len;
    q.more = q.names.busy() or p.stream.busyFor(rp.serial);
    // The best is current until a step or a click moves it.
    q.current = if (shown > 0) 0 else null;
    countCurrent(q);
    showCurrent(rp);
    if (q.current == null) blankPreview(p, id) else showTarget(p, id);
}

/// A Grep keeps this many lines: the rest wait (the disk engine's `More`).
pub const grep_cap = 2000;

/// A Grep's rows: each file's name over its lines, while typed a window
/// of `live_rows` around the current one, `full` (frozen) every one sent.
fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    const dir = std.fs.path.dirname(rp.file.?.path) orelse "/";
    const at: usize = @min(q.grep_at, q.found.items.len -| 1);
    q.items.clearRetainingCapacity();
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    var last_path: []const u8 = "";
    var pathbuf: [4096 + 8]u8 = undefined;
    const lo = if (full) 0 else at -| 2;
    const hi = if (full) q.found.items.len else @min(q.found.items.len, lo + live_rows);
    if (lo > 0) {
        var hb: [64]u8 = undefined;
        try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, "  ... {d} lines before these", .{lo}) catch "  ...");
    }
    var current: ?usize = null;
    for (q.found.items[lo..hi], lo..) |fd, i| {
        const rel = q.found_bytes.items[fd.path..][0..fd.path_len];
        const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue;
        if (!std.mem.eql(u8, rel, last_path)) {
            last_path = rel;
            try q.items.append(p.gpa, .{ .kind = .header });
            try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 });
        }
        const code = q.found_bytes.items[fd.code..][0..fd.code_len];
        if (i == at) current = q.items.items.len;
        try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 });
        try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{});
    }
    if (hi < q.found.items.len) {
        var hb: [64]u8 = undefined;
        try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, "  ... {d} lines after these", .{q.found.items.len - hi}) catch "  ...");
    }
    if (p.stream.target == rp.serial and p.stream.state == .capped) try noteRow(p, q, &out, &rows, "  ... stopped at 2000 lines: More in the tag goes on");
    try skippedRow(p, q, rp, &out, &rows);
    setRows(p, rp, &out, &rows);
    q.total = q.found.items.len;
    q.more = p.stream.busyFor(rp.serial);
    q.current = current orelse firstHit(q);
    countGrepCurrent(q);
    showCurrent(rp);
    if (q.current == null) blankPreview(p, id);
}

/// What the disk walk passed over, said under the rows: a search that
/// found nothing where it could not look says so, never just nothing.
fn skippedRow(p: *Pardes, q: *Query, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) !void {
    const n = p.stream.skipped;
    if (p.stream.target != rp.serial or n == 0) return;
    var hb: [96]u8 = undefined;
    try noteRow(p, q, out, rows, std.fmt.bufPrint(&hb, "  {d} director{s} skipped: permission denied", .{ n, if (n == 1) "y" else "ies" }) catch "  directories skipped");
}

/// `k` for a Grep: the current row's line among all the lines sent.
fn countGrepCurrent(q: *Query) void {
    q.k = 0;
    const c = q.current orelse return;
    if (c < q.items.items.len and q.items.items[c].kind == .hit) q.k = q.items.items[c].hit + 1;
}

/// The disk engine's rows for query pane `q` (Stream.receive): a Grep's
/// lines (`path:line:col-end code`, relative to the pane's directory) kept
/// as found, a listing's names added to what Find scores.
pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void {
    var lines = std.mem.splitScalar(u8, rows, '\n');
    while (lines.next()) |ln| {
        if (ln.len == 0) continue;
        switch (kind) {
            .files => q.names.add(p.gpa, ln, 0, ln.len, Names.baseOf(ln), 0) catch return,
            .grep => {
                const t = look.parsePathLine(ln);
                if (t.at.line == 0 or t.path.len == 0) continue;
                const code = if (t.end < ln.len) ln[t.end + 1 ..] else "";
                const path_at: u32 = @intCast(q.found_bytes.items.len);
                q.found_bytes.appendSlice(p.gpa, t.path) catch return;
                const code_at: u32 = @intCast(q.found_bytes.items.len);
                q.found_bytes.appendSlice(p.gpa, code) catch return;
                q.found.append(p.gpa, .{
                    .path = path_at,
                    .path_len = @intCast(t.path.len),
                    .line = @intCast(t.at.line),
                    .col = @intCast(t.at.col -| 1),
                    .end = @intCast(if (t.at.end_col > 0) t.at.end_col else t.at.col),
                    .code = code_at,
                    .code_len = @intCast(code.len),
                }) catch return;
            },
        }
    }
    q.names.gen +%= 1;
}

/// A Grep's hits in each open file are that pane's places: its tints,
/// ticks and n/N.
fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void {
    _ = q;
    for (p.panes) |slot| {
        const tp = slot orelse continue;
        const f = tp.file orelse continue;
        if (f.output != null or tp.query != null) continue;
        tp.places.search(p, tp, .list, serial, pat, true, null, false);
    }
}

/// The language server's answer for an owner's Refs, Def, Impl or
/// Diagnostics, into its query pane (made or reused) with line 1 the word:
/// what follows the word filters the rows; the places in the owner's text
/// are its places. `rows` are `path:line:col text`, as the server's
/// answer is written (lsp_client).
pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void {
    const owner = p.panes[owner_id] orelse return;
    var id = ofOwner(p, owner.serial);
    if (id == null or p.panes[id.?].?.query.?.source != source) {
        open(p, owner_id, source, "", false);
        id = ofOwner(p, owner.serial);
    }
    const qid = id orelse return;
    const rp = p.panes[qid].?;
    const q = rp.query.?;
    const copy = p.gpa.dupe(u8, rows) catch return;
    p.gpa.free(q.lsp_rows);
    q.lsp_rows = copy;
    const line = lineOne(rp.file.?.content);
    const a = parse(line) orelse return;
    makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err);
    // Diagnostics are a jump (]d): the keyboard stays on the place in the
    // text. The others are a list answered, not a query typed: the keyboard
    // on the current row in normal mode (j, k, n, N step, Enter lands, Esc
    // goes back), line 1 left as text for whoever wants to edit it.
    if (source == .diagnostics) {
        p.active = owner_id;
        return;
    }
    tagline.exitHeader(p);
    p.active = qid;
    if (layout.findPane(p, qid)) |at| p.setActiveColumn(at.col);
    rp.focus = .body;
    const t = &rp.body;
    if (t.mode == .insert) edit.exitInsert(p, t);
    t.vsel.active = false;
    t.nsel = 0;
    caretTo(rp, q.current orelse 0);
    showTarget(p, qid);
}

fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    const dir = std.fs.path.dirname(rp.file.?.path) orelse "/";
    q.items.clearRetainingCapacity();
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(p.gpa);
    var rows: std.ArrayList(locations.Row) = .empty;
    const owner_id = p.paneBySerial(q.owner);
    const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else "";
    // Each open file's places in the list, its tints and n/N: the owner's
    // and any other pane's the rows land in.
    var feeds: [pardes.MAX_PANES]std.ArrayList(Places.Hit) = @splat(.empty);
    defer for (&feeds) |*f| f.deinit(p.gpa);
    // In order: by path, then place, as a list of places reads.
    var sorted: std.ArrayList([]const u8) = .empty;
    defer sorted.deinit(p.gpa);
    var split = std.mem.splitScalar(u8, q.lsp_rows, '\n');
    while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln);
    std.mem.sort([]const u8, sorted.items, {}, struct {
        fn lt(_: void, a: []const u8, b: []const u8) bool {
            const ta = look.parsePathLine(a);
            const tb = look.parsePathLine(b);
            const order = std.mem.order(u8, ta.path, tb.path);
            if (order != .eq) return order == .lt;
            if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line;
            return ta.at.col < tb.at.col;
        }
    }.lt);
    var last_path: []const u8 = "";
    var pathbuf: [4096 + 8]u8 = undefined;
    var n: usize = 0;
    for (sorted.items) |ln| {
        if (ln.len == 0) continue;
        if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue;
        const t = look.parsePathLine(ln);
        if (t.at.line == 0) continue;
        const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue;
        if (!std.mem.eql(u8, t.path, last_path)) {
            last_path = t.path;
            try q.items.append(p.gpa, .{ .kind = .header });
            try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 });
        }
        const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:");
        const col0 = t.at.col -| 1;
        // The row's text: the line as an open pane has it, when one shows
        // the file, else as the server said it.
        var code: []const u8 = rest;
        var col = @min(col0, rest.len);
        var end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1, rest.len);
        var shown_in: u32 = 0;
        for (p.panes, 0..) |slot, i| {
            const tp = slot orelse continue;
            if (!searchable(tp)) continue;
            const tf = &tp.file.?;
            if (tf.output != null or !std.mem.eql(u8, tf.path, path) or t.at.line > File.nlines(p.gpa, tf)) continue;
            const ls = File.lineStart(p.gpa, tf, t.at.line - 1);
            const nx = File.lineStart(p.gpa, tf, t.at.line);
            const le = if (nx > ls and tf.content[nx - 1] == '\n') nx - 1 else nx;
            code = tf.content[ls..le];
            col = @min(col0, code.len);
            end = @min(@max(end, col + 1), code.len);
            feeds[i].append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {};
            shown_in = tp.serial;
            break;
        }
        try q.items.append(p.gpa, .{ .kind = .hit, .n = 1, .serial = shown_in });
        try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{});
        n += 1;
    }
    if (n == 0) try noteRow(p, q, &out, &rows, "  nothing");
    setRows(p, rp, &out, &rows);
    q.total = n;
    q.more = false;
    q.current = firstHit(q);
    for (p.panes, 0..) |slot, i| if (slot) |tp| {
        if (feeds[i].items.len > 0) tp.places.feed(p, tp, rp.serial, feeds[i].items, null) else if (tp.places.from == rp.serial) tp.places.clear(p.gpa);
    };
    if (owner_id) |oid| {
        const owner = p.panes[oid].?;
        // Current: the first place after where it was asked (the answer
        // may come after the cursor moved), shown in the owner.
        const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner);
        const hits = owner.places.hits.items;
        var next: ?usize = null;
        for (hits, 0..) |h, i| if (h.start > asked_at) {
            next = i;
            break;
        };
        if (next == null and hits.len > 0) next = 0;
        if (next) |hi| {
            owner.places.goTo(owner, hi, false);
            for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) {
                const meta = rp.file.?.location_rows[i + 1];
                if (!std.mem.eql(u8, meta.path, owner_path)) continue;
                const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1);
                if (ls + meta.at.col -| 1 == hits[hi].start) {
                    q.current = i;
                    break;
                }
            };
        }
    }
    countCurrent(q);
    showCurrent(rp);
}

/// The places query `serial` fed in panes other than the owner, cleared
/// (a new source or pattern makes its own); the owner's too when the new
/// line is no `/`.
fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void {
    _ = q;
    _ = asked;
    for (p.panes, 0..) |slot, i| {
        const tp = slot orelse continue;
        if (tp.places.from != serial) continue;
        if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp);
        tp.places.clear(p.gpa);
    }
}

// ---- the current row ----

/// The current row scrolled into view while the keyboard is on line 1 or
/// elsewhere, line 1 kept when it can be. Its mark is `paint`'s, drawn
/// from `current`: no selection, so no click, sweep or chord clears it and
/// no B2 or B3 borrows it.
fn showCurrent(rp: *Pane) void {
    const q = rp.query orelse return;
    if (rp.body.cur_row != 0 and rp.focus == .body) return;
    const c = q.current orelse return;
    const r: i32 = @intCast(c + 1);
    // Typed into, line 1 stays in view whatever the current row: what you
    // type is never scrolled away (the live rows start just before the
    // current one, so it sits under line 1). Frozen, the row is scrolled to.
    if (!q.frozen) {
        if (rp.scroll() != 0) rp.scrollBy(-rp.scroll());
        return;
    }
    const off = rp.scroll();
    const shown = off + @as(i32, rp.rows) - 1;
    if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off);
}

/// The caret on item `i`'s row, the row in view.
fn caretTo(rp: *Pane, i: usize) void {
    const r: i32 = @intCast(i + 1);
    rp.body.cur_row = r;
    rp.body.cur_col = 0;
    rp.body.cur_pinned = true;
    rp.query.?.seen_row = r;
    const off = rp.scroll();
    if (r >= off + @as(i32, rp.rows)) rp.scrollBy(r - off - @as(i32, rp.rows) + 1) else if (r < off) rp.scrollBy(r - off);
}

/// The line (0-based) of byte `at` of `f`'s text.
fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize {
    const index = File.lineIndex(p.gpa, f) catch return 0;
    var lo: usize = 0;
    var hi = index.len;
    while (lo < hi) {
        const mid = lo + (hi - lo) / 2;
        if (index[mid] <= at) lo = mid + 1 else hi = mid;
    }
    return lo -| 1;
}

/// The first of pane `tp`'s places on line `line` (1-based), if any.
fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize {
    const f = &tp.file.?;
    if (line == 0 or line > File.nlines(p.gpa, f)) return null;
    const ls = File.lineStart(p.gpa, f, line - 1);
    const next = File.lineStart(p.gpa, f, line);
    const hits = tp.places.hits.items;
    const i = Places.firstFrom(hits, ls);
    if (i < hits.len and (hits[i].start < next or (next == ls))) return i;
    return null;
}

/// Item `i` current, and shown where it points (`show`).
fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void {
    const rp = p.panes[id].?;
    const q = rp.query.?;
    q.current = i;
    const it = q.items.items[i];
    if (q.source == .grep and it.kind == .hit) q.grep_at = it.hit;
    const rows = rp.file.?.location_rows;
    if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| {
        const tp = p.panes[tid].?;
        if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| {
            tp.places.current = hi;
            tp.places.gen +%= 1;
            if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q);
        } else countCurrent(q);
    } else countCurrent(q) else countCurrent(q);
    showCurrent(rp);
    if (show) showTarget(p, id);
}

/// Step the current row `delta` hits on, round the end silently: Ctrl-n,
/// Ctrl-p, Down and Up on line 1, n and N in the pane.
pub fn step(p: *Pardes, id: usize, delta: i32) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    // A `/`: the owner's places step, the rows follow them.
    if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| {
        const owner = p.panes[oid].?;
        if (owner.places.from == rp.serial) {
            const keyboard = p.active;
            owner.places.step(p, owner, delta > 0, 1, false);
            p.active = keyboard;
            showPlacesCurrent(p, id);
            return;
        }
    };
    // A Grep: by its lines, the window made again when the next is past it.
    if (q.source == .grep and q.found.items.len > 0) {
        const n = q.found.items.len;
        q.grep_at = if (delta > 0) (q.grep_at + 1) % n else (q.grep_at + n - 1) % n;
        const in_window = for (q.items.items) |it| {
            if (it.kind == .hit and it.hit == q.grep_at) break true;
        } else false;
        if (!in_window) makeGrepRows(p, id, q.frozen) catch {};
        for (q.items.items, 0..) |it, i| if (it.kind == .hit and it.hit == q.grep_at) return setCurrent(p, id, i, true);
        return;
    }
    const items = q.items.items;
    if (items.len == 0) return;
    var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0);
    for (0..items.len) |_| {
        if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1;
        if (items[i].kind == .hit) break;
    } else return;
    setCurrent(p, id, i, true);
}

/// Nothing current (a query that matches nothing): the +Preview shows
/// nothing, rather than a file the query no longer names.
fn blankPreview(p: *Pardes, qid: usize) void {
    const pid = previewOf(p, qid) orelse return;
    const pane = p.panes[pid].?;
    const f = &pane.file.?;
    if (f.content.len == 0) return;
    const dir = std.fs.path.dirname(p.panes[qid].?.file.?.path) orelse "/";
    const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ dir, config.preview_buffer }) catch return;
    const empty = p.gpa.alloc(u8, 0) catch {
        p.gpa.free(path);
        return;
    };
    p.gpa.free(f.path);
    f.path = path;
    File.setContent(p, f, empty);
    f.saved_revision = f.revision;
    f.scroll = 0;
}

/// Where the current row points, shown with the keyboard left where it is:
/// a place in an open pane's text selected there (its places' current),
/// in view; a file an open pane shows, its line there; any other file in
/// the +Preview under this pane. Every pane it moves remembers its view
/// first, for Esc.
fn showTarget(p: *Pardes, id: usize) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    const c = q.current orelse return;
    const f = &rp.file.?;
    if (c + 1 >= f.location_rows.len) return;
    const it = q.items.items[c];
    const meta = f.location_rows[c + 1];
    const keyboard = p.active;
    defer p.active = keyboard;
    if (it.serial != 0) {
        const tid = p.paneBySerial(it.serial) orelse return;
        const tp = p.panes[tid].?;
        if (tp.places.snap.len == 0) tp.places.remember(p, tp);
        if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false);
        return;
    }
    if (q.source == .symbols) {
        const oid = p.paneBySerial(q.owner) orelse return;
        look.focusPaneLine(p, oid, .{ .line = it.ref }, .center);
        return;
    }
    if (q.source == .panes) return;
    if (meta.path.len == 0) return;
    // A file open in a pane: shown there.
    for (p.panes, 0..) |slot, i| {
        const tp = slot orelse continue;
        const tf = tp.file orelse continue;
        if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue;
        if (tp.places.snap.len == 0) tp.places.remember(p, tp);
        const line0 = meta.at.line -| 1;
        const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows;
        if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center);
        return;
    }
    displayPreview(p, id, meta.path, meta.at);
}

// ---- the +Preview ----

/// The +Preview under query pane `qid`, if it has one: by serial.
fn previewOf(p: *Pardes, qid: usize) ?usize {
    const q = p.panes[qid].?.query.?;
    if (q.preview == 0) return null;
    return p.paneBySerial(q.preview) orelse {
        q.preview = 0;
        return null;
    };
}

/// Whether `pane` is a query pane's +Preview: that query pane's slot.
pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize {
    const f = pane.file orelse return null;
    const o = f.output orelse return null;
    if (o.from != .preview) return null;
    for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i;
    return null;
}

/// A +Preview made under query pane `qid`, `rows` tall, out of `giver`'s
/// rows: the text that asked, at the key that asked; the query pane itself
/// when its source word was edited to one that previews while typing (its
/// line 1 stays where it is).
fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize {
    const rp = p.panes[qid].?;
    const free = p.freeSlot() orelse return null;
    const dir = std.fs.path.dirname(rp.file.?.path) orelse "/";
    const content = p.gpa.dupe(u8, "") catch return null;
    const np = Output.open(p, free, dir, .preview, "", content) catch {
        p.gpa.free(content);
        return null;
    };
    layout.compute(p);
    if (!layout.attachFrom(p, qid, free, rows, giver)) {
        p.removePane(free, qid) catch {};
        return null;
    }
    rp.query.?.preview = np.serial;
    return free;
}

/// File `path` at `at` in the +Preview: its text read (once a file: a
/// file open in a pane would be shown there instead), the place centred
/// and selected. Made when the pane has none and its owner has the rows.
fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void {
    const id = previewOf(p, qid) orelse makePreview(p, qid, p.rects[qid].h / 2, qid) orelse return;
    const pane = p.panes[id].?;
    const f = &pane.file.?;
    if (!std.mem.eql(u8, f.path, path)) {
        if (exec.kindOf(path)) |kind| if (kind != .file) return;
        const bytes = blk: {
            pardes.turn.yield();
            defer pardes.turn.back();
            break :blk filesystem.read(p, path) catch return;
        };
        if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) {
            p.gpa.free(bytes);
            return;
        }
        const owned_path = p.gpa.dupe(u8, path) catch {
            p.gpa.free(bytes);
            return;
        };
        p.gpa.free(f.path);
        f.path = owned_path;
        File.setContent(p, f, bytes);
        f.saved_revision = f.revision;
        f.scroll = 0;
        f.syntax_dirty = true;
        pane.hscroll = 0;
        p.sync();
    }
    look.clearNavigationSelection(p, pane);
    if (at.line == 0 or at.line > File.nlines(p.gpa, f)) {
        f.scroll = 0;
        f.syntax_dirty = true;
        pane.body.cur_row = 0;
        pane.body.cur_col = 0;
        pane.body.cur_pinned = true;
        return;
    }
    look.focusPaneLine(p, id, at, .center);
    if (at.end_line == 0 or at.end_col <= at.col)
        pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) };
}

/// The +Preview becomes the file's pane where it stands: same slot, same
/// serial, same rect, its scroll and selection as the preview left them.
/// It is a file pane from here: an empty undo history, the Recent entry,
/// the watch, a file's tag; and a pane of its own, no longer attached (it
/// stays when its query pane goes).
fn promote(p: *Pardes, qid: usize, id: usize) void {
    const pane = p.panes[id] orelse return;
    const f = &pane.file.?;
    f.output = null;
    if (pane.tag.own) |own| p.gpa.free(own);
    pane.tag.own = null;
    f.saved_revision = f.revision;
    f.saved_hash = null;
    f.saved_len = null;
    f.disk_gone = false;
    f.syntax_dirty = true;
    pane.attached_to = null;
    if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path);
    if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
    pardes.ctlfs.events.noteLog(p, .rename, pane);
    p.panes[qid].?.query.?.preview = 0;
}

// ---- Enter, Esc ----

/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit
/// in its pane (the +Preview promoted to the file's pane when it shows
/// it), a `/` into the register, and the rows frozen into ordinary text.
pub fn land(p: *Pardes, id: usize, row: ?usize) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true);
    const t = &rp.body;
    if (t.mode == .insert) edit.exitInsert(p, t);
    freeze(p, id);
    const owner_id = p.paneBySerial(q.owner);
    if (q.source == .text) {
        const oid = owner_id orelse return;
        const owner = p.panes[oid].?;
        const set = &owner.places;
        // The whole list now, once, every place found: a result from here.
        if (set.started and set.from == rp.serial) {
            set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget);
            makeTextRows(p, id, oid, true) catch {};
        }
        if (set.started and set.from == rp.serial) {
            if (set.literal) {
                var escaped: std.ArrayList(u8) = .empty;
                normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {};
                p.registers.put(p.gpa, '/', escaped.items, 0, 1, true);
            } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true);
            p.registers.last_search = '/';
            set.provenance = .search;
        }
        p.jump_force = true;
        p.active = oid;
        return;
    }
    const c = q.current orelse {
        if (owner_id) |oid| p.active = oid;
        return;
    };
    const f = &rp.file.?;
    const it = q.items.items[c];
    const meta = f.location_rows[c + 1];
    p.jump_force = true;
    if (it.serial != 0) {
        if (p.paneBySerial(it.serial)) |tid| {
            p.active = tid;
            if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col);
        }
        return;
    }
    switch (q.source) {
        .symbols => if (owner_id) |oid| {
            look.focusPaneLine(p, oid, .{ .line = it.ref }, .center);
            return;
        },
        .panes => {
            if (p.paneBySerial(it.ref)) |tid| {
                p.active = tid;
                if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col);
                return;
            }
            // A pane this session closed: back where it was, from the
            // pane that asked (the owner, not this one, which may go).
            _ = p.store.reopen(p, it.ref, owner_id orelse id);
            return;
        },
        else => {},
    }
    // The preview shows it: promoted where it stands.
    if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) {
        promote(p, id, pid);
        p.active = pid;
        if (q.source == .grep) {
            const a = parse(q.asked) orelse return;
            const pp = p.panes[pid].?;
            pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false);
        }
        return;
    };
    // A Grep's whole list, now it is a result.
    if (q.source == .grep) makeGrepRows(p, id, true) catch {};
    var buf: [4096 + 64]u8 = undefined;
    const address = if (meta.at.line > 0)
        std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path
    else
        meta.path;
    look.lookAt(p, id, address);
}

/// The rows frozen: ordinary text from here, Save works on them; the
/// places they fed stay, while the pane lives; every view stays where the
/// search left it; the preview, of no more use, goes.
fn freeze(p: *Pardes, id: usize) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    q.frozen = true;
    if (q.saved) |s| freeSaved(p.gpa, s);
    q.saved = null;
    for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa);
    if (previewOf(p, id)) |pid| {
        const pv = p.panes[pid].?;
        // A preview showing the current row is promoted by `land`: one
        // showing another file goes.
        _ = pv;
    }
}

/// Esc on line 1 while typing: every view as the search found it, the
/// places it fed gone, and the pane closed (nothing was answered); a
/// reused pane's frozen rows come back instead, and their places.
pub fn cancel(p: *Pardes, id: usize) void {
    const rp = p.panes[id] orelse return;
    const q = rp.query orelse return;
    const t = &rp.body;
    if (t.mode == .insert) edit.exitInsert(p, t);
    const owner_id = p.paneBySerial(q.owner);
    for (p.panes) |slot| if (slot) |tp| {
        if (tp.places.from != rp.serial and tp.serial != q.owner) continue;
        tp.places.restore(p, tp);
        tp.places.forget(p.gpa);
        if (tp.places.from == rp.serial) tp.places.clear(p.gpa);
    };
    if (q.saved) |s| {
        q.saved = null;
        // A preview made for the query Esc took back has no use: its rows
        // go to the text whose rows they were.
        if (previewOf(p, id)) |pid| {
            p.panes[pid].?.attached_to = null;
            p.removePane(pid, owner_id) catch {};
            q.preview = 0;
        }
        const f = &rp.file.?;
        File.setContent(p, f, s.content);
        locations.freeRows(p.gpa, f.location_rows);
        f.location_rows = s.rows;
        p.gpa.free(q.asked);
        q.asked = s.asked;
        q.source = s.source;
        q.items.clearRetainingCapacity();
        q.items.appendSlice(p.gpa, s.items) catch {};
        p.gpa.free(s.items);
        q.current = s.current;
        q.total = s.total;
        q.k = s.k;
        q.frozen = true;
        rp.body.cur_row = 0;
        rp.body.cur_col = 0;
        showCurrent(rp);
        // Its places again, as Enter left them.
        if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| {
            const owner = p.panes[oid].?;
            owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false);
        };
        if (owner_id) |oid| p.active = oid;
        return;
    }
    // Attached, its rows go back to its owner; in the finder column, to its
    // own column's.
    const attached = layout.ownerOf(p, id) != null;
    if (owner_id) |oid| {
        p.removePane(id, if (attached) oid else null) catch {};
        p.active = oid;
        if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col);
    } else p.removePane(id, null) catch {};
}

/// A parse of pane `serial`'s text came back (Stream.receiveParse): its
/// query panes' rows are made again, under the declarations now, and a
/// Symbols query gathers them.
pub fn declsArrived(p: *Pardes, serial: u32) void {
    for (p.panes, 0..) |slot, id| {
        const rp = slot orelse continue;
        const q = rp.query orelse continue;
        if (q.owner != serial or q.frozen) continue;
        q.made_gen = std.math.maxInt(u64);
        if (q.source == .symbols) {
            startSource(p, id, q, .symbols, p.paneBySerial(serial));
            if (parse(q.asked)) |a| q.names.typed(p.gpa, a.pat);
        }
    }
}

/// The pane going (Del, its owner's Del): the places it fed go with it,
/// and a disk search still running for it.
pub fn release(p: *Pardes, pane: *Pane) void {
    if (p.stream.target == pane.serial) _ = p.stream.stop();
    for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) {
        tp.places.forget(p.gpa);
        tp.places.clear(p.gpa);
    };
}

// ---- keys, the mouse, edits ----

/// The keys a query pane answers itself, before its text has them. On
/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up
/// step the current row. In normal mode: Enter on a hit row lands on it,
/// n and N step. Anything else is ordinary text editing (line 1) or is
/// refused (the rows, while live: clampEdit). Tab stays the exec chord.
pub fn key(p: *Pardes, id: usize, k: Key) bool {
    const rp = p.panes[id] orelse return false;
    const q = rp.query orelse return false;
    if (rp.focus != .body) return false;
    const t = &rp.body;
    // Normal mode, live or frozen: n and N step the rows (the current one
    // shown where it points, the keyboard staying), Enter on a hit row lands
    // on it, as Enter typing does.
    if (t.mode == .normal) {
        if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false;
        if (k.cp == 'n' or k.cp == 'N') {
            step(p, id, if (k.cp == 'n') 1 else -1);
            // The caret on the rows goes to the current row, as j and k
            // would have taken it there.
            if (t.cur_row != 0) if (q.current) |c| {
                caretTo(rp, c);
            };
            return true;
        }
        // A language server's list, live: Esc is back to the text it was
        // asked in, every view as it was.
        if (hit(k, config.escape) and !q.frozen and q.lsp_rows.len > 0 and t.nsel == 0 and !t.vsel.active) {
            cancel(p, id);
            return true;
        }
        // Enter lands the current row: the caret's when j or k took it
        // there, never one a B1 only put the caret on.
        if (hit(k, config.look_key) and t.cur_row > 0 and q.current != null) {
            land(p, id, null);
            return true;
        }
        return false;
    }
    if (q.frozen) return false;
    if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false;
    if (hit(k, config.escape)) {
        cancel(p, id);
        return true;
    }
    if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) {
        land(p, id, null);
        return true;
    }
    const down = hit(k, config.query_next);
    const up = hit(k, config.query_prev);
    if (down or up) {
        step(p, id, if (down) 1 else -1);
        return true;
    }
    return false;
}

/// An edit of a live query pane's text (edit.setEditTextSpan): inside line
/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a
/// newline put in it, a blank); one wholly in the rows refused, as a tag's
/// prefix refuses one. Null: refused. Lifted from queryline.
pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 {
    const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len;
    const span = File.spanOf(old, new);
    const old_to = old.len - span.tail;
    const put = new[span.head .. new.len - span.tail];
    const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null;
    if (rows_same) return new;
    if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) {
        t.refused = true;
        if (t.pane()) |pane| if (p.paneIdOf(pane)) |id|
            p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)");
        return null;
    }
    // From inside line 1 into the rows: what it put in, flat, and what is
    // left of line 1 after it; the rows as they were.
    const kept = if (old_to < end) old[old_to..end] else "";
    const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null;
    for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') {
        c.* = ' ';
    };
    return out;
}

/// B3 on a row's gutter (its line number): the row's address, as a +Diff
/// line's prefix is its place (exec.operandAt). Null off a gutter.
pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 {
    if (pane.query == null) return null;
    const f = pane.file orelse return null;
    if (row == 0 or row >= f.location_rows.len) return null;
    const meta = f.location_rows[row];
    if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null;
    if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null;
    return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null;
}

/// The tag's start for a query pane: its name and where it is, `+Search
/// 3/27`, `0` with nothing found, `+` while it still counts.
pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 {
    const name = std.fs.path.basename(path);
    const more = if (q.more and !q.frozen) "+" else "";
    if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more });
    if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more });
    return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more });
}

/// The current row's mark: a tint the width of the body, painted before
/// the row's colours, so its match's tint, the places' and any selection
/// draw over it. Its own, from `current`: no click, sweep or chord clears
/// it, no B2 or B3 borrows it.
pub fn paintMark(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void {
    const q = pane.query orelse return;
    const c = q.current orelse return;
    const th = p.theme();
    const mark = colors.mix(th.bg orelse th.tag_bg, th.sel_bg);
    const tx = r.x + config.GUTTER;
    const tw = r.w -| config.GUTTER;
    const col = File.gutterWidth(pane);
    var row: i32 = 0;
    while (row < body_h) : (row += 1) {
        if (pane.wrapAt(row).line != @as(i32, @intCast(c + 1)) or col >= tw) continue;
        s.tint(tx + col, p.bodyTop(pane, r) + @as(u16, @intCast(row)), tw - col, mark, null);
    }
}

/// The other places on a hit row's line tinted, from the pane its rows are
/// in (the first is the row's own mark, Output.decorateRow): the current
/// one strongest, as in that pane's text.
pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void {
    const q = pane.query orelse return;
    const f = if (pane.file) |*file| file else return;
    const th = p.theme();
    const strong = p.chromeTheme().search_bg;
    const quiet = colors.mix(th.bg orelse th.tag_bg, strong);
    var vr: i32 = 0;
    var last: i32 = -1;
    while (vr < body_h) : (vr += 1) {
        const row = pane.wrapAt(vr).line;
        if (row == last or row < 1) continue;
        last = row;
        const i: usize = @intCast(row - 1);
        if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue;
        const it = q.items.items[i];
        if (it.kind != .hit or it.serial == 0) continue;
        const tid = p.paneBySerial(it.serial) orelse continue;
        const tp = p.panes[tid].?;
        const set = &tp.places;
        if (!set.shows(tp)) continue;
        const tf = &tp.file.?;
        const meta = f.location_rows[@intCast(row)];
        // Its line's places as they are now, found by the line: the rows
        // may be a tick behind the places.
        if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue;
        const ls = File.lineStart(p.gpa, tf, meta.at.line - 1);
        const next = File.lineStart(p.gpa, tf, meta.at.line);
        const line = modal.lineSlice(f.content, @intCast(row));
        var hi = Places.firstFrom(set.hits.items, ls);
        while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) {
            const h = set.hits.items[hi];
            if (h.start < ls + meta.source_column) continue;
            const a = meta.code_start + (h.start - ls - meta.source_column);
            const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column));
            if (b <= a or a >= line.len) continue;
            const current = set.current != null and set.current.? == hi;
            File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet);
        }
    }
}

// ---- tests ----

fn typeKeys(p: *Pardes, text: []const u8) void {
    for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
}

fn queryPane(p: *Pardes) ?usize {
    for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i;
    return null;
}

test "parse: line 1's first word names the source" {
    try std.testing.expectEqual(Source.text, parse("/alpha").?.source);
    try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat);
    try std.testing.expectEqual(Source.find, parse("Find lay").?.source);
    try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat);
    try std.testing.expectEqual(Source.grep, parse("Grep").?.source);
    try std.testing.expectEqual(Source.all, parse("All x y").?.source);
    try std.testing.expectEqualStrings("x y", parse("All x y").?.pat);
    try std.testing.expectEqual(Source.refs, parse("Refs").?.source);
    try std.testing.expect(parse("Findx") == null);
    try std.testing.expect(parse("grep x") == null);
    try std.testing.expect(parse("") == null);
}

test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n");
    p.newScratchBelow(0);
    const below = p.col_panes[0][1];
    p.active = 0;
    layout.compute(p);
    const before = p.rects;
    // cursor on line 3 (row 2)
    pane.body.cur_row = 2;
    pane.body.cur_col = 0;
    typeKeys(p, "/");
    const qid = queryPane(p).?;
    const qp = p.panes[qid].?;
    try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid));
    try std.testing.expectEqual(qid, p.active);
    try std.testing.expectEqualDeep(before[below], p.rects[below]);
    const born = p.rects[qid];
    try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content));
    // keystroke 1
    typeKeys(p, "a");
    const q = qp.query.?;
    try std.testing.expectEqual(Source.text, q.source);
    try std.testing.expect(pane.places.started and pane.places.from == qp.serial);
    try std.testing.expect(q.total > 0);
    try std.testing.expectEqualDeep(born, p.rects[qid]);
    // keystroke 2 .. `alph`: four places on four lines (rows), the
    // current the first at or after the cursor (line 3's alphabet)
    typeKeys(p, "lph");
    try std.testing.expectEqual(@as(usize, 4), q.total);
    try std.testing.expectEqual(@as(usize, 2), q.k);
    try std.testing.expectEqual(@as(?usize, 1), pane.places.current);
    const sel = pane.body.primaryRange(pane.file.?.content, 0);
    try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head));
    try std.testing.expectEqualDeep(born, p.rects[qid]);
    try std.testing.expectEqualDeep(before[below], p.rects[below]);
    try std.testing.expectEqual(qid, p.active);
    // Ctrl-n steps, the owner follows
    p.update(.{ .key = .{ .cp = 'n', .ctrl = true } });
    try std.testing.expectEqual(@as(usize, 3), q.k);
    // drawn: rows, tints, ticks
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    _ = try p.render(frame.allocator());
    try std.testing.expect(p.surface.nrail_ticks > 0);
    // zero hits: a state, the pane stays where it was, line 1 as typed
    typeKeys(p, "zz");
    try std.testing.expectEqual(@as(usize, 0), q.total);
    try std.testing.expect(p.panes[qid] != null);
    try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content));
    try std.testing.expectEqualDeep(born, p.rects[qid]);
    const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp);
    try std.testing.expectEqualStrings("+Search 0", tag);
    // Esc: the pane gone, its rows back to the owner, the owner as it was
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(p.panes[qid] == null);
    try std.testing.expectEqual(@as(usize, 0), p.active);
    layout.compute(p);
    try std.testing.expectEqualDeep(before[0], p.rects[0]);
    try std.testing.expectEqualDeep(before[below], p.rects[below]);
    try std.testing.expect(!pane.places.started);
    try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row);
}

test "a dump holding a query pane, live or frozen, restores, the pane as plain text" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    _ = try p.setTestFile("alpha one\nbeta\nalphabet\n");
    typeKeys(p, "/alpha");
    for (0..2) |_| {
        const qid = queryPane(p).?;
        try pardes.dump.dumpState(p);
        const restored = try pardes.dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?);
        defer restored.deinit();
        const back = restored.panes[qid].?;
        try std.testing.expect(back.query == null);
        try std.testing.expectEqual(@as(usize, 0), back.file.?.location_rows.len);
        try std.testing.expect(std.mem.startsWith(u8, back.file.?.content, "/alpha\n"));
        p.update(.{ .key = .{ .cp = Key.enter } });
    }
}

test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n");
    typeKeys(p, "/alpha");
    const qid = queryPane(p).?;
    const qp = p.panes[qid].?;
    const q = qp.query.?;
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expect(q.frozen);
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?);
    try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance);
    const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content);
    defer std.testing.allocator.free(frozen);
    // the rows: one a line (gamma alpha has one), a gutter number each
    try std.testing.expect(std.mem.indexOf(u8, frozen, "  1  alpha one\n") != null);
    // B3 on a row's line number is its address; on its code, no address
    var abuf: [256]u8 = undefined;
    const addr = rowAddress(qp, 1, 2, &abuf).?;
    try std.testing.expect(std.mem.endsWith(u8, addr, ":1:1"));
    try std.testing.expect(rowAddress(qp, 1, qp.file.?.location_rows[1].code_start + 1, &abuf) == null);
    // n and N in the owner step the same set, round the end silently
    const logged = p.messages.len;
    try std.testing.expectEqual(@as(?usize, 0), pane.places.current);
    typeKeys(p, "nnn");
    try std.testing.expectEqual(@as(?usize, 3), pane.places.current);
    typeKeys(p, "n");
    try std.testing.expectEqual(@as(?usize, 0), pane.places.current);
    try std.testing.expect(pane.places.wrapped);
    try std.testing.expectEqual(logged, p.messages.len);
    typeKeys(p, "N");
    try std.testing.expectEqual(@as(?usize, 3), pane.places.current);
    // a later `/` reuses the pane: line 1 fresh, the rows the new query's
    typeKeys(p, "/");
    try std.testing.expectEqual(qid, queryPane(p).?);
    try std.testing.expectEqual(qid, p.active);
    try std.testing.expect(!q.frozen);
    typeKeys(p, "beta");
    try std.testing.expectEqual(@as(usize, 1), q.total);
    // Esc: the frozen rows of `/alpha` again, the owner's places with them
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(p.panes[qid] != null);
    try std.testing.expect(q.frozen);
    try std.testing.expectEqualStrings(frozen, qp.file.?.content);
    try std.testing.expectEqualStrings("alpha", pane.places.pattern);
    // Del closes it, its places with it
    exec.runBuiltin(p, .Del, qid, "", null);
    try std.testing.expect(p.panes[qid] == null);
    try std.testing.expect(!pane.places.started);
}

/// A test's file pane in `tmp`, named `name`, holding `text`.
fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane {
    try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text });
    var base_buf: [std.fs.max_path_bytes]u8 = undefined;
    const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)];
    const pane = try p.setTestFile(text);
    p.gpa.free(pane.file.?.path);
    pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name });
    return pane;
}

fn leader(p: *Pardes, keys: []const u8) void {
    p.update(.{ .key = .{ .cp = ' ', .text = " " } });
    typeKeys(p, keys);
}

fn settle(p: *Pardes) void {
    // a typed Grep's pause run out on the clock
    p.advance(p.now_ns + Stream.debounce_ns + std.time.ns_per_ms);
    var frames: usize = 0;
    while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick);
    p.update(.tick);
}

test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" {
    if (!filesystem.platform_has_fs) return;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try tmp.dir.createDirPath(std.testing.io, "src");
    for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name|
        try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" });
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
    defer p.deinit();
    _ = try testFileIn(p, &tmp, "x.txt", "x\n");
    p.newScratchBelow(0);
    const other = p.col_panes[0][1];
    try std.testing.expect(layout.splitColumn(p, other, other, false));
    p.active = 0;
    layout.compute(p);
    const before = p.rects;
    leader(p, "ff");
    const qid = queryPane(p).?;
    const q = p.panes[qid].?.query.?;
    try std.testing.expectEqual(Source.find, q.source);
    try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content));
    // the group: owner, query pane, +Preview, out of the owner's rows alone
    const pv = previewOf(p, qid).?;
    try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv));
    try std.testing.expectEqualDeep(before[other], p.rects[other]);
    try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h);
    settle(p);
    // an empty query lists every name
    try std.testing.expectEqual(@as(usize, 4), q.total);
    const born = p.rects;
    typeKeys(p, "lay");
    settle(p);
    try std.testing.expectEqual(@as(usize, 1), q.total);
    try std.testing.expectEqualDeep(born[qid], p.rects[qid]);
    try std.testing.expectEqualDeep(born[pv], p.rects[pv]);
    // the current one in the preview, never by the pointer
    try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig"));
    try std.testing.expectEqual(qid, p.active);
    const serial = p.panes[pv].?.serial;
    const rect = p.rects[pv];
    p.update(.{ .key = .{ .cp = Key.enter } });
    // promoted where it stands: same slot, serial, rect; a file pane now
    try std.testing.expectEqual(pv, p.active);
    try std.testing.expectEqual(serial, p.panes[pv].?.serial);
    try std.testing.expect(p.panes[pv].?.file.?.output == null);
    try std.testing.expect(p.panes[pv].?.attached_to == null);
    layout.compute(p);
    try std.testing.expectEqualDeep(rect, p.rects[pv]);
    try std.testing.expect(q.frozen);
    try std.testing.expectEqualDeep(before[other], p.rects[other]);
}

test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" {
    if (!filesystem.platform_has_fs) return;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" });
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
    defer p.deinit();
    const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n");
    leader(p, "fg");
    const qid = queryPane(p).?;
    const q = p.panes[qid].?.query.?;
    typeKeys(p, "needle");
    settle(p);
    // a.txt's one, b.zig's three lines
    try std.testing.expectEqual(@as(usize, 3), q.total);
    const body = p.panes[qid].?.file.?.content;
    try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null);
    // the open file's hits are its places
    try std.testing.expect(a.places.started and a.places.hits.items.len == 1);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(p.panes[qid] == null);
    try std.testing.expect(!a.places.started);

    // All: a second pane, both searched, grouped by serial
    p.newScratchBelow(0);
    const s = p.active;
    const sf = &p.panes[s].?.file.?;
    File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n"));
    p.active = 0;
    leader(p, "/");
    const aid = queryPane(p).?;
    const aq = p.panes[aid].?.query.?;
    try std.testing.expectEqual(Source.all, aq.source);
    typeKeys(p, "needle");
    settle(p);
    try std.testing.expectEqual(@as(usize, 3), aq.total);
    const all = p.panes[aid].?.file.?.content;
    var hb: [32]u8 = undefined;
    const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?;
    const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?;
    try std.testing.expect(a.serial < p.panes[s].?.serial and first < second);
    try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?);
    // two places on one line are one row
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice"));
}

test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=<path>)" {
    const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest;
    const path = std.mem.span(path_z);
    const io = std.testing.io;
    const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20));
    defer std.testing.allocator.free(bytes);
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 });
    defer p.deinit();
    const pane = try p.setTestFile(bytes);
    p.gpa.free(pane.file.?.path);
    pane.file.?.path = try p.gpa.dupe(u8, path);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    _ = try p.render(frame.allocator());
    pane.body.cur_row = 15000;
    pane.ensureCursorVisible();
    _ = frame.reset(.retain_capacity);
    _ = try p.render(frame.allocator());
    const Clock = struct {
        fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 {
            const t0 = Places.nowNs();
            pp.update(ev);
            _ = fr.reset(.retain_capacity);
            _ = try pp.render(fr.allocator());
            return Places.nowNs() - t0;
        }
    };
    var report: std.ArrayList(u8) = .empty;
    defer report.deinit(std.testing.allocator);
    var base: u64 = 0;
    for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } });
    try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000});
    const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } });
    try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000});
    for ("pane.v") |c| {
        const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } });
        var ticks: usize = 0;
        var worst: u64 = 0;
        while (busy(p) or pane.places.busy(pane)) : (ticks += 1) {
            if (ticks > 500) break;
            worst = @max(worst, try Clock.step(p, &frame, .tick));
        }
        const qid = queryPane(p).?;
        try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total });
    }
    // Enter: frozen; then edits in the owner with the pane open.
    _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } });
    _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } });
    var worst_edit: u64 = 0;
    var sum: u64 = 0;
    for (0..20) |_| {
        const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } });
        worst_edit = @max(worst_edit, t);
        sum += t;
        const t2 = try Clock.step(p, &frame, .tick);
        worst_edit = @max(worst_edit, t2);
    }
    try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 });
    // The same edits with no query pane at all, for the editor's own cost.
    p.update(.{ .key = .{ .cp = Key.escape } });
    exec.runBuiltin(p, .Del, queryPane(p).?, "", null);
    p.update(.tick);
    p.update(.{ .key = .{ .cp = 'i', .text = "i" } });
    sum = 0;
    for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } });
    try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000});
    std.debug.print("{s}", .{report.items});
}

test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
    defer p.deinit();
    const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n    _ = alpha;\n}\nfn gamma() void {}\n");
    p.gpa.free(pane.file.?.path);
    pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig");
    // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text
    typeKeys(p, "e*");
    const qid = queryPane(p).?;
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/"));
    try std.testing.expect(pane.places.started);
    typeKeys(p, "n");
    try std.testing.expectEqual(@as(?usize, 0), pane.places.current);
    // SPC b b: the open panes by name; Enter goes to the marked one
    p.newScratchBelow(0);
    const other = p.active;
    p.active = 0;
    leader(p, "bb");
    const bid = queryPane(p).?;
    try std.testing.expectEqual(bid, qid);
    try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source);
    try std.testing.expect(p.panes[bid].?.query.?.total >= 1);
    // SPC s s: the declarations, fuzzy; Enter lands on the line
    p.update(.{ .key = .{ .cp = Key.escape } });
    p.active = 0;
    leader(p, "ss");
    const sid = queryPane(p).?;
    try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source);
    // (context declarations span lines: a one-line fn is none of them)
    typeKeys(p, "bet");
    try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total);
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
    _ = other;
    // SearchPane new: the frozen one stays, unattached; a new one under the owner
    p.settings.search_pane = .new;
    typeKeys(p, "/");
    const nid = queryPane2(p, sid).?;
    try std.testing.expect(nid != sid);
    try std.testing.expect(p.panes[sid].?.attached_to == null);
    try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid));
}

fn queryPane2(p: *Pardes, not: usize) ?usize {
    for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i;
    return null;
}

test "a language server's list: one answer lands with no pane, several open the list in normal mode on the current row, none is a message, Esc goes back" {
    const lsp = pardes.lsp;
    if (!lsp.supports.contains(.references) or !lsp.supports.contains(.diagnostics)) return;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("alpha one\nbeta\nalpha two\ngamma\nalpha three\n");
    const npanes = struct {
        fn of(pp: *Pardes) usize {
            var n: usize = 0;
            for (pp.panes) |slot| n += @intFromBool(slot != null);
            return n;
        }
    }.of;
    // One: the keyboard on it, no pane, the place tinted and n's.
    p.lspRequest(0, .references, "");
    p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "/test.txt:3:1-5 alpha two\n" } });
    try std.testing.expectEqual(@as(usize, 1), npanes(p));
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row);
    try std.testing.expectEqual(@as(usize, 1), pane.places.hits.items.len);
    try std.testing.expectEqual(Places.Hit{ .start = 15, .end = 20 }, pane.places.hits.items[0]);
    // None: a message, no pane.
    p.lspRequest(0, .diagnostics, "");
    p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "" } });
    try std.testing.expectEqual(@as(usize, 1), npanes(p));
    try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "none") != null);
    // Several: the list open, the keyboard in it in normal mode on the
    // current row, which the text shows; line 1 as text.
    pane.body.cur_row = 0;
    pane.body.cur_col = 0;
    p.lspRequest(0, .references, "");
    p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "/test.txt:1:1-5 alpha one\n/test.txt:3:1-5 alpha two\n/test.txt:5:1-5 alpha three\n" } });
    const qid = queryPane(p).?;
    const qp = p.panes[qid].?;
    const q = qp.query.?;
    try std.testing.expectEqual(qid, p.active);
    try std.testing.expect(qp.body.mode == .normal);
    try std.testing.expect(std.mem.startsWith(u8, qp.file.?.content, "Refs"));
    try std.testing.expectEqual(@as(i32, @intCast(q.current.? + 1)), qp.body.cur_row);
    try std.testing.expectEqual(@as(usize, 3), pane.places.hits.items.len);
    const first = pane.places.current.?;
    // n steps the rows, the caret with them, the text following.
    typeKeys(p, "n");
    try std.testing.expectEqual(@as(i32, @intCast(q.current.? + 1)), qp.body.cur_row);
    try std.testing.expectEqual(first + 1, pane.places.current.?);
    // Esc: back to the text, as it was, the list gone.
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(p.panes[qid] == null);
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
}

test "B1 on a query pane's rows places the caret and selects, nothing else, the current row's mark kept; j, k and n make a row current, Enter lands the current" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n");
    typeKeys(p, "/alpha");
    const qid = queryPane(p).?;
    const qp = p.panes[qid].?;
    const q = qp.query.?;
    p.acknowledgePanelPresentation(&.{});
    const owner_sel = pane.body.primaryRange(pane.file.?.content, 0);
    const owner_scroll = pane.file.?.scroll;
    try std.testing.expectEqual(@as(?usize, 0), q.current);
    const place = pane.places.current;
    const r = p.rects[qid];
    const row_y = r.y + qp.tag_rows;
    const y = row_y + 3;
    const x = r.x + config.GUTTER + File.gutterWidth(qp) + 6;
    // a click: the caret there, the current row and every other pane as they were
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = y } });
    try std.testing.expectEqual(@as(i32, 3), qp.body.cur_row);
    try std.testing.expectEqual(@as(?usize, 0), q.current);
    try std.testing.expectEqual(place, pane.places.current);
    try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0));
    try std.testing.expectEqual(owner_scroll, pane.file.?.scroll);
    try std.testing.expect(queryPane2(p, qid) == null);
    // the current row (1) still marked, no other row (2) is
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const surf = try p.render(frame.allocator());
    const far = r.x + r.w - 2;
    try std.testing.expect(!std.meta.eql(surf.at(far, row_y + 1).style.bg, surf.at(far, row_y + 2).style.bg));
    // a sweep selects the text it went over, and nothing else
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 4, .row = y } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x + 4, .row = y } });
    const swept = qp.sel[@backingInt(config.select_button)];
    try std.testing.expect(swept.state == .done and swept.r0 == swept.r1 and swept.c1 - swept.c0 == 4);
    try std.testing.expectEqual(@as(?usize, 0), q.current);
    try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0));
    // the keyboard: n steps from the current row, not the caret's, the caret with it
    p.active = qid;
    if (qp.body.mode == .insert) p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expect(p.panes[qid] != null);
    typeKeys(p, "n");
    try std.testing.expectEqual(@as(?usize, 1), pane.places.current);
    try std.testing.expectEqual(@as(i32, 2), qp.body.cur_row);
    // j onto the next row makes it current, the text following
    typeKeys(p, "j");
    try std.testing.expectEqual(@as(i32, 3), qp.body.cur_row);
    try std.testing.expectEqual(@as(?usize, 2), pane.places.current);
    // B1 elsewhere, then Enter: the current row lands, not the caret's
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = row_y + 1 } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = row_y + 1 } });
    p.active = qid;
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expectEqual(@as(usize, 0), p.active);
    try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row);
}