plv 0.26.0

A terminal viewer and editor for CSV, TSV, JSONL, Parquet and DuckLake data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
use std::{
    cell::Cell,
    io,
    path::{Path, PathBuf},
    sync::mpsc,
    time::Duration,
};

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::{
    DefaultTerminal, Frame,
    layout::{Constraint, Layout},
    style::Style,
    widgets::Paragraph,
};

use crate::clipboard;
use crate::complete::{self, Completion};
use crate::data::Store;
use crate::data::lake_db::{self, LakeDb};
use crate::lake::{Lake, Level, Scope};
use crate::picker::Picker;
use crate::search::{SearchQuery, SearchState, SearchStatus};
use crate::ui::{
    self, Browser, CellView, CellWindow, DataTable, Help, Panel, Prompt, Section, SelectionMode,
    StatusBar, Theme,
};
use crate::view;
use polars::prelude::DataType;
use regex::Regex;

enum AppMode {
    Normal,
    Search,
    /// Typing a new value for one cell. What is typed goes into the edit
    /// buffer, never straight to disk — `:w` writes.
    Edit,
    /// Typing an ex command after `:`.
    Command,
    /// The column picker is up. It holds a working copy of what it edits, so
    /// the table underneath is untouched until `Enter`.
    Picker,
}

/// A rectangle of cells, as inclusive `(row range, column range)` in absolute
/// coordinates.
type Block = ((usize, usize), (usize, usize));

/// A block operator holds a value per cell — an overlay entry, or a register
/// slot — and a column-mode selection covers every row in the file. Past this
/// many cells it is refused rather than attempted.
const MAX_BLOCK: usize = 100_000;

/// A pending operator over a visual selection.
#[derive(Clone, Copy)]
struct Fill {
    block: Block,
    mode: FillMode,
}

/// How a fill combines the typed text with what each cell already holds.
///
/// Mirrors blockwise visual mode in vim, where `c` changes the block outright
/// but `I` and `A` insert at the start and the end of every line in it. plv has
/// no text objects, so the lowercase keys are free to mean the same thing.
#[derive(Clone, Copy, PartialEq, Debug)]
enum FillMode {
    /// `c`: the typed value replaces each cell.
    Replace,
    /// `i`: the typed text goes in front of what is already there.
    Prepend,
    /// `a`: the typed text goes after what is already there.
    Append,
}

impl FillMode {
    /// How the prompt describes what is about to happen.
    fn verb(self) -> &'static str {
        match self {
            FillMode::Replace => "fill",
            FillMode::Prepend => "prepend to",
            FillMode::Append => "append to",
        }
    }

    fn combine(self, typed: &str, current: &str) -> String {
        match self {
            FillMode::Replace => typed.to_string(),
            FillMode::Prepend => format!("{typed}{current}"),
            FillMode::Append => format!("{current}{typed}"),
        }
    }
}

/// How far `Ctrl+d`/`Ctrl+u` and `Ctrl+f`/`Ctrl+b` move.
#[derive(Clone, Copy)]
enum Page {
    Half,
    Whole,
}

/// Where the caret lands when a cell edit opens, following vim.
#[derive(Clone, Copy)]
enum EditStart {
    /// `i`: the value as it stands, caret at the front.
    Front,
    /// `a`: the value as it stands, caret at the end.
    End,
    /// `c`: an empty field.
    Empty,
}

/// The cell window, while it is up: where the value is scrolled to, and how
/// much of it the window can hold.
///
/// The height is captured by `draw` rather than worked out by the key
/// handler, because how tall the window is depends on how the value wrapped,
/// which depends on how wide it is — all of it settled by `ui::cell_window`
/// at layout time. A key pressed before the first frame simply moves by a
/// line.
struct Inspect {
    /// First wrapped line on show. Not clamped here: `draw` knows how many
    /// lines there are and clamps it there, the way the picker's scroll is
    /// clamped, so `G` can just ask for the end.
    scroll: usize,
    rows: usize,
    /// The value's display lines, formatted once when the window opened.
    ///
    /// Kept rather than rebuilt each frame because recognising a format is a
    /// real parse of the whole value, and paying that on every `j` would make
    /// scrolling a big document cost what opening it did. Nothing can change
    /// it while it is held: the cursor cannot move while the window is up, so
    /// the cell under it is fixed.
    content: ui::cell::Content,
    /// What the window's own `/` is looking for, if anything.
    hunt: Option<Hunt>,
}

/// A search inside the cell window.
///
/// **Its own, not the table's.** `/` out there moves the cursor between rows
/// and leaves a state the status bar reports; borrowing it would mean closing
/// the window changed which row you were on, and stepping off the end of a
/// value would walk into the file. The two searches never meet: this one is
/// created when the window opens a pattern and dies with the window.
///
/// The hits are counted in **wrapped** lines, so they are found where `draw`
/// is — the only place that knows how the value broke — and stored back here
/// for `n` and `N` to step through, exactly as the scroll's clamp is. The
/// wrap depends on the width, so `at` records the width and the view they
/// were found under, and they are looked for again when either changes.
struct Hunt {
    pattern: String,
    regex: Regex,
    /// The pieces of every match, for the renderer to colour. A run the wrap
    /// broke is two pieces and one match.
    hits: Vec<ui::cell::Hit>,
    /// The line each match begins on — what `n` steps between, so a match
    /// drawn in two places is stepped to once.
    starts: Vec<usize>,
    /// Which match `n` last landed on. `None` until the first frame has found
    /// them, and where the pattern matched nothing.
    current: Option<usize>,
    /// `(width, raw)` the hits were found under, or `None` while they still
    /// have to be. `r` changes the lines themselves, so it invalidates them
    /// as surely as a resize does.
    at: Option<(u16, bool)>,
}

impl Hunt {
    fn new(pattern: String, regex: Regex) -> Self {
        Self {
            pattern,
            regex,
            hits: Vec::new(),
            starts: Vec::new(),
            current: None,
            at: None,
        }
    }

    /// Step to the next match, or the previous one, wrapping at either end.
    /// Answers the line to put on screen.
    ///
    /// Which match it steps *from* depends on where the reader is looking.
    /// While the one they are on is still on screen, `n` means the one after
    /// it — the ordinary reading. Once they have scrolled away from it, `n`
    /// means the next one from **here**, because the match they were on is no
    /// longer where they are, and being sent back up the value to resume from
    /// somewhere off screen is the surprising answer. It is `/`'s rule out in
    /// the table, where the cursor plays the part the viewport plays here.
    fn step(&mut self, top: usize, rows: usize, forward: bool) -> Option<usize> {
        let total = self.starts.len();
        if total == 0 {
            return None;
        }
        let showing = |line: usize| line >= top && line < top + rows;
        let at = match self.current.filter(|&at| showing(self.starts[at])) {
            Some(at) if forward => (at + 1) % total,
            Some(at) => (at + total - 1) % total,
            None if forward => self.starts.partition_point(|&line| line < top) % total,
            None => self
                .starts
                .iter()
                .rposition(|&line| line < top)
                .unwrap_or(total - 1),
        };
        self.current = Some(at);
        Some(self.starts[at])
    }
}

/// Which screen is in front: the lake catalog browser, or the data viewer.
#[derive(PartialEq)]
enum Screen {
    Browser,
    Viewer,
}

pub struct App {
    file_path: Option<PathBuf>,
    store: Option<Store>,
    col_offset: usize,
    cursor_row: usize,
    pending_num: String,
    /// A multi-key prefix waiting for its second key: `g` or `z`.
    pending_prefix: Option<char>,
    message: Option<String>,
    exit: bool,
    error: Option<String>,
    theme: Theme,
    selection_mode: SelectionMode,
    /// Selected column (absolute index). Only actively navigated in Column/Cell modes;
    /// initialised to col_offset when entering those modes via Tab.
    cursor_col: usize,
    /// Last fully-visible column index from the most recent render. Used to
    /// detect when the column cursor has scrolled off the right edge.
    last_vis_col: usize,
    /// Terminal width captured each frame; used to compute column layout.
    last_frame_width: u16,
    mode: AppMode,
    /// Cell being edited, as `(absolute row, column index)`. Editing is
    /// blocked while a sort is active, so the row is also the file's row.
    edit_cell: Option<(usize, usize)>,
    /// When set, committing runs over a whole block rather than over
    /// `edit_cell` alone.
    edit_fill: Option<Fill>,
    /// Where a visual selection started, as `(absolute row, column index)`.
    /// Absolute, so scrolling the anchor off screen does not move it.
    visual_anchor: Option<(usize, usize)>,
    /// The yank register: a block of cell text, rows outermost. Internal to
    /// plv — nothing is exchanged with the system clipboard.
    register: Vec<Vec<String>>,
    edit_buf: String,
    /// Caret position in `edit_buf`, counted in characters.
    edit_cursor: usize,
    command_buf: String,
    /// Candidates from the last Tab on the command line, and which of them is
    /// currently applied. Cleared by any key that changes the line.
    completion: Option<Completion>,
    completion_index: Option<usize>,
    search_buf: String,
    search_state: Option<SearchState>,
    /// Receives batches of matching row indices from the background search thread.
    /// Dropping this cancels the search.
    search_rx: Option<mpsc::Receiver<Vec<usize>>>,
    /// Receives the sorted first-page DataFrame from the background sort thread.
    sort_rx: Option<mpsc::Receiver<polars::prelude::DataFrame>>,
    /// Receives batches of rows matching the active `:filter`. Dropping this
    /// cancels the scan.
    filter_rx: Option<mpsc::Receiver<Vec<usize>>>,
    /// Incremented each draw while a background task is running; drives animations.
    spinner_tick: usize,
    /// Present when the opened path was a DuckLake catalog rather than a file.
    lake: Option<Lake>,
    screen: Screen,
    /// Viewport height captured each frame, so key handlers can size a new Store.
    last_vp: usize,
    /// The `?` key-binding overlay is showing.
    help_visible: bool,
    /// Number rows by distance from the cursor, so `{n}j` and `{n}G` can be
    /// read off the gutter instead of worked out.
    relative_rows: bool,
    /// The cursor cell is being shown in full above the status bar.
    ///
    /// Stays on while the cursor moves, so a column of long values can be read
    /// by walking down it — which is the thing a truncated column makes hard.
    cell_view: bool,
    /// Column widths set by hand, by source column index. Kept here and not
    /// in the `View`: how wide a column is drawn is a fact about this screen,
    /// not about which rows and columns the file is being asked for.
    widths: ui::Widths,
    /// Columns held at the left edge while the rest scroll past, by **source**
    /// column index — so a pin follows its column through a `:select` that
    /// reorders, exactly as `widths` does.
    ///
    /// Display state for the same reason widths are, and out of the `View` for
    /// the same reason: which column stays in sight while you walk sideways is
    /// a fact about this screen. `u` is the edit buffer's undo and does not
    /// take a pin back; `zp` again does, and `z|` takes them all back.
    pinned: std::collections::BTreeSet<usize>,
    /// The column picker, while it is up.
    picker: Option<Picker>,
    /// The cursor cell shown in a window of its own, over the table.
    ///
    /// Where `cell_view` is a band that stays on while the cursor moves, this
    /// is modal and holds the keys while it is up: what `j` scrolls is the
    /// value, not the table. Two views of one cell, because reading a long
    /// value and walking a column of them are different things to want.
    inspect: Option<Inspect>,
}

impl App {
    pub fn new(file: Option<PathBuf>) -> Self {
        Self {
            file_path: file,
            store: None,
            col_offset: 0,
            cursor_row: 0,
            pending_num: String::new(),
            pending_prefix: None,
            message: None,
            exit: false,
            error: None,
            theme: Theme::catppuccin_mocha(),
            selection_mode: SelectionMode::default(),
            cursor_col: 0,
            last_vis_col: 0,
            last_frame_width: 0,
            mode: AppMode::Normal,
            edit_cell: None,
            edit_fill: None,
            visual_anchor: None,
            register: Vec::new(),
            edit_buf: String::new(),
            edit_cursor: 0,
            command_buf: String::new(),
            completion: None,
            completion_index: None,
            search_buf: String::new(),
            search_state: None,
            search_rx: None,
            sort_rx: None,
            filter_rx: None,
            spinner_tick: 0,
            lake: None,
            screen: Screen::Viewer,
            last_vp: 20,
            help_visible: false,
            relative_rows: true,
            cell_view: false,
            widths: ui::Widths::new(),
            pinned: std::collections::BTreeSet::new(),
            picker: None,
            inspect: None,
        }
    }

    pub fn run(&mut self, terminal: &mut DefaultTerminal) -> anyhow::Result<()> {
        if let Some(path) = self.file_path.clone() {
            let size = terminal.size()?;
            let vp = Self::viewport_rows(size.height, 0);
            self.last_vp = vp;

            if let Some(lake_path) = lake_db::detect(&path) {
                match LakeDb::open(&lake_path, None).and_then(Lake::new) {
                    Ok(lake) => {
                        self.lake = Some(lake);
                        self.screen = Screen::Browser;
                    }
                    Err(e) => self.error = Some(e.to_string()),
                }
            } else {
                match Store::open_file(&path, vp) {
                    Ok(store) => {
                        // What opening the file turned up — keys the table has
                        // no room for, lines that were not records. Said once,
                        // where every other refusal and remark is said.
                        self.message = store.notes().map(str::to_string);
                        self.store = Some(store);
                    }
                    Err(e) => self.error = Some(e.to_string()),
                }
            }
        }

        while !self.exit {
            terminal.draw(|frame| self.draw(frame))?;
            self.handle_events()?;
        }
        Ok(())
    }

    /// status bar (1) + block borders (2) + header row (1) = 4 overhead,
    /// plus whatever the candidate panel is taking.
    fn viewport_rows(terminal_height: u16, panel: u16) -> usize {
        (terminal_height as usize).saturating_sub(4 + panel as usize)
    }

    /// Rows the strip above the status bar wants right now.
    ///
    /// Completion and the cell view share it. They cannot both be wanted —
    /// one belongs to the command line and the other to the table — so
    /// whichever is on gets it.
    fn panel_height(&self, width: u16, height: u16) -> u16 {
        if let Some(completion) = &self.completion {
            return ui::panel_height(&completion.options, width);
        }
        if self.cell_view {
            // Never more than half the screen: the table is still the point.
            let room = (height / 2).max(2);
            return match self.cell_under_cursor() {
                Some((_, value)) => ui::cell_height(&value, width, room),
                None => 0,
            };
        }
        0
    }

    /// The column name and full text of the cell under the cursor.
    fn cell_under_cursor(&self) -> Option<(String, String)> {
        let store = self.store.as_ref()?;
        let (name, _) = store.column_info(self.cursor_col)?;
        let value = store.cell_text(self.cursor_row, self.cursor_col)?;
        Some((name, value))
    }

    fn draw(&mut self, frame: &mut Frame) {
        let area = frame.area();
        self.last_frame_width = area.width;

        let panel = self.panel_height(area.width, area.height);
        let vp = Self::viewport_rows(area.height, panel);
        self.last_vp = vp;
        if let Some(s) = &mut self.store
            && s.viewport_rows != vp
        {
            let _ = s.resize(vp);
        }

        if self.screen == Screen::Browser {
            self.draw_browser(frame, area);
            self.draw_help(frame, area);
            return;
        }

        // A resize can leave row mode scrolled past what now fits.
        if matches!(self.selection_mode, SelectionMode::Row) {
            self.col_offset = self.col_offset.min(self.max_col_offset());
        }

        // In Column/Cell mode keep cursor_col within [col_offset, last_vis_col].
        // Must be correct in a single pass: handle_events blocks on event::read
        // when no search is active, so multi-frame convergence never fires.
        if !matches!(self.selection_mode, SelectionMode::Row) {
            // A pinned column is drawn at every offset, so landing on one is
            // never a reason to scroll: the view stays where it was and the
            // cursor is visible in the pinned block.
            let held = self.display_pins().contains(&self.cursor_col);
            if !held && self.cursor_col < self.col_offset {
                self.col_offset = self.cursor_col;
            } else if !held && self.cursor_col > self.last_vis_col {
                // cursor is off the right edge — compute the col_offset that
                // places cursor_col at the rightmost visible position.
                self.col_offset = self.col_offset_to_show_at_right(self.cursor_col);
            }
        }

        let [table_area, panel_area, status_area] = Layout::vertical([
            Constraint::Min(3),
            Constraint::Length(panel),
            Constraint::Length(1),
        ])
        .areas(area);

        // Done here, while `self` is still free to be borrowed mutably: the
        // render below only reads.
        if let Some(picker) = &mut self.picker {
            let len = picker.len();
            picker.state.go_to(picker.state.selected, len);
            picker
                .state
                .clamp_scroll(Browser::viewport_rows(table_area.height));
        }

        let file_name = self
            .lake
            .as_ref()
            .and_then(|l| l.scope_label())
            .or_else(|| {
                self.file_path
                    .as_ref()
                    .and_then(|p| p.file_name())
                    .and_then(|n| n.to_str())
                    .map(|s| s.to_string())
            })
            .unwrap_or_else(|| "plv".to_string());
        let col_offset = self.col_offset;
        let cursor_row = self.cursor_row;

        let vis_col_cell = Cell::new(self.col_offset);

        if let Some(store) = &self.store {
            // Advance spinner each frame while any background task is running.
            if self.search_rx.is_some() || self.sort_rx.is_some() || self.filter_rx.is_some() {
                self.spinner_tick = self.spinner_tick.wrapping_add(1);
            }

            let cursor_col = match self.selection_mode {
                SelectionMode::Row => col_offset,
                _ => self.cursor_col,
            };
            let edited = store.edited_cells();
            let sort_display = store.sort_display();

            // The picker takes the table's place rather than covering it:
            // the status bar below stays put, so a refusal it makes is
            // reported where every other refusal is.
            if let Some(picker) = &self.picker {
                let rows = picker.rows();
                frame.render_widget(
                    Browser {
                        title: picker.title(),
                        headers: Picker::headers(),
                        widths: Picker::widths(),
                        rows: &rows,
                        selected: picker.state.selected,
                        offset: picker.state.offset,
                        theme: &self.theme,
                    },
                    table_area,
                );
            } else {
                frame.render_widget(
                    DataTable {
                        df: &store.current_view,
                        col_offset,
                        cursor_col,
                        row_offset: store.row_offset,
                        cursor_row,
                        selection_mode: self.selection_mode,
                        theme: &self.theme,
                        search: self.search_state.as_ref(),
                        search_col: self.search_state.as_ref().and_then(|s| s.col_idx),
                        last_vis_col_out: &vis_col_cell,
                        sort: &sort_display,
                        sort_tick: self.sort_rx.as_ref().map(|_| self.spinner_tick),
                        edited: &edited,
                        selection: self.visual_range(),
                        relative_rows: self.relative_rows,
                        widths: &self.widths,
                        pinned: &self.display_pins(),
                    },
                    table_area,
                );
            }

            match self.mode {
                AppMode::Search => {
                    frame.render_widget(
                        Prompt {
                            prefix: "/",
                            buffer: &self.search_buf,
                            cursor: self.search_buf.chars().count(),
                            theme: &self.theme,
                        },
                        status_area,
                    );
                }
                AppMode::Command => {
                    frame.render_widget(
                        Prompt {
                            prefix: ":",
                            buffer: &self.command_buf,
                            cursor: self.command_buf.chars().count(),
                            theme: &self.theme,
                        },
                        status_area,
                    );
                }
                AppMode::Edit => {
                    // Name the column being edited: once the prompt has the
                    // caret, the header is the only thing saying what the
                    // value means.
                    // A fill spans columns, so it is counted rather than
                    // named; a single cell is named by its column.
                    let label = match self.edit_fill {
                        Some(fill) => format!(
                            " {} {} cells: ",
                            fill.mode.verb(),
                            Self::block_size(fill.block)
                        ),
                        None => self
                            .edit_cell
                            .and_then(|(_, col)| store.column_info(col))
                            .map_or_else(|| " ".to_string(), |(name, _)| format!(" {name}: ")),
                    };
                    frame.render_widget(
                        Prompt {
                            prefix: &label,
                            buffer: &self.edit_buf,
                            cursor: self.edit_cursor,
                            theme: &self.theme,
                        },
                        status_area,
                    );
                }
                AppMode::Normal | AppMode::Picker => {
                    let search_info = self.search_state.as_ref().map(|s| {
                        let (cur, total, complete) = s.match_info();
                        (s.query.raw.clone(), cur, total, complete)
                    });
                    frame.render_widget(
                        StatusBar {
                            file_name,
                            cursor_row,
                            total_rows: store.row_count(),
                            view: store.view.describe(&store.schema).map(|text| {
                                if store.filter_truncated() {
                                    format!("{text}  (first {})", store.row_count())
                                } else {
                                    text
                                }
                            }),
                            col_position: self.col_position(),
                            total_cols: store.column_count(),
                            message: self.message.clone(),
                            dirty: store.dirty(),
                            selection: self
                                .visual_range()
                                .map(|((r0, r1), (c0, c1))| (r1 - r0 + 1, c1 - c0 + 1)),
                            pending_num: self.pending_num.clone(),
                            pending_prefix: self.pending_prefix,
                            theme: &self.theme,
                            search_info,
                            spinner_tick: self.spinner_tick,
                            sort_tick: self.sort_rx.as_ref().map(|_| self.spinner_tick),
                            filtering: store.filtering(),
                            help: if let Some(inspect) = &self.inspect {
                                // The window holds every key while it is up,
                                // so the bar has to stop offering the table's.
                                // `r` is named only where there is another
                                // view of this value to switch to.
                                match (inspect.content.switchable(), inspect.content.raw) {
                                    (false, _) => " j/k:↕  g/G:start/end  q:close ",
                                    (true, false) => " j/k:↕  g/G:start/end  r:raw  q:close ",
                                    (true, true) => " j/k:↕  g/G:start/end  r:formatted  q:close ",
                                }
                            } else if self.picker.is_some() {
                                " -:show  a/A:all/one  p:pin  ⏎:apply  esc "
                            } else if self.lake.is_some() {
                                " f:partitions  T:snapshots  b:back  ?:help "
                            } else {
                                " j/k:↕  h/l:←→  /:search  ?:help  q:quit "
                            },
                        },
                        status_area,
                    );
                }
            }
        } else if let Some(err) = &self.error {
            frame.render_widget(
                Paragraph::new(format!("Error: {err}")).style(Style::new().red()),
                table_area,
            );
        } else {
            frame.render_widget(
                Paragraph::new(
                    "Usage: plv <file.csv|file.jsonl|file.parquet|lake.ducklake|bundle-dir>",
                )
                .centered(),
                table_area,
            );
        }

        if let Some(completion) = &self.completion {
            frame.render_widget(
                Panel {
                    items: &completion.options,
                    selected: self.completion_index,
                    theme: &self.theme,
                },
                panel_area,
            );
        } else if self.cell_view
            && let Some((name, value)) = self.cell_under_cursor()
        {
            frame.render_widget(
                CellView {
                    name: &name,
                    value: &value,
                    theme: &self.theme,
                },
                panel_area,
            );
        }

        self.draw_inspect(frame, area);
        self.draw_help(frame, area);
        self.last_vis_col = vis_col_cell.get();
    }

    /// The cell window, drawn over the table and under the help overlay —
    /// `?` explains what is in front, so it has to be in front.
    ///
    /// Where the scroll is clamped: this is the one place that knows both how
    /// many lines the value wrapped to and how many the window holds, and it
    /// runs before every frame, so a key handler can move the scroll freely
    /// and `G` can simply ask for the end. The picker's scroll is clamped
    /// here for the same reason.
    fn draw_inspect(&mut self, frame: &mut Frame, area: ratatui::layout::Rect) {
        if self.inspect.is_none() {
            return;
        }
        // The value itself is not read here: the window holds the lines it
        // formatted when it opened. This is the check that there is still a
        // cell under the cursor at all — the window holds every key while it
        // is up, and one with nothing in it could only be escaped from.
        let Some((name, _)) = self.cell_under_cursor() else {
            self.inspect = None;
            return;
        };
        let dtype = self
            .store
            .as_ref()
            .and_then(|store| store.column_info(self.cursor_col))
            .map_or_else(String::new, |(_, dtype)| dtype.to_string());

        let Some(inspect) = &self.inspect else {
            return;
        };
        let title = ui::cell::title(&name, &dtype, &inspect.content);
        let layout = ui::cell::window(&inspect.content.lines, &title, area);
        let (popup, lines) = (layout.rect, &layout.lines);
        let rows = ui::cell::text_rows(popup);

        // The hits are found here for the reason the scroll is clamped here:
        // this is the one place that knows how the value wrapped, and a match
        // is a position in what is drawn. Found again only when the width or
        // the view changed under them — otherwise a `j` would re-run the
        // pattern over the whole document, which is the cost `Content` exists
        // to have paid once.
        let under = (popup.width, inspect.content.raw);
        if let Some(inspect) = &mut self.inspect
            && let Some(hunt) = &mut inspect.hunt
            && hunt.at != Some(under)
        {
            hunt.hits = ui::cell::find(
                &inspect.content.lines,
                &layout.lines,
                &layout.origins,
                &hunt.regex,
            );
            hunt.starts = ui::cell::match_lines(&hunt.hits);
            hunt.at = Some(under);
            // A rewrap moves every line, so the hit `n` was on is not the one
            // it was: land on the first from where the reader is rather than
            // on a number that now points somewhere else.
            hunt.current = None;
            let top = inspect.scroll;
            if let Some(line) = hunt.step(top, rows, true) {
                inspect.scroll = line.saturating_sub(rows / 3);
            }
        }

        let Some(inspect) = &self.inspect else {
            return;
        };
        let scroll = inspect.scroll.min(ui::cell::max_scroll(lines.len(), rows));

        if let Some(inspect) = &mut self.inspect {
            inspect.rows = rows;
            inspect.scroll = scroll;
        }

        let Some(inspect) = &self.inspect else {
            return;
        };
        let (hits, current, pattern) = match &inspect.hunt {
            Some(hunt) => (
                hunt.hits.as_slice(),
                hunt.current,
                Some(hunt.pattern.as_str()),
            ),
            None => ([].as_slice(), None, None),
        };
        frame.render_widget(
            CellWindow {
                name: &name,
                dtype: &dtype,
                content: &inspect.content,
                scroll,
                hits,
                current,
                pattern,
                theme: &self.theme,
            },
            area,
        );
    }

    fn draw_help(&self, frame: &mut Frame, area: ratatui::layout::Rect) {
        if !self.help_visible {
            return;
        }
        frame.render_widget(
            Help {
                sections: self.help_sections(),
                theme: &self.theme,
            },
            area,
        );
    }

    /// Key bindings for whatever is currently in front.
    fn help_sections(&self) -> &'static [Section<'static>] {
        const MOVE: &[(&str, &str)] = &[
            ("j / \u{2193}", "Move down"),
            ("k / \u{2191}", "Move up"),
            (
                "Ctrl+d / Ctrl+u",
                "Half a screen down / up, view and cursor",
            ),
            ("Ctrl+f / Ctrl+b", "A whole screen down / up"),
            ("gg / G", "First / last row"),
            ("{n}gg / {n}G", "Jump to row n"),
            ("zz / zt / zb", "Centre / top / bottom"),
            ("z> / z<", "Widen / narrow the cursor column"),
            ("z_", "Fit the column to what is on screen"),
            ("z=", "Put every column width back"),
            ("K", "Open the cursor cell in a window"),
            ("zk", "Show the cursor cell above the status bar"),
            ("#", "Relative or absolute row numbers"),
        ];
        const COLUMNS: &[(&str, &str)] = &[
            ("h / l", "Scroll columns left / right"),
            ("{n}h / {n}l", "Jump n columns"),
            ("H", "First column"),
            ("0 / $", "Scroll to the first / last column"),
            ("Tab", "Cycle row \u{2192} column \u{2192} cell"),
            ("s", "Sort by cursor column"),
            ("-", "Hide the cursor column (:reset select brings it back)"),
            ("C", "The column picker: show, hide and pin from a list"),
            ("zp", "Pin / unpin the cursor column at the left edge"),
            ("z|", "Unpin every column"),
        ];
        const SEARCH: &[(&str, &str)] = &[
            ("/", "Search (regex)"),
            ("n / N", "Next / previous match"),
            ("Esc", "Clear search and sorts"),
        ];
        const EDIT: &[(&str, &str)] = &[
            ("i / a", "Edit cell, caret at start / end"),
            ("c", "Replace cell"),
            ("x", "Clear cell"),
            ("dd / {n}dd", "Delete the row, or n rows"),
            ("o / O", "Open a new row below / above"),
            ("u / Ctrl+r", "Undo / redo"),
            ("y", "Yank, to the register and the system clipboard"),
            ("p", "Paste the register at the cursor"),
            ("", "Your terminal's paste key pastes from outside"),
            (
                "Tab / Shift+Tab",
                "While editing: commit, next / previous cell",
            ),
            (":w   :w!   :w path", "Write (force / elsewhere)"),
            (":q   :q!   :wq", "Quit (discarding / writing)"),
        ];
        const VIEWS: &[(&str, &str)] = &[
            (":select a b", "Show only these columns"),
            (":hide a b", "Drop these columns"),
            (":expand payload", "Lift a JSONL document into columns"),
            (":filter c > 10", "Keep matching rows; `~` is a regex"),
            (":filter a = x and b ~ y", "Conditions join with `and`"),
            (":sort a b-", "Sort by columns, `-` for descending"),
            (":select   :sort", "The verb alone puts it back"),
            (":reset [slot]", "Clear select, filter, sort, or all"),
            (
                "Tab / Shift+Tab",
                "Complete, then step through the candidates",
            ),
        ];
        const VISUAL: &[(&str, &str)] = &[
            ("v", "Start or cancel a selection"),
            ("", "Its shape follows the Tab mode"),
            ("c", "Replace every cell with one value"),
            ("i / a", "Prepend / append text to every cell"),
            ("x", "Clear the selected cells"),
            ("d", "Delete the selected rows"),
            ("y", "Yank the selection"),
        ];
        const GENERAL: &[(&str, &str)] = &[("?", "This help"), ("q", "Quit")];
        const LAKE: &[(&str, &str)] = &[
            ("f", "Partitions of this table"),
            ("b", "Back to the catalog"),
            ("T", "Snapshots (time travel)"),
        ];
        const BROWSE: &[(&str, &str)] = &[
            ("j / k", "Move selection"),
            ("g / G", "First / last entry"),
            ("Ctrl+d / Ctrl+u", "Half page down / up"),
            ("Enter", "Open the selection"),
            ("l / f", "Partitions of this table"),
            ("T", "Snapshots (time travel)"),
            ("a", "Whole table (from partitions)"),
            ("h / Esc", "Back"),
        ];

        // `Views` is in every one of these: `:select`, `:filter` and `:sort`
        // work on whatever is open, so a read-only file used to get an
        // overlay that named none of the commands it answers.
        const VIEWER: &[Section<'static>] = &[
            ("Rows", MOVE),
            ("Columns", COLUMNS),
            ("Search", SEARCH),
            ("Views", VIEWS),
            ("General", GENERAL),
        ];
        const VIEWER_LAKE: &[Section<'static>] = &[
            ("Rows", MOVE),
            ("Columns", COLUMNS),
            ("Search", SEARCH),
            ("Lake", LAKE),
            ("Views", VIEWS),
            ("General", GENERAL),
        ];
        const VIEWER_EDIT: &[Section<'static>] = &[
            ("Rows", MOVE),
            ("Columns", COLUMNS),
            ("Search", SEARCH),
            ("Edit", EDIT),
            ("Visual", VISUAL),
            ("Views", VIEWS),
            ("General", GENERAL),
        ];
        const PICK: &[(&str, &str)] = &[
            ("j / k", "Move down the list"),
            ("g / G", "First / last column"),
            ("Ctrl+d / Ctrl+u", "Half page down / up"),
            ("-", "Show or hide this column"),
            ("a / A", "Show every column / hide all but this one"),
            ("p", "Pin or unpin this column"),
            ("Enter", "Apply"),
            ("Esc", "Cancel, changing nothing"),
        ];
        const READ: &[(&str, &str)] = &[
            ("j / k", "Down / up a line"),
            ("Ctrl+d / Ctrl+u", "Half a window"),
            ("Ctrl+f / Ctrl+b", "A whole window"),
            ("g / G", "First / last line"),
            ("/", "Find in this value (regex)"),
            ("n / N", "Next / previous match"),
            ("", "Its own search: the table's is left alone"),
            ("r", "Raw ↔ formatted, where a format was recognised"),
            ("q / Esc / K", "Close"),
        ];
        const BROWSER: &[Section<'static>] = &[("Catalog", BROWSE), ("General", GENERAL)];
        // No `General` section: its `q` means quit, and in the picker `q`
        // cancels — one overlay must not say both. The picker's own list
        // already covers every key it answers.
        const PICKER: &[Section<'static>] = &[("Columns", PICK)];
        // Same reason the picker has no `General`: while the window is up `q`
        // closes it rather than quitting, and one overlay must not say both.
        const CELL: &[Section<'static>] = &[("Cell", READ)];

        // The status bar has room for a few hints and then degrades, so for a
        // modal screen whose keys are not guessable the overlay is the real
        // reference — which is the reason it exists.
        if self.inspect.is_some() {
            CELL
        } else if self.picker.is_some() {
            PICKER
        } else if self.screen == Screen::Browser {
            BROWSER
        } else if self.lake.is_some() {
            VIEWER_LAKE
        } else if self.store.as_ref().is_some_and(Store::is_editable) {
            VIEWER_EDIT
        } else {
            VIEWER
        }
    }

    // ── lake catalog browser ──────────────────────────────────────────────

    fn draw_browser(&mut self, frame: &mut Frame, area: ratatui::layout::Rect) {
        let [list_area, status_area] =
            Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).areas(area);

        let Some(lake) = &mut self.lake else { return };

        let len = lake.list_len();
        lake.state.go_to(lake.state.selected, len);
        lake.state
            .clamp_scroll(Browser::viewport_rows(list_area.height));

        let rows = lake.rows();
        frame.render_widget(
            Browser {
                title: lake.title(),
                headers: lake.headers(),
                widths: lake.widths(),
                rows: &rows,
                selected: lake.state.selected,
                offset: lake.state.offset,
                theme: &self.theme,
            },
            list_area,
        );

        let help = match lake.level {
            Level::Tables => " Enter:open  l:partitions  T:snapshots  ?:help  q:quit ",
            Level::Partitions { .. } => " Enter:open partition  a:whole table  h:back  ?:help ",
            Level::Snapshots => " Enter:travel to snapshot  h:back  ?:help ",
        };
        let line = match &self.message {
            Some(msg) => format!(" {msg}"),
            None => format!("{help}  [{}/{}]", lake.state.selected + 1, len.max(1)),
        };
        let style = if self.message.is_some() {
            Style::new()
                .bg(self.theme.message_bg)
                .fg(self.theme.message_fg)
        } else {
            Style::new()
                .bg(self.theme.status_bg)
                .fg(self.theme.status_fg)
        };
        frame.render_widget(Paragraph::new(line).style(style), status_area);
    }

    fn handle_browser_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Some(lake) = &mut self.lake else {
            return Ok(());
        };
        let len = lake.list_len();

        match key.code {
            KeyCode::Char('q') | KeyCode::Char('Q') => self.exit = true,
            KeyCode::Char('j') | KeyCode::Down => lake.state.move_by(1, len),
            KeyCode::Char('k') | KeyCode::Up => lake.state.move_by(-1, len),
            KeyCode::Char('d') if ctrl => lake.state.move_by(self.last_vp as isize / 2, len),
            KeyCode::Char('u') if ctrl => lake.state.move_by(-(self.last_vp as isize) / 2, len),
            KeyCode::Char('g') | KeyCode::Home => lake.state.go_to(0, len),
            KeyCode::Char('G') | KeyCode::End => lake.state.go_to(len.saturating_sub(1), len),

            // Descend into the partition list for the selected table.
            KeyCode::Char('l') | KeyCode::Right | KeyCode::Char('f') => {
                if let Level::Tables = lake.level {
                    let table = lake.state.selected;
                    if lake
                        .table(table)
                        .is_some_and(|t| !t.partition_cols.is_empty())
                    {
                        self.show_partitions(table, 0)?;
                    } else {
                        self.message = Some("Table is not partitioned".to_string());
                    }
                }
            }

            // Time travel: list the lake's snapshots.
            KeyCode::Char('T') => {
                lake.level = Level::Snapshots;
                lake.state = Default::default();
                let current = lake.current_snapshot_index();
                lake.state.go_to(current, lake.list_len());
            }

            // Back out of a sub-list to the table list.
            KeyCode::Char('h') | KeyCode::Left | KeyCode::Esc => {
                if let Level::Partitions { table } = lake.level {
                    lake.level = Level::Tables;
                    lake.state = Default::default();
                    lake.state.go_to(table, lake.list_len());
                } else if let Level::Snapshots = lake.level {
                    lake.level = Level::Tables;
                    lake.state = Default::default();
                } else if self.store.is_some() {
                    // Nothing to go back to at the top level; return to the
                    // viewer if one is already open.
                    self.screen = Screen::Viewer;
                }
            }

            // Open the whole table even while standing in its partition list.
            KeyCode::Char('a') => {
                if let Level::Partitions { table } = lake.level {
                    self.open_scope(Scope {
                        table,
                        partition: None,
                    })?;
                }
            }

            KeyCode::Enter => match lake.level {
                Level::Tables => {
                    let table = lake.state.selected;
                    self.open_scope(Scope {
                        table,
                        partition: None,
                    })?;
                }
                Level::Partitions { table } => {
                    let partition = lake.state.selected;
                    self.open_scope(Scope {
                        table,
                        partition: Some(partition),
                    })?;
                }
                Level::Snapshots => {
                    let Some(snapshot) = lake.snapshots.get(lake.state.selected) else {
                        return Ok(());
                    };
                    let (id, time) = (snapshot.id, snapshot.short_time());
                    self.switch_snapshot(id, &time)?;
                }
            },

            _ => {}
        }
        Ok(())
    }

    /// Re-resolve the whole catalog as of `snapshot` and, where possible, stay
    /// on the table the viewer was already showing so the same data can be
    /// compared across snapshots.
    ///
    /// A file-level scope is deliberately widened to the whole table: file ids
    /// are not stable across snapshots, so the same list position would mean a
    /// different slice of data.
    fn switch_snapshot(&mut self, snapshot: i64, time: &str) -> anyhow::Result<()> {
        let Some(lake) = &self.lake else {
            return Ok(());
        };
        let path = lake.db.path.clone();
        let previous = lake
            .scope
            .and_then(|s| lake.table(s.table))
            .map(|t| t.qualified_name());

        let reopened = match LakeDb::open(&path, Some(snapshot)).and_then(Lake::new) {
            Ok(lake) => lake,
            Err(e) => {
                self.message = Some(format!("Cannot read snapshot {snapshot}: {e}"));
                return Ok(());
            }
        };

        let target = previous.and_then(|name| {
            reopened
                .tables
                .iter()
                .position(|t| t.qualified_name() == name)
        });

        self.store = None;
        self.reset_view();
        self.lake = Some(reopened);

        if let Some(table) = target {
            self.open_scope(Scope {
                table,
                partition: None,
            })?;
            if let Some(lake) = &mut self.lake {
                lake.state.go_to(table, lake.list_len());
            }
        }

        // Whether or not the table survived, say where we landed. This
        // overwrites any inlined-rows notice from open_scope — the snapshot
        // change is the more important thing to report right now.
        self.message = Some(format!("Snapshot {snapshot} ({time})"));
        Ok(())
    }

    /// Show the partition list for `table`, loading it if needed.
    ///
    /// Partition lists are not loaded up front: each one costs a GROUP BY over
    /// the table, so it is paid only when the user asks to see it.
    fn show_partitions(&mut self, table: usize, select: usize) -> anyhow::Result<()> {
        let Some(lake) = &mut self.lake else {
            return Ok(());
        };
        if let Err(e) = lake.load_partitions(table) {
            self.message = Some(format!("Cannot list partitions: {e}"));
            return Ok(());
        }
        lake.level = Level::Partitions { table };
        lake.state = Default::default();
        lake.state.go_to(select, lake.list_len());
        self.screen = Screen::Browser;
        Ok(())
    }

    /// Build a `Store` for `scope` and switch to the data viewer.
    ///
    /// Errors are surfaced as a status message rather than aborting: a bad
    /// scope should leave the user in the browser, able to pick another.
    fn open_scope(&mut self, scope: Scope) -> anyhow::Result<()> {
        let vp = self.last_vp;
        let Some(lake) = &self.lake else {
            return Ok(());
        };
        let Some(table) = lake.table(scope.table) else {
            return Ok(());
        };

        // Row counts come from the partition list or the table's own count,
        // both of which the extension answers from catalog statistics.
        let (partition, rows) = match scope.partition {
            Some(i) => match lake.partitions.get(i) {
                Some(p) => (Some(p), p.rows),
                None => return Ok(()),
            },
            None => (None, table.rows),
        };

        let source = lake.db.source(table, partition);
        // Asked once when the table is opened: a page then seeks to the file
        // its rows are in rather than counting its way there. `None` when the
        // catalog will not say plainly, which is every page as it was.
        let reader = lake.db.reader(Some(table), &source);
        let opened = lake
            .db
            .try_clone()
            .and_then(|conn| Store::new_lake(conn, source, reader, vp, rows as usize));

        match opened {
            Ok(store) => {
                self.store = Some(store);
                self.reset_view();
                if let Some(lake) = &mut self.lake {
                    lake.scope = Some(scope);
                }
                self.screen = Screen::Viewer;
            }
            Err(e) => self.message = Some(format!("Cannot open: {e}")),
        }
        Ok(())
    }

    /// Clear per-table view state when a different scope is loaded.
    fn reset_view(&mut self) {
        self.col_offset = 0;
        self.cursor_row = 0;
        self.cursor_col = 0;
        self.pending_num.clear();
        self.search_state = None;
        self.search_rx = None;
        self.sort_rx = None;
        self.filter_rx = None;
    }

    fn handle_events(&mut self) -> io::Result<()> {
        // If a background task changed any state, return immediately so the
        // main loop redraws before blocking on input.
        if self.poll_sort() || self.poll_search() || self.poll_filter() {
            return Ok(());
        }

        // While any background task is running use a short timeout so the UI
        // redraws as result batches arrive. When idle, block on read directly.
        if (self.search_rx.is_some() || self.sort_rx.is_some() || self.filter_rx.is_some())
            && !event::poll(Duration::from_millis(50))?
        {
            return Ok(());
        }

        let outcome = match event::read()? {
            Event::Key(key) if key.kind == KeyEventKind::Press => self.handle_key_event(key),
            // What the terminal's own paste key pasted. plv never asks for the
            // clipboard — reading OSC 52 back is disabled in most terminals —
            // so this is the whole of the way in.
            Event::Paste(text) => self.handle_paste(text),
            _ => Ok(()),
        };
        if let Err(e) = outcome {
            self.error = Some(e.to_string());
        }
        Ok(())
    }

    /// Text arriving from outside, read as the block it is and put down where
    /// `p` would have put it.
    ///
    /// Down the same path as an internal paste — the clipping at the last row
    /// and column, the count of what fell off the edge — so there is one
    /// answer to what pasting does, whichever side the block came from.
    fn handle_paste(&mut self, text: String) -> anyhow::Result<()> {
        // Into whatever is taking text, when something is. A paste while a
        // command or a cell is being typed is meant for the line, not for the
        // grid, and a line holds one line — so the breaks in a multi-line
        // paste become spaces rather than being dropped or ending the edit.
        if !matches!(self.mode, AppMode::Normal | AppMode::Picker) {
            let flat = text.replace(['\n', '\r', '\t'], " ");
            match self.mode {
                AppMode::Edit => {
                    let at = self.edit_byte_index(self.edit_cursor);
                    self.edit_buf.insert_str(at, &flat);
                    self.edit_cursor += flat.chars().count();
                }
                AppMode::Command => {
                    self.command_buf.push_str(&flat);
                    self.completion = None;
                    self.completion_index = None;
                }
                AppMode::Search => self.search_buf.push_str(&flat),
                _ => {}
            }
            return Ok(());
        }
        if matches!(self.mode, AppMode::Picker) {
            return Ok(());
        }
        let block = clipboard::parse(&text);
        if block.is_empty() {
            return Ok(());
        }
        self.paste_block(&block)
    }

    /// Drain any pending search result batches from the background thread,
    /// then auto-jump to the nearest match on the first batch that arrives.
    /// Returns `true` if any state changed (triggers an immediate redraw).
    fn poll_search(&mut self) -> bool {
        let mut changed = false;

        loop {
            let result = match &self.search_rx {
                None => break,
                Some(rx) => rx.try_recv(),
            };
            match result {
                Ok(rows) => {
                    // What the search reports depends on the frame it read.
                    let shown: Vec<usize> = match &self.store {
                        Some(store) => rows
                            .into_iter()
                            .filter_map(|r| store.search_row_to_display(r))
                            .collect(),
                        None => rows,
                    };
                    if let Some(state) = &mut self.search_state {
                        state.matching_rows.extend(shown);
                        changed = true;
                    }
                }
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.search_rx = None;
                    if let Some(state) = &mut self.search_state {
                        state.status = SearchStatus::Complete;
                    }
                    changed = true;
                    break;
                }
            }
        }

        // Auto-jump to nearest match the first time results arrive.
        let needs_jump = self
            .search_state
            .as_ref()
            .is_some_and(|s| !s.initial_jump_done && !s.matching_rows.is_empty());

        if needs_jump {
            let cursor = self.cursor_row;
            let row = self.search_state.as_mut().and_then(|s| {
                s.initial_jump_done = true;
                s.next_from(cursor)
            });
            if let Some(row) = row {
                let _ = self.cursor_to(row);
            }
        }

        changed
    }

    /// Take whatever the filter scan has found since the last frame.
    fn poll_filter(&mut self) -> bool {
        let Some(rx) = &self.filter_rx else {
            return false;
        };
        let mut batches = Vec::new();
        let mut finished = false;
        loop {
            match rx.try_recv() {
                Ok(batch) => batches.push(batch),
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    finished = true;
                    break;
                }
            }
        }
        if batches.is_empty() && !finished {
            return false;
        }
        if let Some(store) = &mut self.store {
            for batch in batches {
                // The set fills up before the file runs out on a filter that
                // matches nearly everything; stop asking for more.
                if !store.extend_filter(batch).unwrap_or(false) {
                    finished = true;
                    break;
                }
            }
            if finished {
                let _ = store.finish_filter();
            }
        }
        if finished {
            // Dropping the receiver ends the scan.
            self.filter_rx = None;
        }
        // Rows arriving can leave the cursor past the end of what matched.
        let last = self
            .store
            .as_ref()
            .map_or(0, |s| s.row_count().saturating_sub(1));
        self.cursor_row = self.cursor_row.min(last);
        true
    }

    /// Check for completion of the background sort thread.
    /// Returns `true` if state changed (triggers an immediate redraw).
    fn poll_sort(&mut self) -> bool {
        let result = match &self.sort_rx {
            None => return false,
            Some(rx) => rx.try_recv(),
        };
        match result {
            Ok(df) => {
                self.sort_rx = None;
                if let Some(store) = &mut self.store {
                    let _ = store.adopt_sorted(df);
                }
                true
            }
            Err(mpsc::TryRecvError::Empty) => false,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.sort_rx = None;
                true
            }
        }
    }

    fn handle_key_event(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        self.message = None;
        if self.help_visible {
            // Any key dismisses the overlay, including a second '?'.
            self.help_visible = false;
            return Ok(());
        }
        // Only in the modes that are not taking text: '?' is an ordinary
        // character to type into a search pattern, a cell or a command. The
        // picker takes single keys, not text, so it can spare this one — and
        // needs to, since its keys are the ones least likely to be guessed.
        if key.code == KeyCode::Char('?') && matches!(self.mode, AppMode::Normal | AppMode::Picker)
        {
            self.help_visible = true;
            return Ok(());
        }
        if self.screen == Screen::Browser {
            return self.handle_browser_key(key);
        }
        // The window is modal: it is opened to read one value, and every key
        // that would move the table underneath is a key it wants for moving
        // through that value. `q` closes it rather than quitting for the same
        // reason it cancels the picker — closing a window never destroys
        // work, and there is none here to destroy.
        if self.inspect.is_some() && matches!(self.mode, AppMode::Normal) {
            return self.handle_inspect_key(key);
        }
        match self.mode {
            AppMode::Search => self.handle_search_key(key),
            AppMode::Edit => self.handle_edit_key(key),
            AppMode::Command => self.handle_command_key(key),
            AppMode::Picker => self.handle_picker_key(key),
            AppMode::Normal => self.handle_normal_key(key),
        }
    }

    fn handle_search_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        match key.code {
            KeyCode::Esc => {
                self.mode = AppMode::Normal;
                self.search_buf.clear();
            }
            KeyCode::Enter => {
                let raw = std::mem::take(&mut self.search_buf);
                self.mode = AppMode::Normal;
                // With the window up the pattern is for the value in it, not
                // for the file: the window holds every key, so `/` reached
                // here through it, and a search that moved the cursor
                // underneath would change the row the window is showing.
                if let Some(inspect) = &mut self.inspect {
                    if raw.is_empty() {
                        inspect.hunt = None;
                        return Ok(());
                    }
                    match Regex::new(&raw) {
                        Err(e) => self.message = Some(format!("Bad regex: {e}")),
                        Ok(regex) => inspect.hunt = Some(Hunt::new(raw, regex)),
                    }
                    return Ok(());
                }
                if raw.is_empty() {
                    self.search_state = None;
                    self.search_rx = None;
                    return Ok(());
                }
                match SearchQuery::new(raw) {
                    Err(e) => {
                        self.message = Some(format!("Bad regex: {e}"));
                    }
                    Ok(query) => {
                        if let Some(store) = &self.store {
                            let col_name = match self.selection_mode {
                                SelectionMode::Column | SelectionMode::Cell => {
                                    store.column_info(self.cursor_col).map(|(name, _)| name)
                                }
                                SelectionMode::Row => None,
                            };
                            let (tx, rx) = mpsc::channel();
                            store.search_async(query.raw.clone(), col_name.clone(), tx);
                            // Replace any in-progress search (dropping old rx cancels it)
                            self.search_rx = Some(rx);
                            let col_idx = col_name.map(|_| self.cursor_col);
                            self.search_state = Some(SearchState::new(query, col_idx));
                        }
                    }
                }
            }
            KeyCode::Backspace => {
                self.search_buf.pop();
            }
            KeyCode::Char(c) => {
                self.search_buf.push(c);
            }
            _ => {}
        }
        Ok(())
    }

    /// Keys while the cell window is up: the value scrolls, nothing else
    /// moves.
    ///
    /// The scroll is only ever moved here — clamping is `draw`'s, which is
    /// the only place that knows how far there is to go — so `G` asks for
    /// further than there is and lands at the bottom.
    fn handle_inspect_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Some(inspect) = &mut self.inspect else {
            return Ok(());
        };
        let rows = inspect.rows.max(1);
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => inspect.scroll += 1,
            KeyCode::Char('k') | KeyCode::Up => inspect.scroll = inspect.scroll.saturating_sub(1),
            KeyCode::Char('d') if ctrl => inspect.scroll += (rows / 2).max(1),
            KeyCode::Char('u') if ctrl => {
                inspect.scroll = inspect.scroll.saturating_sub((rows / 2).max(1))
            }
            KeyCode::Char('f') if ctrl => inspect.scroll += rows,
            KeyCode::PageDown => inspect.scroll += rows,
            KeyCode::Char('b') if ctrl => inspect.scroll = inspect.scroll.saturating_sub(rows),
            KeyCode::PageUp => inspect.scroll = inspect.scroll.saturating_sub(rows),
            // A lone `g` is the top. There is no other `g` command in here to
            // tell it apart from, and `gg` still works: the second one asks
            // for the top again.
            KeyCode::Char('g') | KeyCode::Home => inspect.scroll = 0,
            KeyCode::Char('G') | KeyCode::End => inspect.scroll = usize::MAX,
            KeyCode::Char('q') | KeyCode::Char('K') | KeyCode::Esc => self.inspect = None,
            // The window's own search. It borrows the `:`/`/` line's mode and
            // buffer — one prompt, one place that draws it — and
            // `handle_search_key` looks at whether the window is up to decide
            // which of the two searches the pattern is for.
            KeyCode::Char('/') if !ctrl => {
                self.search_buf.clear();
                self.mode = AppMode::Search;
            }
            // Stepping is counted from the top line on screen and not from
            // the last hit, so scrolling away by hand and pressing `n` goes on
            // from where the reader is looking.
            KeyCode::Char('n') | KeyCode::Char('N') if !ctrl => {
                let forward = key.code == KeyCode::Char('n');
                let top = inspect.scroll;
                let rows = inspect.rows.max(1);
                if let Some(hunt) = &mut inspect.hunt
                    && let Some(line) = hunt.step(top, rows, forward)
                {
                    // The hit is put a third of the way down rather than at
                    // the very top: a match with nothing above it has lost
                    // the run-up that says what it is part of. `zt` and `zz`
                    // are the same argument, settled the same way.
                    inspect.scroll = line.saturating_sub(rows / 3);
                }
            }
            // Back and forth between the bytes and what plv made of them. The
            // formatted view is an interpretation, and the raw value is the
            // one that gets edited and written, so it has to be reachable.
            // The scroll is kept and `draw` clamps it: the two views are the
            // same value and roughly the same length, so landing back where
            // you were reads better than being sent to the top.
            KeyCode::Char('r') if !ctrl && inspect.content.switchable() => {
                let raw = !inspect.content.raw;
                if let Some((_, value)) = self.cell_under_cursor() {
                    let content = ui::cell::Content::new(&value, raw, &self.theme);
                    if let Some(inspect) = &mut self.inspect {
                        inspect.content = content;
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn handle_normal_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        if let Some(prefix) = self.pending_prefix.take() {
            return self.resolve_prefix(prefix, key.code);
        }

        match key.code {
            KeyCode::Char('q') | KeyCode::Char('Q') => self.quit(false),

            // '0' scrolls to the first column, leaving it at the left edge.
            // Must come before the digit-accumulation arm — but only when no
            // count is being typed, or `10j` would lose its zero.
            KeyCode::Char('0') if !ctrl && self.pending_num.is_empty() => {
                self.col_offset = 0;
                self.cursor_col = 0;
            }

            // Accumulate numeric prefix (used by j/k/G)
            KeyCode::Char(c) if c.is_ascii_digit() && !ctrl => {
                self.pending_num.push(c);
            }

            // Row navigation — move cursor; scroll only when cursor leaves the viewport
            KeyCode::Char('j') | KeyCode::Down => {
                let n = self.take_count(1);
                self.cursor_down(n)?;
            }
            KeyCode::Char('k') | KeyCode::Up => {
                let n = self.take_count(1);
                self.cursor_up(n)?;
            }
            KeyCode::Char('d') if ctrl => self.scroll_page(true, Page::Half)?,
            KeyCode::Char('u') if ctrl => self.scroll_page(false, Page::Half)?,
            KeyCode::Char('f') if ctrl => self.scroll_page(true, Page::Whole)?,
            KeyCode::Char('b') if ctrl => self.scroll_page(false, Page::Whole)?,
            KeyCode::PageDown => self.scroll_page(true, Page::Whole)?,
            KeyCode::PageUp => self.scroll_page(false, Page::Whole)?,

            // `g` and `d` wait for their second key. The count survives, so
            // `12gg` and `3dd` each read as one action.
            KeyCode::Char('g') => self.pending_prefix = Some('g'),
            // Over a selection `d` acts at once, on the rows already chosen,
            // so it does not wait for a second key.
            KeyCode::Char('d') if !ctrl && self.visual_anchor.is_none() => {
                self.pending_prefix = Some('d')
            }
            KeyCode::Home => {
                self.pending_num.clear();
                self.cursor_to(0)?;
            }
            KeyCode::Char('G') | KeyCode::End => {
                if self.pending_num.is_empty() {
                    let last = self
                        .store
                        .as_ref()
                        .map_or(0, |s| s.row_count().saturating_sub(1));
                    self.cursor_to(last)?;
                } else {
                    let s = std::mem::take(&mut self.pending_num);
                    self.jump_to_line(&s)?;
                }
            }

            // z-prefix: zz (centre), zt (top), zb (bottom), and the column
            // widths. `Z` opens it too: its second keys are shifted ones, and
            // the shift tends to go down before the `z` does.
            KeyCode::Char('z' | 'Z') => {
                self.pending_num.clear();
                self.pending_prefix = Some('z');
            }

            // Column navigation, counted the same way `j` and `k` are.
            KeyCode::Char('h') | KeyCode::Left => {
                let n = self.take_count(1);
                self.column_left(n);
            }
            KeyCode::Char('l') | KeyCode::Right => {
                let n = self.take_count(1);
                self.column_right(n);
            }
            // Jump to first column (all modes) or last column (Column/Cell via $).
            KeyCode::Char('H') => {
                self.pending_num.clear();
                self.col_offset = 0;
                self.cursor_col = 0;
            }
            // '$' scrolls until the last column sits at the right edge.
            KeyCode::Char('$') => {
                self.pending_num.clear();
                self.cursor_col = self
                    .store
                    .as_ref()
                    .map_or(0, |s| s.column_count().saturating_sub(1));
                self.col_offset = self.max_col_offset();
            }

            // Sort by cursor column (Column/Cell mode only). Toggles asc ↔ desc;
            // pressing s on a new column adds it as the next priority sort key.
            // The picker needs no column cursor — it is a list of every
            // column, not an operation on the one under the cursor — so
            // unlike `-` it works in row mode too.
            KeyCode::Char('C') => {
                self.pending_num.clear();
                self.open_picker();
            }

            // Hide the cursor column. Row mode has no column cursor, so it
            // adopts one exactly as the edit keys do, rather than leaving the
            // key silently dead in the mode plv opens in.
            //
            // No exception for a row-shaped selection, unlike an edit: hiding
            // a column renumbers the ones after it, so `after_view_change`
            // drops the selection whatever mode it was made in. There is
            // nothing here to protect.
            KeyCode::Char('-') => {
                self.pending_num.clear();
                self.adopt_column_cursor();
                self.hide_column()?;
            }

            // Sort by the cursor column. Row mode adopts one, as `-` and the
            // edit keys do — and the selection it would reshape is one this
            // key already clears, so there is nothing to make an exception
            // for. `Esc` puts the order back.
            KeyCode::Char('s') => {
                self.visual_anchor = None;
                // Asked before anything moves, so a refusal leaves the screen
                // as it was — the selection mode included. Adopting a cursor
                // for a sort that is then refused would be a visible change
                // with nothing to show for it.
                if let Some(reason) = self.store.as_ref().and_then(Store::sort_blocked) {
                    self.message = Some(reason);
                    return Ok(());
                }
                self.adopt_column_cursor();
                if let Some(store) = &mut self.store {
                    self.sort_rx = Some(store.begin_sort(self.cursor_col));
                    self.cursor_row = 0;
                    // Sort changes the frame order, so any active search positions
                    // are now stale. Clear the search.
                    self.search_state = None;
                    self.search_rx = None;
                }
            }

            // Cycle selection mode: Row → Column → Cell → Row
            KeyCode::Tab => {
                self.visual_anchor = None;
                self.selection_mode = self.selection_mode.cycle();
                if !matches!(self.selection_mode, SelectionMode::Row) {
                    // Start column cursor at the leftmost visible column.
                    self.cursor_col = self.col_offset;
                }
                // Clear search — scope has changed
                self.search_state = None;
                self.search_rx = None;
            }

            // Lake: jump to this table's file pane / back to the browser.
            KeyCode::Char('f') if self.lake.is_some() => {
                self.pending_num.clear();
                if let Some(scope) = self.lake.as_ref().and_then(|l| l.scope) {
                    self.show_partitions(scope.table, scope.partition.unwrap_or(0))?;
                }
            }
            KeyCode::Char('b') if self.lake.is_some() => {
                self.pending_num.clear();
                self.screen = Screen::Browser;
            }
            KeyCode::Char('T') if self.lake.is_some() => {
                self.pending_num.clear();
                if let Some(lake) = &mut self.lake {
                    lake.level = Level::Snapshots;
                    lake.state = Default::default();
                    let current = lake.current_snapshot_index();
                    lake.state.go_to(current, lake.list_len());
                    self.screen = Screen::Browser;
                }
            }

            // Search
            KeyCode::Char('/') => {
                self.pending_num.clear();
                self.search_buf.clear();
                self.mode = AppMode::Search;
            }
            KeyCode::Char('n') => {
                self.pending_num.clear();
                if let Some(state) = &mut self.search_state {
                    if let Some(ci) = state.col_idx {
                        self.cursor_col = ci;
                    }
                    if let Some(row) = state.next_from(self.cursor_row) {
                        self.cursor_to(row)?;
                    }
                }
            }
            KeyCode::Char('N') => {
                self.pending_num.clear();
                if let Some(state) = &mut self.search_state {
                    if let Some(ci) = state.col_idx {
                        self.cursor_col = ci;
                    }
                    if let Some(row) = state.prev_from(self.cursor_row) {
                        self.cursor_to(row)?;
                    }
                }
            }
            // Editing. Ctrl+u and Ctrl+d are matched further up, so plain 'u'
            // reaching here is always undo.
            KeyCode::Char('v') => {
                self.pending_num.clear();
                self.visual_anchor = match self.visual_anchor {
                    Some(_) => None,
                    None => Some((self.cursor_row, self.cursor_col)),
                };
            }
            KeyCode::Char('c') if self.visual_anchor.is_some() => {
                self.begin_fill(FillMode::Replace)?
            }
            KeyCode::Char('i') if self.visual_anchor.is_some() => {
                self.begin_fill(FillMode::Prepend)?
            }
            KeyCode::Char('a') if self.visual_anchor.is_some() => {
                self.begin_fill(FillMode::Append)?
            }
            KeyCode::Char('x') if self.visual_anchor.is_some() => self.clear_selection()?,
            KeyCode::Char('d') if self.visual_anchor.is_some() => {
                let rows = self.visual_range().map(|((first, last), _)| (first, last));
                if let Some((first, last)) = rows {
                    self.delete_rows(first, last - first + 1)?;
                }
            }
            // `K` is vim's "tell me about the thing under the cursor", and
            // vim opens a pager in a window of its own to answer — which is
            // what a cell too big for its column needs. The strip is `zk`,
            // with the rest of the display adjustments.
            //
            // Row mode has no column cursor, so it adopts one exactly as the
            // edit keys do, rather than leaving the key dead in the mode plv
            // opens in.
            KeyCode::Char('K') => {
                self.pending_num.clear();
                self.adopt_column_cursor();
                // Nothing to read means no window: it holds every key while
                // it is up, so an empty one could only be escaped from.
                if let Some((_, value)) = self.cell_under_cursor() {
                    self.inspect = Some(Inspect {
                        scroll: 0,
                        rows: 0,
                        content: ui::cell::Content::new(&value, false, &self.theme),
                        hunt: None,
                    });
                }
            }
            KeyCode::Char('#') => {
                self.pending_num.clear();
                self.relative_rows = !self.relative_rows;
            }
            KeyCode::Char('o') => self.open_row(true)?,
            KeyCode::Char('O') => self.open_row(false)?,
            KeyCode::Char('y') => self.yank()?,
            KeyCode::Char('p') => self.paste()?,
            KeyCode::Char('i') => self.begin_edit(EditStart::Front)?,
            KeyCode::Char('a') => self.begin_edit(EditStart::End)?,
            KeyCode::Char('c') => self.begin_edit(EditStart::Empty)?,
            KeyCode::Char('x') => self.clear_cell()?,
            KeyCode::Char('u') => self.undo()?,
            KeyCode::Char('r') if ctrl => self.redo()?,
            KeyCode::Char(':') => {
                self.pending_num.clear();
                self.command_buf.clear();
                self.mode = AppMode::Command;
            }

            KeyCode::Esc if self.cell_view => {
                self.pending_num.clear();
                self.cell_view = false;
            }
            KeyCode::Esc if self.visual_anchor.is_some() => {
                self.pending_num.clear();
                self.visual_anchor = None;
            }
            KeyCode::Esc => {
                self.search_state = None;
                self.search_rx = None; // dropping rx cancels background scan
                self.pending_num.clear();
                if let Some(store) = &mut self.store
                    && !store.view.sort.is_empty()
                {
                    let _ = store.clear_sort();
                    self.cursor_row = 0;
                }
            }

            _ => {
                self.pending_num.clear();
            }
        }
        Ok(())
    }

    // ── editing ───────────────────────────────────────────────────────────

    /// Give row mode a column cursor, at the leftmost visible column — which
    /// is where `Tab` would put it.
    ///
    /// A key that acts on *a column* has to have one to act on, and of the
    /// three answers to being pressed without one, silence is the worst: it
    /// is indistinguishable from a key that does not exist. Refusing at least
    /// says why. Adopting does the obvious thing and leaves the user where
    /// they meant to be.
    ///
    /// Callers decide when, because a row-shaped *selection* can be
    /// meaningful in its own right and this reshapes it.
    fn adopt_column_cursor(&mut self) {
        if matches!(self.selection_mode, SelectionMode::Row) {
            self.selection_mode = SelectionMode::Cell;
            self.cursor_col = self.col_offset;
        }
    }

    /// Whether an edit can start here, reporting why not when it cannot.
    ///
    /// An edit needs a column cursor, so row mode adopts one rather than doing
    /// nothing — the leftmost visible column, which is where Tab would put it.
    fn ready_to_edit(&mut self) -> bool {
        let blocked = match &self.store {
            None => Some("no file open"),
            Some(store) => store.edit_blocked(),
        };
        if let Some(reason) = blocked {
            self.message = Some(reason.to_string());
            return false;
        }
        // Row mode has no column cursor, so a single-cell edit adopts one —
        // but a row-shaped *selection* is meaningful in its own right and must
        // not be reshaped out from under the operator about to run on it.
        if self.visual_anchor.is_none() {
            self.adopt_column_cursor();
        }
        true
    }

    fn begin_edit(&mut self, start: EditStart) -> anyhow::Result<()> {
        self.pending_num.clear();
        if !self.ready_to_edit() {
            return Ok(());
        }
        let cell = (self.cursor_row, self.cursor_col);
        let Some(current) = self
            .store
            .as_ref()
            .and_then(|s| s.cell_text(cell.0, cell.1))
        else {
            return Ok(());
        };
        self.edit_buf = match start {
            EditStart::Empty => String::new(),
            EditStart::Front | EditStart::End => current,
        };
        self.edit_cursor = match start {
            EditStart::Front => 0,
            EditStart::End | EditStart::Empty => self.edit_buf.chars().count(),
        };
        self.edit_cell = Some(cell);
        self.mode = AppMode::Edit;
        Ok(())
    }

    /// `x`: empty the cell under the cursor without opening the editor.
    fn clear_cell(&mut self) -> anyhow::Result<()> {
        self.pending_num.clear();
        if !self.ready_to_edit() {
            return Ok(());
        }
        let cell = (self.cursor_row, self.cursor_col);
        if let Some(store) = &mut self.store {
            store.edit([(cell, String::new())])?;
        }
        Ok(())
    }

    /// The selected block, in absolute coordinates.
    fn visual_range(&self) -> Option<Block> {
        self.block_from(self.visual_anchor?)
    }

    /// The block an operator acts on with no selection: the cursor, shaped
    /// exactly as `v` would shape a selection of one.
    fn cursor_block(&self) -> Option<Block> {
        self.block_from((self.cursor_row, self.cursor_col))
    }

    /// A block spanning `anchor` to the cursor. Its shape follows the
    /// selection mode: whole rows, whole columns, or a rectangle.
    fn block_from(&self, (anchor_row, anchor_col): (usize, usize)) -> Option<Block> {
        let store = self.store.as_ref()?;
        let rows = (
            anchor_row.min(self.cursor_row),
            anchor_row.max(self.cursor_row),
        );
        let cols = (
            anchor_col.min(self.cursor_col),
            anchor_col.max(self.cursor_col),
        );
        let all_rows = (0, store.row_count().saturating_sub(1));
        let all_cols = (0, store.column_count().saturating_sub(1));
        Some(match self.selection_mode {
            SelectionMode::Row => (rows, all_cols),
            SelectionMode::Column => (all_rows, cols),
            SelectionMode::Cell => (rows, cols),
        })
    }

    fn block_size(((r0, r1), (c0, c1)): Block) -> usize {
        (r1 - r0 + 1).saturating_mul(c1 - c0 + 1)
    }

    /// Every cell in a block, row by row.
    fn cells_in(((r0, r1), (c0, c1)): Block) -> impl Iterator<Item = (usize, usize)> {
        (r0..=r1).flat_map(move |row| (c0..=c1).map(move |col| (row, col)))
    }

    /// Whether plv will take on a block of this size, complaining if not.
    fn within_limit(&mut self, block: Block) -> bool {
        let size = Self::block_size(block);
        if size > MAX_BLOCK {
            self.message = Some(format!(
                "{size} cells is too many to handle at once (limit {MAX_BLOCK})"
            ));
            return false;
        }
        true
    }

    /// The selected block an editing operator is about to run on, once it is
    /// known to be one the edit buffer can hold.
    fn operable_range(&mut self) -> Option<Block> {
        self.pending_num.clear();
        if !self.ready_to_edit() {
            return None;
        }
        let block = self.visual_range()?;
        self.within_limit(block).then_some(block)
    }

    /// `y`: copy the selection — or the cursor, shaped by the mode — into the
    /// register. Reading only, so it works on views that refuse edits.
    fn yank(&mut self) -> anyhow::Result<()> {
        self.pending_num.clear();
        let block = match self.visual_anchor {
            Some(_) => self.visual_range(),
            None => self.cursor_block(),
        };
        let Some(block) = block.filter(|&b| self.within_limit(b)) else {
            return Ok(());
        };
        let Some(store) = self.store.as_ref() else {
            return Ok(());
        };
        self.register = store.block_text(block.0, block.1)?;

        let cells = Self::block_size(block);
        // As in vim, a visual yank leaves the cursor where the selection
        // began, so a paste can be aimed from a known place rather than from
        // wherever the selection happened to end.
        if let Some((row, col)) = self.visual_anchor.take() {
            self.cursor_col = col;
            self.cursor_to(row)?;
        }
        // And out to the system clipboard, so a block yanked here can be
        // pasted into a spreadsheet or a second plv. A terminal that will not
        // take it leaves the internal register untouched — the yank still
        // happened, it just did not travel.
        let shared = clipboard::copy(&clipboard::tsv(&self.register)).unwrap_or(false);
        self.message = Some(match shared {
            true => format!("yanked {cells} cells to the clipboard"),
            false => format!("yanked {cells} cells"),
        });
        Ok(())
    }

    /// `p`: write the register into the grid with its top-left at the cursor.
    ///
    /// Overwrites rather than inserting — a fixed grid has nowhere to push
    /// cells along to — and anything past the last row or column is dropped
    /// rather than silently wrapping.
    fn paste(&mut self) -> anyhow::Result<()> {
        self.pending_num.clear();
        if self.register.is_empty() {
            self.message = Some("nothing to paste".to_string());
            return Ok(());
        }
        // Taken out of the register first: the block being written and the
        // register are the same thing here, and the edit needs the store.
        let block = std::mem::take(&mut self.register);
        let result = self.paste_block(&block);
        self.register = block;
        result
    }

    /// Write `block` into the grid with its top-left at the cursor.
    fn paste_block(&mut self, block: &[Vec<String>]) -> anyhow::Result<()> {
        if !self.ready_to_edit() {
            return Ok(());
        }
        let Some(store) = self.store.as_ref() else {
            return Ok(());
        };
        let last_row = store.row_count().saturating_sub(1);
        let last_col = store.column_count().saturating_sub(1);

        let mut edits = Vec::new();
        let mut clipped = 0usize;
        for (down, row) in block.iter().enumerate() {
            for (across, value) in row.iter().enumerate() {
                let cell = (self.cursor_row + down, self.cursor_col + across);
                if cell.0 > last_row || cell.1 > last_col {
                    clipped += 1;
                } else {
                    edits.push((cell, value.clone()));
                }
            }
        }

        let pasted = edits.len();
        if let Some(store) = &mut self.store {
            store.edit(edits)?;
        }
        self.visual_anchor = None;
        self.message = Some(match clipped {
            0 => format!("pasted {pasted} cells"),
            n => format!("pasted {pasted} cells, {n} past the edge"),
        });
        Ok(())
    }

    /// `c`, `i` and `a` over a selection: type one value, apply it to every
    /// cell in the block.
    fn begin_fill(&mut self, mode: FillMode) -> anyhow::Result<()> {
        let Some(block) = self.operable_range() else {
            return Ok(());
        };
        self.edit_buf.clear();
        self.edit_cursor = 0;
        self.edit_cell = Some((self.cursor_row, self.cursor_col));
        self.edit_fill = Some(Fill { block, mode });
        self.mode = AppMode::Edit;
        Ok(())
    }

    /// `x` / `d` over a selection: empty every cell in it, as one undo step.
    fn clear_selection(&mut self) -> anyhow::Result<()> {
        let Some(block) = self.operable_range() else {
            return Ok(());
        };
        let edits: Vec<_> = Self::cells_in(block)
            .map(|cell| (cell, String::new()))
            .collect();
        let cleared = edits.len();
        if let Some(store) = &mut self.store {
            store.edit(edits)?;
        }
        self.visual_anchor = None;
        self.message = Some(format!("cleared {cleared} cells"));
        Ok(())
    }

    /// Strike out `count` rows from display position `first`.
    ///
    /// Nothing is removed from the file until `:w`; until then the rows are
    /// simply not shown, and `u` puts them back.
    fn delete_rows(&mut self, first: usize, count: usize) -> anyhow::Result<()> {
        self.pending_num.clear();
        let blocked = match &self.store {
            None => Some("no file open"),
            Some(store) => store.delete_blocked(),
        };
        if let Some(reason) = blocked {
            self.message = Some(reason.to_string());
            return Ok(());
        }

        let deleted = match &mut self.store {
            Some(store) => store.delete_rows(first..first + count)?,
            None => 0,
        };
        self.visual_anchor = None;

        // Everything below has moved up; the cursor may now be past the end.
        let last = self
            .store
            .as_ref()
            .map_or(0, |s| s.row_count().saturating_sub(1));
        if self.cursor_row > last {
            self.cursor_to(last)?;
        }
        self.message = Some(format!(
            "deleted {deleted} row{}",
            if deleted == 1 { "" } else { "s" }
        ));
        Ok(())
    }

    /// `o` and `O`: a new row below or above, ready to be typed into.
    ///
    /// Opens the editor on it straight away, as vim does — an empty row is
    /// only useful once something is in it.
    fn open_row(&mut self, below: bool) -> anyhow::Result<()> {
        self.pending_num.clear();
        let blocked = match &self.store {
            None => Some("no file open"),
            Some(store) => store.insert_blocked(),
        };
        if let Some(reason) = blocked {
            self.message = Some(reason.to_string());
            return Ok(());
        }

        let at = self.cursor_row;
        let landed = match &mut self.store {
            Some(store) => store.add_row(at, below)?,
            None => at,
        };
        self.visual_anchor = None;
        self.cursor_to(landed)?;

        // A row needs a column cursor to be typed into, the way a cell edit
        // does, and starts at the first column.
        if matches!(self.selection_mode, SelectionMode::Row) {
            self.selection_mode = SelectionMode::Cell;
        }
        self.cursor_col = 0;
        self.col_offset = 0;
        self.begin_edit(EditStart::Empty)
    }

    fn undo(&mut self) -> anyhow::Result<()> {
        self.pending_num.clear();
        let Some(store) = &mut self.store else {
            return Ok(());
        };
        if !store.undo()? {
            self.message = Some("nothing to undo".to_string());
        }
        Ok(())
    }

    fn redo(&mut self) -> anyhow::Result<()> {
        self.pending_num.clear();
        let Some(store) = &mut self.store else {
            return Ok(());
        };
        if !store.redo()? {
            self.message = Some("nothing to redo".to_string());
        }
        Ok(())
    }

    fn handle_edit_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Esc => self.end_edit(),
            KeyCode::Enter => {
                self.commit_edit()?;
                self.end_edit();
            }
            // Commit and step sideways, so a row can be filled in without
            // leaving the editor between cells.
            KeyCode::Tab => self.commit_and_step(1)?,
            KeyCode::BackTab => self.commit_and_step(-1)?,
            KeyCode::Left => self.edit_cursor = self.edit_cursor.saturating_sub(1),
            KeyCode::Right => {
                self.edit_cursor = (self.edit_cursor + 1).min(self.edit_buf.chars().count());
            }
            KeyCode::Home => self.edit_cursor = 0,
            KeyCode::End => self.edit_cursor = self.edit_buf.chars().count(),
            KeyCode::Backspace => {
                if self.edit_cursor > 0 {
                    self.edit_cursor -= 1;
                    self.remove_edit_char(self.edit_cursor);
                }
            }
            KeyCode::Delete => self.remove_edit_char(self.edit_cursor),
            KeyCode::Char(c) if !ctrl => {
                let at = self.edit_byte_index(self.edit_cursor);
                self.edit_buf.insert(at, c);
                self.edit_cursor += 1;
            }
            _ => {}
        }
        Ok(())
    }

    /// Put the typed value in the edit buffer. Nothing reaches the file
    /// until `:w`.
    fn commit_edit(&mut self) -> anyhow::Result<()> {
        let Some(cell) = self.edit_cell else {
            return Ok(());
        };
        let value = std::mem::take(&mut self.edit_buf);

        let edits = match self.edit_fill {
            // A fill writes every cell in the block, including any that
            // already hold the value: comparing first would mean reading rows
            // that are not on the page.
            Some(fill) => self.fill_edits(fill, &value)?,
            None => {
                // Retyping what was already there should not mark the file
                // dirty, and should not rewrite the field: the bytes on disk
                // may be formatted differently from what Polars renders.
                let unchanged = self
                    .store
                    .as_ref()
                    .and_then(|s| s.cell_text(cell.0, cell.1))
                    .is_some_and(|current| current == value);
                if unchanged {
                    return Ok(());
                }
                vec![(cell, value)]
            }
        };

        // Read the warning off the values actually about to be written, which
        // for a prepend or an append is the only place they exist.
        let warning = edits
            .iter()
            .find_map(|((_, col), written)| self.type_warning(*col, written));
        let filled = edits.len();
        if let Some(store) = &mut self.store {
            store.edit(edits)?;
        }
        self.visual_anchor = None;
        self.message = warning.or_else(|| (filled > 1).then(|| format!("filled {filled} cells")));
        Ok(())
    }

    /// Every cell the block operator will write, paired with its new value.
    ///
    /// `Replace` needs nothing from the file. `Prepend` and `Append` build on
    /// what each cell already holds, so they read the block first — including
    /// the rows below the viewport, which is why the size is capped before the
    /// editor ever opens.
    fn fill_edits(&self, fill: Fill, typed: &str) -> anyhow::Result<Vec<((usize, usize), String)>> {
        if fill.mode == FillMode::Replace {
            return Ok(Self::cells_in(fill.block)
                .map(|cell| (cell, typed.to_string()))
                .collect());
        }
        let Some(store) = self.store.as_ref() else {
            return Ok(Vec::new());
        };
        let ((first_row, _), (first_col, _)) = fill.block;
        let current = store.block_text(fill.block.0, fill.block.1)?;

        Ok(Self::cells_in(fill.block)
            .map(|(row, col)| {
                let existing = current
                    .get(row - first_row)
                    .and_then(|cells| cells.get(col - first_col))
                    .map_or("", String::as_str);
                ((row, col), fill.mode.combine(typed, existing))
            })
            .collect())
    }

    /// Commit the current cell and open the next one along, if there is one.
    fn commit_and_step(&mut self, delta: isize) -> anyhow::Result<()> {
        if self.edit_fill.is_some() {
            // A fill has no "next cell" to step to; commit it and stop.
            self.commit_edit()?;
            self.end_edit();
            return Ok(());
        }
        self.commit_edit()?;
        let last = self
            .store
            .as_ref()
            .map_or(0, |s| s.column_count().saturating_sub(1));
        let next = self.cursor_col as isize + delta;
        self.end_edit();
        if next < 0 || next as usize > last {
            return Ok(());
        }
        self.cursor_col = next as usize;
        self.begin_edit(EditStart::End)
    }

    /// Warn when a value will not read back as its column's type.
    ///
    /// A warning and not a refusal: the file is text, the types are Polars'
    /// inference over it, and the user may well mean it. But the column will
    /// come back as text next time the file is opened, which is worth saying
    /// out loud.
    fn type_warning(&self, col: usize, value: &str) -> Option<String> {
        if value.is_empty() {
            return None; // an empty field is a null, which any column takes
        }
        let (name, dtype) = self.store.as_ref()?.column_info(col)?;
        let fits = match &dtype {
            d if d.is_integer() => value.parse::<i64>().is_ok(),
            d if d.is_float() => value.parse::<f64>().is_ok(),
            DataType::Boolean => matches!(value, "true" | "false"),
            _ => true,
        };
        (!fits).then(|| format!("\"{value}\" is not {dtype} — column \"{name}\" becomes text"))
    }

    fn end_edit(&mut self) {
        self.mode = AppMode::Normal;
        self.edit_cell = None;
        self.edit_fill = None;
        self.edit_buf.clear();
        self.edit_cursor = 0;
    }

    /// Byte offset of the `n`th character of the edit buffer, or its end.
    fn edit_byte_index(&self, n: usize) -> usize {
        self.edit_buf
            .char_indices()
            .nth(n)
            .map_or(self.edit_buf.len(), |(i, _)| i)
    }

    fn remove_edit_char(&mut self, at: usize) {
        if at < self.edit_buf.chars().count() {
            let i = self.edit_byte_index(at);
            self.edit_buf.remove(i);
        }
    }

    // ── ex commands ───────────────────────────────────────────────────────

    fn handle_command_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Esc => {
                self.mode = AppMode::Normal;
                self.command_buf.clear();
                self.forget_completion();
            }
            KeyCode::Enter => {
                let line = std::mem::take(&mut self.command_buf);
                self.mode = AppMode::Normal;
                self.forget_completion();
                self.run_command(line.trim())?;
            }
            KeyCode::Backspace => {
                self.forget_completion();
                if self.command_buf.pop().is_none() {
                    // Backspacing off the `:` leaves the command line, as in vim.
                    self.mode = AppMode::Normal;
                }
            }
            KeyCode::Tab => return self.complete_command(false),
            KeyCode::BackTab => return self.complete_command(true),
            KeyCode::Char(c) if !ctrl => {
                self.command_buf.push(c);
                self.forget_completion();
            }
            _ => {}
        }
        Ok(())
    }

    /// Tab on the command line: extend as far as the candidates agree, then
    /// step through them.
    ///
    /// Extending first is what makes it predictable — the line only ever grows
    /// towards something real. Stepping is what makes it useful once the
    /// common prefix has run out, which for column names is most of the time.
    fn complete_command(&mut self, backwards: bool) -> anyhow::Result<()> {
        if let Some(completion) = &self.completion
            && completion.options.len() > 1
        {
            let count = completion.options.len();
            let next = match self.completion_index {
                Some(index) if backwards => (index + count - 1) % count,
                Some(index) => (index + 1) % count,
                None if backwards => count - 1,
                None => 0,
            };
            self.command_buf = completion.with(next);
            self.completion_index = Some(next);
            return Ok(());
        }

        let Some(store) = &self.store else {
            return Ok(());
        };
        let Some(found) = complete::complete(&self.command_buf, &store.schema) else {
            self.forget_completion();
            return Ok(());
        };
        self.command_buf = found.extended();
        self.completion_index = None;
        // A single candidate has been applied in full; there is nothing left
        // to show or to step through.
        self.completion = (found.options.len() > 1).then_some(found);
        Ok(())
    }

    fn forget_completion(&mut self) {
        self.completion = None;
        self.completion_index = None;
    }

    /// `w` writes the buffer and `q` quits; a trailing `!` forces past the
    /// guard each of them puts up.
    fn run_command(&mut self, line: &str) -> anyhow::Result<()> {
        let (word, rest) = match line.split_once(char::is_whitespace) {
            Some((word, rest)) => (word, rest.trim()),
            None => (line, ""),
        };
        let force = word.ends_with('!');
        let path = (!rest.is_empty()).then(|| PathBuf::from(rest));

        match word.trim_end_matches('!') {
            "" => {}
            "w" => {
                self.write(path.as_deref(), force)?;
            }
            "wq" | "x" => {
                if self.write(path.as_deref(), force)? {
                    self.exit = true;
                }
            }
            "q" => self.quit(force),
            // Anything else is the view language, which reports its own
            // unknown-command error against the word that caused it.
            _ => self.run_view_command(line)?,
        }
        Ok(())
    }

    /// `:select`, `:hide`, `:filter`, `:sort`, `:reset`.
    ///
    /// Parsed and checked against the schema first, then tried on the frame:
    /// a view that will not collect is refused rather than adopted, so one
    /// mistyped command cannot leave the viewer showing an error.
    fn run_view_command(&mut self, line: &str) -> anyhow::Result<()> {
        let Some(store) = &self.store else {
            self.message = Some("no file open".to_string());
            return Ok(());
        };
        let command = match view::parse(line, &store.schema) {
            Ok(command) => command,
            Err(e) => {
                self.message = Some(e.message);
                return Ok(());
            }
        };
        self.apply_view_command(command)
    }

    /// Adopt a view command, whether it was typed on the `:` line or came
    /// from a key.
    ///
    /// Split out so `-` is genuinely the command it looks like rather than a
    /// second way to narrow the view: one path decides what a new view costs,
    /// refuses the ones that will not collect, and puts the cursor back.
    fn apply_view_command(&mut self, command: view::Command) -> anyhow::Result<()> {
        let Some(store) = &self.store else {
            self.message = Some("no file open".to_string());
            return Ok(());
        };

        // Whether the row set has to be rebuilt is a property of the command,
        // not of the state it produces: `:select` leaves a filter's matches
        // exactly as they were, and rescanning the file to rediscover that
        // would throw away the whole point of resolving it once.
        let refiltered = matches!(
            command,
            view::Command::Filter(_)
                | view::Command::Reset(None)
                | view::Command::Reset(Some(view::Slot::Filter))
        );

        // Expanding writes to no slot of the view: it changes which columns
        // exist, which is the store's business. Handled here rather than in
        // `View::apply`, which is about what is on show.
        if let view::Command::Expand(cols) = &command {
            let cols = cols.clone();
            let sorted = !store.view.sort.is_empty();
            let mut said = Vec::new();
            for col in cols {
                let Some(store) = &mut self.store else { break };
                match store.expand(col) {
                    Ok(note) => said.push(note),
                    Err(e) => said.push(e.to_string()),
                }
            }
            self.message = Some(said.join("; "));
            // The held frame was built against the old schema, so a sorted
            // view has to be rebuilt against the new one.
            if sorted {
                self.rebuild_view();
            }
            self.after_view_change(false)?;
            return Ok(());
        }

        // Asked before the key is recorded, so a refusal leaves the view as
        // it was rather than in an order nothing can produce.
        if let view::Command::Sort(keys) = &command
            && !keys.is_empty()
            && let Some(reason) = store.sort_blocked()
        {
            self.message = Some(reason);
            return Ok(());
        }

        let mut next = store.view.clone();
        let sort_before = next.sort.clone();
        if let Err(e) = next.apply(command, store.schema.len()) {
            self.message = Some(e);
            return Ok(());
        }
        let reordered = next.sort != sort_before;

        if let Some(store) = &mut self.store
            && let Err(e) = store.apply_view(next)
        {
            self.message = Some(e.to_string());
            return Ok(());
        }
        if reordered || refiltered {
            self.rebuild_view();
        }
        self.after_view_change(reordered || refiltered)?;
        Ok(())
    }

    /// Rebuild whatever backs the view, after a sort or a filter changed.
    ///
    /// The two are never both running. A held sort has the whole table in
    /// memory and applies the filter as part of building it, so a row-set scan
    /// would be re-reading a file that is already read. Without a sort the
    /// scan is the cheaper answer, because it never materialises anything.
    fn rebuild_view(&mut self) {
        // Dropping the receivers cancels whatever was still running.
        self.sort_rx = None;
        self.filter_rx = None;
        let Some(store) = &mut self.store else {
            return;
        };
        if store.view.sort.is_empty() {
            match store.begin_filter() {
                Ok(rx) => self.filter_rx = rx,
                Err(e) => self.message = Some(e.to_string()),
            }
        } else {
            self.sort_rx = Some(store.resort());
        }
    }

    /// Put the cursor back inside a view that may have fewer columns, and drop
    /// whatever was keyed to the old numbering.
    fn after_view_change(&mut self, reordered: bool) -> anyhow::Result<()> {
        let last = self
            .store
            .as_ref()
            .map_or(0, |s| s.column_count().saturating_sub(1));
        self.cursor_col = self.cursor_col.min(last);
        self.col_offset = self.col_offset.min(last);

        // A selection, and a search's match rows and scoped column, all refer
        // to the view that has just been replaced.
        self.visual_anchor = None;
        self.search_state = None;
        self.search_rx = None;

        if reordered {
            // The rows are in a different order, so the cursor's row number no
            // longer means what it did.
            self.cursor_to(0)?;
        }
        Ok(())
    }

    /// Returns whether the write happened; `:wq` only quits if it did.
    fn write(&mut self, dst: Option<&Path>, force: bool) -> anyhow::Result<bool> {
        let Some(store) = &mut self.store else {
            self.message = Some("no file open".to_string());
            return Ok(false);
        };
        match store.save(dst, force) {
            Ok(path) => {
                let name = path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("file")
                    .to_string();
                self.message = Some(format!("wrote {name}"));
                Ok(true)
            }
            Err(e) => {
                self.message = Some(e.to_string());
                Ok(false)
            }
        }
    }

    /// Quitting refuses while the buffer holds unwritten edits.
    fn quit(&mut self, force: bool) {
        let dirty = self.store.as_ref().map_or(0, |s| s.dirty());
        if dirty > 0 && !force {
            self.message = Some(format!(
                "{dirty} unsaved edit{} — :w to write, :q! to discard",
                if dirty == 1 { "" } else { "s" }
            ));
            return;
        }
        self.exit = true;
    }

    /// The second key of a `g` or `z` sequence. Anything else cancels it.
    fn resolve_prefix(&mut self, prefix: char, code: KeyCode) -> anyhow::Result<()> {
        // The second key is read case-insensitively. Every `z` width command
        // takes a shifted key — `<`, `>`, `_` — and the shift naturally goes
        // down before the `z` does, so both keys arrive capitalised.
        let code = match code {
            KeyCode::Char(c) => KeyCode::Char(c.to_ascii_lowercase()),
            other => other,
        };
        match (prefix, code) {
            ('z', KeyCode::Char('z')) => self.scroll_center(),
            ('z', KeyCode::Char('t')) => self.scroll_cursor_top(),
            ('z', KeyCode::Char('b')) => self.scroll_cursor_bottom(),
            // Column widths. `z` is where display adjustments live, here as in
            // vim, and a width is one: it changes how the table is drawn and
            // nothing about the data.
            ('z', KeyCode::Char('>')) => self.resize_column(1),
            ('z', KeyCode::Char('<')) => self.resize_column(-1),
            ('z', KeyCode::Char('_')) => self.fit_column(),
            ('z', KeyCode::Char('p')) => self.toggle_pin(),
            // The strip above the status bar. It lives in the `z` family
            // because it is display state of exactly that kind: it stays on,
            // it takes its rows out of the table, and it changes nothing
            // about which rows and columns are being asked for. `K` is the
            // window, which covers rather than displaces.
            ('z', KeyCode::Char('k')) => {
                self.adopt_column_cursor();
                self.cell_view = !self.cell_view;
                Ok(())
            }
            // Unpinning the lot is `z|` and not `zP`, because the second key
            // is lowercased above: a shifted letter cannot mean anything the
            // unshifted one does not. The divider is what a pin draws, so the
            // key names the thing it takes away.
            ('z', KeyCode::Char('|')) => {
                self.pinned.clear();
                Ok(())
            }
            ('z', KeyCode::Char('=')) => {
                self.widths.clear();
                self.message = Some("column widths reset".to_string());
                Ok(())
            }
            // `gg` is the first row, or the nth when a count precedes it.
            // `dd` takes out the cursor row, `{n}dd` that many.
            ('d', KeyCode::Char('d')) => {
                let count = self.take_count(1);
                self.delete_rows(self.cursor_row, count)
            }
            ('g', KeyCode::Char('g')) => {
                if self.pending_num.is_empty() {
                    self.cursor_to(0)
                } else {
                    let count = std::mem::take(&mut self.pending_num);
                    self.jump_to_line(&count)
                }
            }
            _ => {
                self.pending_num.clear();
                Ok(())
            }
        }
    }

    /// `Ctrl+d`/`Ctrl+u` and `Ctrl+f`/`Ctrl+b`: a screen or half of one, view
    /// and cursor together.
    ///
    /// vim moves both, keeping the cursor at the same height in the window,
    /// rather than walking the cursor down until it falls off the edge — so
    /// the view moves even when the cursor had room to spare. (The commands
    /// that scroll the view and leave the cursor behind are `Ctrl+e` and
    /// `Ctrl+y`, which plv does not have.)
    ///
    /// Against the ends of the file the view runs out of room first; the
    /// cursor then carries on alone, as it does in vim.
    fn scroll_page(&mut self, down: bool, page: Page) -> anyhow::Result<()> {
        let Some(store) = &self.store else {
            return Ok(());
        };
        let viewport = store.viewport_rows.max(1);
        let step = match page {
            Page::Half => (viewport / 2).max(1),
            Page::Whole => viewport.max(1),
        };
        let last_row = store.row_count().saturating_sub(1);
        let offset = store.row_offset;
        let height_in_view = self.cursor_row.saturating_sub(offset);

        let new_offset = if down {
            (offset + step).min(store.row_count().saturating_sub(viewport))
        } else {
            offset.saturating_sub(step)
        };

        if let Some(store) = &mut self.store {
            store.scroll_to_offset(new_offset)?;
        }
        let settled = self.store.as_ref().map_or(0, |s| s.row_offset);

        self.cursor_row = if settled == offset {
            // The view could not move, so only the cursor does.
            if down {
                (self.cursor_row + step).min(last_row)
            } else {
                self.cursor_row.saturating_sub(step)
            }
        } else {
            (settled + height_in_view).min(last_row)
        };
        Ok(())
    }

    // ── cursor + scroll helpers ────────────────────────────────────────────

    /// Move cursor to `row` (0-based), scrolling the viewport only if needed.
    fn cursor_to(&mut self, row: usize) -> anyhow::Result<()> {
        let (total, vp, offset) = match &self.store {
            Some(s) => (s.row_count(), s.viewport_rows, s.row_offset),
            None => return Ok(()),
        };
        if total == 0 {
            return Ok(());
        }
        let row = row.min(total - 1);
        self.cursor_row = row;

        let new_offset = if row < offset {
            row
        } else if row >= offset + vp {
            (row + 1).saturating_sub(vp)
        } else {
            return Ok(()); // already visible
        };

        if let Some(s) = &mut self.store {
            s.scroll_to_offset(new_offset)?;
        }
        Ok(())
    }

    fn cursor_down(&mut self, n: usize) -> anyhow::Result<()> {
        let total = self.store.as_ref().map_or(0, |s| s.row_count());
        if total == 0 {
            return Ok(());
        }
        let new_row = (self.cursor_row + n).min(total - 1);
        self.cursor_to(new_row)
    }

    fn cursor_up(&mut self, n: usize) -> anyhow::Result<()> {
        self.cursor_to(self.cursor_row.saturating_sub(n))
    }

    /// zz — scroll so the cursor is vertically centered.
    fn scroll_center(&mut self) -> anyhow::Result<()> {
        let (total, vp) = match &self.store {
            Some(s) => (s.row_count(), s.viewport_rows),
            None => return Ok(()),
        };
        let offset = self
            .cursor_row
            .saturating_sub(vp / 2)
            .min(total.saturating_sub(vp));
        if let Some(s) = &mut self.store {
            s.scroll_to_offset(offset)?;
        }
        Ok(())
    }

    /// zt — scroll so the cursor is at the top of the viewport.
    fn scroll_cursor_top(&mut self) -> anyhow::Result<()> {
        if let Some(s) = &mut self.store {
            s.scroll_to_offset(self.cursor_row)?;
        }
        Ok(())
    }

    /// zb — scroll so the cursor is at the bottom of the viewport.
    fn scroll_cursor_bottom(&mut self) -> anyhow::Result<()> {
        let (total, vp) = match &self.store {
            Some(s) => (s.row_count(), s.viewport_rows),
            None => return Ok(()),
        };
        let offset = self
            .cursor_row
            .saturating_sub(vp.saturating_sub(1))
            .min(total.saturating_sub(vp));
        if let Some(s) = &mut self.store {
            s.scroll_to_offset(offset)?;
        }
        Ok(())
    }

    /// Parse a buffered number string and jump to that 1-based line number.
    fn jump_to_line(&mut self, num_str: &str) -> anyhow::Result<()> {
        let total = self.store.as_ref().map_or(0, |s| s.row_count());
        match num_str.parse::<usize>() {
            Ok(0) => {
                self.message = Some(format!("Invalid line: 0  (valid: 1–{total})"));
            }
            Ok(n) if n > total => {
                self.message = Some(format!("Line {n} out of range  (file has {total} rows)"));
            }
            Ok(n) => self.cursor_to(n - 1)?,
            Err(_) => {
                self.message = Some(format!("Not a valid line number: \"{num_str}\""));
            }
        }
        Ok(())
    }

    /// Consume the pending numeric prefix, returning `default` if empty.
    fn take_count(&mut self, default: usize) -> usize {
        if self.pending_num.is_empty() {
            default
        } else {
            let n = self.pending_num.parse::<usize>().unwrap_or(default);
            self.pending_num.clear();
            n.max(1)
        }
    }

    /// Compute the `col_offset` that places `cursor_col` at the rightmost
    /// visible position in the current terminal width.
    ///
    /// Mirrors the Phase-1 width logic in `DataTable::render` (no redistribution
    /// needed — only visibility matters here).
    fn col_offset_to_show_at_right(&self, cursor_col: usize) -> usize {
        match &self.store {
            Some(store) => ui::col_offset_showing(
                &store.current_view,
                store.row_offset,
                self.last_frame_width,
                cursor_col,
                &self.widths,
                &self.display_pins(),
            ),
            None => 0,
        }
    }

    /// `h`: `n` columns left, or `n` columns of scroll in row mode.
    fn column_left(&mut self, n: usize) {
        match self.selection_mode {
            SelectionMode::Row => self.col_offset = self.col_offset.saturating_sub(n),
            SelectionMode::Column | SelectionMode::Cell => {
                self.cursor_col = self.cursor_col.saturating_sub(n);
                if !self.display_pins().contains(&self.cursor_col) {
                    self.col_offset = self.col_offset.min(self.cursor_col);
                }
            }
        }
    }

    /// `l`: `n` columns right, stopping at the last column — or, in row mode,
    /// where the last column reaches the right edge.
    ///
    /// The cursor modes only set the cursor; `draw` brings `col_offset` along
    /// if that has taken it out of view. Nudging the offset by hand here was
    /// only ever right for a single step.
    fn column_right(&mut self, n: usize) {
        match self.selection_mode {
            SelectionMode::Row => {
                self.col_offset = (self.col_offset + n).min(self.max_col_offset());
            }
            SelectionMode::Column | SelectionMode::Cell => {
                let last = self
                    .store
                    .as_ref()
                    .map_or(0, |s| s.column_count().saturating_sub(1));
                self.cursor_col = (self.cursor_col + n).min(last);
            }
        }
    }

    // ── the column picker ─────────────────────────────────────────────────

    /// `C`: open the list of every column, ticked for shown and pinned.
    fn open_picker(&mut self) {
        let Some(store) = &self.store else {
            return;
        };
        let names: Vec<String> = store
            .schema
            .iter_names()
            .map(|name| name.to_string())
            .collect();
        let order = store.view.columns(names.len());
        self.picker = Some(Picker::new(names, order, self.pinned.clone()));
        self.mode = AppMode::Picker;
    }

    fn close_picker(&mut self) {
        self.picker = None;
        self.mode = AppMode::Normal;
    }

    fn handle_picker_key(&mut self, key: KeyEvent) -> anyhow::Result<()> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        // Read before the picker is borrowed: a half page is a fact about the
        // screen, which the picker does not know.
        let half = self.last_vp as isize / 2;
        let Some(picker) = &mut self.picker else {
            self.mode = AppMode::Normal;
            return Ok(());
        };
        let len = picker.len();

        match key.code {
            // `q` is deliberately not bound. Everywhere else in vim it closes
            // a window, and a window is a view — closing one never destroys
            // work. The picker holds unapplied changes, so it cannot close
            // harmlessly, and borrowing the letter for something that throws
            // twenty toggles away is what makes `q` mean two things. `Esc`
            // discards, as it discards a half-typed `:` line.
            KeyCode::Esc => self.close_picker(),
            KeyCode::Enter => return self.apply_picker(),
            KeyCode::Char('j') | KeyCode::Down => picker.state.move_by(1, len),
            KeyCode::Char('k') | KeyCode::Up => picker.state.move_by(-1, len),
            KeyCode::Char('d') if ctrl => picker.state.move_by(half, len),
            KeyCode::Char('u') if ctrl => picker.state.move_by(-half, len),
            KeyCode::Char('g') | KeyCode::Home => picker.state.go_to(0, len),
            KeyCode::Char('G') | KeyCode::End => picker.state.go_to(len.saturating_sub(1), len),
            // `-` and not Space, so the key that takes a column off the view
            // is the same one in here as it is out there. In the table it can
            // only hide, since there is nothing on screen to un-hide; in the
            // list the state is in front of you, so it toggles.
            KeyCode::Char('-') => {
                if let Err(refusal) = picker.toggle_shown() {
                    self.message = Some(refusal);
                }
            }
            KeyCode::Char('p') => picker.toggle_pinned(),
            // Bulk over the whole list. Picking four columns out of two
            // hundred means starting from none, and unticking 196 by hand is
            // not a thing anyone will do.
            KeyCode::Char('a') => picker.show_all(),
            KeyCode::Char('A') => picker.show_only_cursor(),
            _ => {}
        }
        Ok(())
    }

    /// `Enter`: adopt what the picker holds.
    ///
    /// The selection goes through `apply_view_command` like every other way of
    /// narrowing the view, so the picker is a way of *writing* a `:select`
    /// rather than a second mechanism that decides what shows.
    fn apply_picker(&mut self) -> anyhow::Result<()> {
        let Some(picker) = self.picker.take() else {
            self.mode = AppMode::Normal;
            return Ok(());
        };
        self.mode = AppMode::Normal;

        let select = picker.selection();
        if select.is_empty() {
            // `toggle_shown` will not let it get here, and `View::apply` would
            // refuse it as well. Belt and braces, because the alternative is a
            // view with nothing in it.
            self.message = Some("that would hide every column".to_string());
            return Ok(());
        }
        self.apply_view_command(view::Command::Select(select))?;
        self.adopt_pins(picker.pins());
        Ok(())
    }

    /// Take the picker's pins, dropping any the screen has no room for.
    ///
    /// Trimmed rather than refused whole. The view change is what the user
    /// came for, and giving it up over a pin that does not fit would be
    /// abandoning the wrong half — so it keeps what fits and says what it
    /// could not take, the way a filter that fills its row set keeps what it
    /// has and reads `(first n)` rather than looking like the whole answer.
    ///
    /// Dropped from the right, because a pin is usually set on something that
    /// belongs at the left edge, and the leftmost is the one most likely meant.
    fn adopt_pins(&mut self, wanted: std::collections::BTreeSet<usize>) {
        self.pinned = wanted;
        let mut dropped = 0;
        while !self.pins_fit() {
            let Some(&rightmost) = self.display_pins().iter().next_back() else {
                break;
            };
            let Some(source) = self
                .store
                .as_ref()
                .and_then(|store| store.source_column(rightmost))
            else {
                break;
            };
            self.pinned.remove(&source);
            dropped += 1;
        }
        if dropped > 0 {
            self.message = Some(format!("no room for {dropped} of the pins"));
        }
    }

    /// Whether what is pinned still leaves room to scroll in.
    fn pins_fit(&self) -> bool {
        match &self.store {
            Some(store) => ui::pin_fits(
                &store.current_view,
                store.row_offset,
                self.last_frame_width,
                &self.widths,
                &self.display_pins(),
            ),
            None => true,
        }
    }

    /// `-`: take the cursor column off the view.
    ///
    /// Sugar for typing `:hide <name>`, and deliberately nothing more: it
    /// writes the slot `:select` writes, through the same `apply` that a
    /// typed line goes through, so there is one answer to which columns show
    /// rather than two that can disagree. `:hide` already reads the current
    /// list and filters it, so pressing this twice narrows twice — where a
    /// second `:select` would replace the first.
    ///
    /// The cursor is left where the column was, on whatever has moved into
    /// that position, as `dd` leaves it on the next row. That falls out of
    /// the clamp in `after_view_change` and needs nothing here.
    fn hide_column(&mut self) -> anyhow::Result<()> {
        let Some(store) = &self.store else {
            return Ok(());
        };
        let Some(source) = store.source_column(self.cursor_col) else {
            return Ok(());
        };
        let name = store
            .current_view
            .columns()
            .get(self.cursor_col)
            .map(|column| column.name().to_string());

        self.apply_view_command(view::Command::Hide(vec![source]))?;

        // Say how to get it back. There is no key that un-hides one column —
        // naming it is the only way to say which — so the way back has to be
        // in front of the user at the moment they might want it.
        if let Some(name) = name
            && self.message.is_none()
        {
            self.message = Some(format!("hid {name} — :reset select brings it back"));
        }
        Ok(())
    }

    /// Widen or narrow the cursor column by `steps`, each of a few characters.
    ///
    /// Columns after it are pushed along and off the right edge rather than
    /// squeezed, which is what a spreadsheet does and what `h`/`l` are for.
    fn resize_column(&mut self, steps: isize) -> anyhow::Result<()> {
        const STEP: isize = 4;
        let Some(source) = self
            .store
            .as_ref()
            .and_then(|store| store.source_column(self.cursor_col))
        else {
            return Ok(());
        };
        let current = match self.widths.get(&source) {
            Some(&width) => width as isize,
            None => self.drawn_width(source) as isize,
        };
        let want = (current + steps * STEP).max(ui::MIN_COLUMN as isize) as usize;
        self.widths.insert(source, want);
        Ok(())
    }

    /// Fit the cursor column to the widest value **on screen**.
    ///
    /// On screen and not in the file: the whole column is not in memory, and
    /// reading it to measure would be the full scan the rest of plv works to
    /// avoid.
    fn fit_column(&mut self) -> anyhow::Result<()> {
        let Some(store) = &self.store else {
            return Ok(());
        };
        let Some(source) = store.source_column(self.cursor_col) else {
            return Ok(());
        };
        let Some(column) = store.current_view.columns().get(self.cursor_col) else {
            return Ok(());
        };
        let widest = ui::natural_width(column);
        self.widths.insert(source, widest);
        Ok(())
    }

    /// The pins as display positions.
    ///
    /// `Store`'s indices are source columns and everything above it counts
    /// display positions, so the crossing happens here and the widget is
    /// handed a set it can use against the frame it is drawing. A pin on a
    /// column the current view hides simply is not in the set — it is not
    /// forgotten, it has nowhere to be drawn.
    fn display_pins(&self) -> ui::Pinned {
        let Some(store) = &self.store else {
            return ui::Pinned::new();
        };
        (0..store.column_count())
            .filter(|&display| {
                store
                    .source_column(display)
                    .is_some_and(|source| self.pinned.contains(&source))
            })
            .collect()
    }

    /// `zp`: hold the cursor column at the left edge, or let it go again.
    ///
    /// The use is comparison: a key or a label stays in sight while `h` and
    /// `l` walk the columns it is being read against, which on a wide table
    /// otherwise means scrolling back and forth and holding a value in your
    /// head.
    fn toggle_pin(&mut self) -> anyhow::Result<()> {
        let Some(source) = self
            .store
            .as_ref()
            .and_then(|store| store.source_column(self.cursor_col))
        else {
            return Ok(());
        };
        if self.pinned.remove(&source) {
            return Ok(());
        }

        // Set the pin, then ask the layout whether what it makes still leaves
        // room to scroll in, and take it back if not. Asking after rather than
        // predicting before means the check sees the block that would actually
        // be drawn, widths set by hand and all.
        self.pinned.insert(source);
        if !self.pins_fit() {
            self.pinned.remove(&source);
            self.message = Some("no room to pin: unpin one, or narrow one with z<".into());
        }
        Ok(())
    }

    /// What the cursor column is drawn at right now.
    fn drawn_width(&self, source: usize) -> usize {
        self.store
            .as_ref()
            .and_then(|store| store.current_view.columns().get(self.cursor_col))
            .map(|column| ui::drawn_width(column, source, self.last_frame_width, &self.widths))
            .unwrap_or(ui::MIN_COLUMN)
    }

    /// The column the status bar names.
    ///
    /// Row mode has no column cursor, so it reports the leftmost visible
    /// column — which is exactly what `h` and `l` move there. The other modes
    /// move a cursor, so the readout follows that instead. Either way the
    /// number moves when the keys that move sideways are pressed.
    fn col_position(&self) -> usize {
        match self.selection_mode {
            SelectionMode::Row => self.col_offset,
            _ => self.cursor_col,
        }
    }

    /// The furthest right the view can scroll: the offset that leaves the last
    /// column at the right edge. Going past it pads the view with empty space
    /// instead of data, which is what row mode used to do.
    fn max_col_offset(&self) -> usize {
        let last = self
            .store
            .as_ref()
            .map_or(0, |s| s.column_count().saturating_sub(1));
        self.col_offset_to_show_at_right(last)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE: &str = "name,count\na,1\nb,2\nc,3\n";

    fn app_with(name: &str, contents: &str) -> (App, PathBuf) {
        let dir = std::env::temp_dir().join("plv-app-tests");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(name);
        std::fs::write(&path, contents).unwrap();
        let mut app = App::new(Some(path.clone()));
        app.store = Some(Store::open_file(&path, 10).unwrap());
        (app, path)
    }

    fn key(app: &mut App, event: impl IntoKeyEvent) {
        app.handle_key_event(event.into_key_event()).unwrap();
    }

    /// So a test can press a plain key or one with modifiers.
    trait IntoKeyEvent {
        fn into_key_event(self) -> KeyEvent;
    }
    impl IntoKeyEvent for KeyCode {
        fn into_key_event(self) -> KeyEvent {
            KeyEvent::new(self, KeyModifiers::NONE)
        }
    }
    impl IntoKeyEvent for KeyEvent {
        fn into_key_event(self) -> KeyEvent {
            self
        }
    }

    fn press(app: &mut App, c: char) {
        key(app, KeyCode::Char(c));
    }

    fn typed(app: &mut App, text: &str) {
        for c in text.chars() {
            press(app, c);
        }
    }

    /// Run an ex command the way a user would: `:`, the text, Enter.
    fn command(app: &mut App, line: &str) {
        press(app, ':');
        typed(app, line);
        key(app, KeyCode::Enter);
    }

    fn shown(app: &App, col: usize, row: usize) -> Option<String> {
        app.store.as_ref()?.cell_text(row, col)
    }

    #[test]
    fn typing_a_cell_and_writing_it_reaches_the_file() {
        let (mut app, path) = app_with("edit.csv", SAMPLE);

        press(&mut app, 'i');
        assert!(matches!(app.mode, AppMode::Edit));
        // Row mode has no column cursor, so an edit adopts one.
        assert_eq!(app.selection_mode, SelectionMode::Cell);
        // `i` keeps the value it found.
        assert_eq!(app.edit_buf, "a");

        typed(&mut app, "bc");
        key(&mut app, KeyCode::Enter);
        assert!(matches!(app.mode, AppMode::Normal));
        // `i` inserts before the character the caret is on, as in vim.
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("bca"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 1);
        // Nothing has touched the file yet.
        assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLE);

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\nbca,1\nb,2\nc,3\n"
        );
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
    }

    #[test]
    fn i_and_a_put_the_caret_at_opposite_ends() {
        let (mut app, _) = app_with("caret.csv", SAMPLE);

        press(&mut app, 'i');
        assert_eq!(app.edit_cursor, 0);
        typed(&mut app, "x");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("xa"));

        press(&mut app, 'a');
        assert_eq!(app.edit_buf, "xa");
        assert_eq!(app.edit_cursor, 2);
        typed(&mut app, "z");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("xaz"));
    }

    #[test]
    fn c_replaces_the_value_and_escape_abandons_it() {
        let (mut app, _) = app_with("abandon.csv", SAMPLE);

        press(&mut app, 'c');
        assert_eq!(app.edit_buf, "", "c starts from an empty field");
        typed(&mut app, "gone");
        key(&mut app, KeyCode::Esc);

        assert!(matches!(app.mode, AppMode::Normal));
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("a"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
    }

    #[test]
    fn x_clears_a_cell_and_u_takes_it_back() {
        let (mut app, _) = app_with("clear.csv", SAMPLE);

        press(&mut app, 'x');
        assert_eq!(shown(&app, 0, 0).as_deref(), Some(""));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 1);

        press(&mut app, 'u');
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("a"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);

        press(&mut app, 'u');
        assert_eq!(app.message.as_deref(), Some("nothing to undo"));
    }

    #[test]
    fn retyping_the_same_value_is_not_an_edit() {
        let (mut app, _) = app_with("noop.csv", SAMPLE);

        press(&mut app, 'i');
        key(&mut app, KeyCode::Enter);
        assert_eq!(
            app.store.as_ref().unwrap().dirty(),
            0,
            "an unchanged cell must not dirty the file"
        );
    }

    #[test]
    fn a_value_that_breaks_the_column_type_warns_but_is_still_taken() {
        let (mut app, _) = app_with("warn.csv", SAMPLE);

        // Move to the numeric column, then replace its value with text.
        press(&mut app, 'i');
        key(&mut app, KeyCode::Esc);
        press(&mut app, 'l');
        press(&mut app, 'c');
        typed(&mut app, "n/a");
        key(&mut app, KeyCode::Enter);

        let message = app.message.clone().expect("a type mismatch should warn");
        assert!(message.contains("becomes text"), "{message}");
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("n/a"));
    }

    #[test]
    fn tab_commits_and_moves_along_the_row() {
        let (mut app, _) = app_with("tab.csv", SAMPLE);

        press(&mut app, 'c');
        typed(&mut app, "first");
        key(&mut app, KeyCode::Tab);

        assert!(matches!(app.mode, AppMode::Edit), "still editing");
        assert_eq!(app.cursor_col, 1);
        assert_eq!(app.edit_buf, "1", "the next cell's value is loaded");

        typed(&mut app, "0");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("first"));
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("10"));
    }

    #[test]
    fn tab_off_the_last_column_leaves_the_editor() {
        let (mut app, _) = app_with("tabend.csv", SAMPLE);

        press(&mut app, 'i');
        key(&mut app, KeyCode::Esc);
        press(&mut app, 'l');
        press(&mut app, 'c');
        typed(&mut app, "9");
        key(&mut app, KeyCode::Tab);

        assert!(matches!(app.mode, AppMode::Normal));
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("9"));
    }

    #[test]
    fn quitting_refuses_while_edits_are_unwritten() {
        let (mut app, _) = app_with("quit.csv", SAMPLE);
        press(&mut app, 'x');

        press(&mut app, 'q');
        assert!(!app.exit);
        let message = app.message.clone().unwrap();
        assert!(message.contains("1 unsaved edit"), "{message}");

        command(&mut app, "q");
        assert!(!app.exit, ":q is guarded too");

        command(&mut app, "q!");
        assert!(app.exit);
    }

    #[test]
    fn wq_writes_before_quitting_and_stays_put_when_the_write_fails() {
        let (mut app, path) = app_with("wq.csv", SAMPLE);
        press(&mut app, 'x');

        // Something else rewrites the file underneath the buffer.
        std::fs::write(&path, "name,count\nz,9\n").unwrap();
        command(&mut app, "wq");
        assert!(!app.exit, "a refused write must not quit");
        assert!(app.message.clone().unwrap().contains("changed on disk"));

        // Putting the original bytes back does not restore the timestamp, so
        // the buffer is still looking at a file it no longer recognises.
        std::fs::write(&path, SAMPLE).unwrap();
        command(&mut app, "wq");
        assert!(!app.exit, "same bytes, new mtime — still guarded");

        command(&mut app, "wq!");
        assert!(app.exit);
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\n,1\nb,2\nc,3\n"
        );
    }

    /// Tab cycles Row → Column → Cell.
    fn cell_mode(app: &mut App) {
        key(app, KeyCode::Tab);
        key(app, KeyCode::Tab);
        assert_eq!(app.selection_mode, SelectionMode::Cell);
    }

    /// Eight narrow columns: more than fit, so scrolling has somewhere to go.
    const WIDE: &str = "a,b,c,d,e,f,g,h\n1,2,3,4,5,6,7,8\n";

    /// `last_frame_width` is normally set by `draw`, which tests do not run.
    fn app_sized(name: &str, contents: &str, width: u16) -> App {
        let (mut app, _) = app_with(name, contents);
        app.last_frame_width = width;
        app
    }

    #[test]
    fn row_mode_stops_where_the_last_column_reaches_the_right_edge() {
        let mut app = app_sized("wide.csv", WIDE, 40);
        assert_eq!(app.selection_mode, SelectionMode::Row);

        for _ in 0..20 {
            press(&mut app, 'l');
        }
        let last = 7;
        assert_eq!(app.col_offset, app.max_col_offset());
        assert!(
            app.col_offset < last,
            "row mode padded the view with empty columns: offset {} of {last}",
            app.col_offset
        );
    }

    #[test]
    fn dollar_and_zero_move_the_viewport_in_every_mode() {
        for enter_cell_mode in [false, true] {
            let mut app = app_sized("ends.csv", WIDE, 40);
            if enter_cell_mode {
                cell_mode(&mut app);
            }

            press(&mut app, '$');
            assert_eq!(
                app.col_offset,
                app.max_col_offset(),
                "cell={enter_cell_mode}"
            );
            assert_eq!(app.cursor_col, 7, "cell={enter_cell_mode}");

            press(&mut app, '0');
            assert_eq!(app.col_offset, 0, "cell={enter_cell_mode}");
            assert_eq!(app.cursor_col, 0, "cell={enter_cell_mode}");
        }
    }

    #[test]
    fn zero_stays_a_digit_while_a_count_is_being_typed() {
        let mut rows = String::from("a,b\n");
        for i in 0..20 {
            rows.push_str(&format!("{i},{i}\n"));
        }
        let mut app = app_sized("count.csv", &rows, 40);
        cell_mode(&mut app);

        press(&mut app, '1');
        press(&mut app, '0');
        assert_eq!(app.pending_num, "10", "'0' continued the count");
        press(&mut app, 'j');
        assert_eq!(app.cursor_row, 10);

        // On its own it is still the jump to the first column.
        press(&mut app, 'l');
        press(&mut app, '0');
        assert_eq!(app.cursor_col, 0);
    }

    #[test]
    fn h_and_l_take_a_count_like_j_and_k() {
        let mut app = app_sized("countcol.csv", WIDE, 40);
        cell_mode(&mut app);

        press(&mut app, '5');
        press(&mut app, 'l');
        assert_eq!(app.cursor_col, 5);
        assert!(app.pending_num.is_empty(), "the count is spent");

        press(&mut app, '3');
        press(&mut app, 'h');
        assert_eq!(app.cursor_col, 2);

        // Uncounted, they are still single steps.
        press(&mut app, 'l');
        assert_eq!(app.cursor_col, 3);
    }

    #[test]
    fn a_counted_column_jump_stops_at_the_ends() {
        let mut app = app_sized("countclamp.csv", WIDE, 40);
        cell_mode(&mut app);

        press(&mut app, '9');
        press(&mut app, '9');
        press(&mut app, 'l');
        assert_eq!(app.cursor_col, 7, "eight columns, so the last is 7");

        press(&mut app, '9');
        press(&mut app, '9');
        press(&mut app, 'h');
        assert_eq!(app.cursor_col, 0);
    }

    #[test]
    fn a_counted_jump_scrolls_row_mode_without_overshooting() {
        let mut app = app_sized("countrow.csv", WIDE, 40);
        assert_eq!(app.selection_mode, SelectionMode::Row);

        press(&mut app, '2');
        press(&mut app, 'l');
        assert_eq!(app.col_offset, 2);

        // Past the end it settles where the last column reaches the edge,
        // exactly where repeated single steps stop.
        press(&mut app, '9');
        press(&mut app, 'l');
        assert_eq!(app.col_offset, app.max_col_offset());
    }

    #[test]
    fn the_column_readout_follows_whatever_is_moving() {
        let mut app = app_sized("readout.csv", WIDE, 40);

        // Row mode moves the viewport, so the readout tracks that.
        press(&mut app, 'l');
        assert_eq!(app.col_offset, 1);
        assert_eq!(app.col_position(), 1);

        // Cell mode moves a cursor, so it tracks that instead — it used to
        // sit still while the cursor walked across the screen.
        cell_mode(&mut app);
        let before = app.col_position();
        press(&mut app, 'l');
        assert_eq!(app.col_position(), app.cursor_col);
        assert_ne!(app.col_position(), before);
    }

    /// 40 rows, so a 10-row viewport has plenty of room to move.
    fn tall_app(name: &str) -> App {
        let mut rows = String::from("n\n");
        for i in 0..40 {
            rows.push_str(&format!("{i}\n"));
        }
        let (mut app, _) = app_with(name, &rows);
        app.last_frame_width = 40;
        app
    }

    fn offset(app: &App) -> usize {
        app.store.as_ref().unwrap().row_offset
    }

    #[test]
    fn it_takes_two_gs_to_reach_the_top() {
        let mut app = tall_app("gg.csv");
        app.cursor_to(20).unwrap();

        press(&mut app, 'g');
        assert_eq!(app.cursor_row, 20, "one g is only half a motion");
        assert_eq!(app.pending_prefix, Some('g'));

        press(&mut app, 'g');
        assert_eq!(app.cursor_row, 0);
        assert_eq!(app.pending_prefix, None);
    }

    #[test]
    fn a_count_survives_the_first_g() {
        let mut app = tall_app("countgg.csv");
        press(&mut app, '1');
        press(&mut app, '2');
        press(&mut app, 'g');
        assert_eq!(app.pending_num, "12", "the count outlives the prefix");
        press(&mut app, 'g');
        assert_eq!(app.cursor_row, 11, "12gg is the twelfth row, 1-based");
    }

    #[test]
    fn an_unfinished_g_is_abandoned_rather_than_acted_on() {
        let mut app = tall_app("gcancel.csv");
        app.cursor_to(20).unwrap();

        press(&mut app, 'g');
        press(&mut app, 'x'); // not a g-command
        assert_eq!(app.pending_prefix, None);
        assert_eq!(app.cursor_row, 20);
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0, "and x did not fire");
    }

    #[test]
    fn a_half_page_moves_the_view_even_when_the_cursor_has_room() {
        let mut app = tall_app("halfpage.csv");
        let viewport = app.store.as_ref().unwrap().viewport_rows;
        assert_eq!(viewport, 10);

        // Cursor at the very top of the window, with nine rows to spare.
        assert_eq!((app.cursor_row, offset(&app)), (0, 0));
        app.handle_key_event(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL))
            .unwrap();

        // vim scrolls the window and takes the cursor with it, keeping its
        // height in the window. Walking the cursor down alone would have left
        // the view untouched.
        assert_eq!(offset(&app), 5, "the view moved half a screen");
        assert_eq!(app.cursor_row, 5, "and the cursor kept its place in it");

        app.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!((app.cursor_row, offset(&app)), (0, 0));
    }

    #[test]
    fn a_whole_page_moves_twice_as_far_as_half_of_one() {
        let mut app = tall_app("wholepage.csv");
        let viewport = app.store.as_ref().unwrap().viewport_rows;
        assert_eq!(viewport, 10);

        app.handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!(offset(&app), viewport, "a whole screen");
        assert_eq!(app.cursor_row, viewport, "the cursor came with it");

        app.handle_key_event(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!((offset(&app), app.cursor_row), (0, 0));

        // Page Up and Page Down say the same thing, as they do in csvlens.
        key(&mut app, KeyCode::PageDown);
        assert_eq!(offset(&app), viewport);
        key(&mut app, KeyCode::PageUp);
        assert_eq!(offset(&app), 0);
    }

    #[test]
    fn at_the_end_of_the_file_the_cursor_carries_on_alone() {
        let mut app = tall_app("halfend.csv");
        press(&mut app, 'G');
        let settled = offset(&app);
        assert_eq!(app.cursor_row, 39);

        app.handle_key_event(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL))
            .unwrap();
        assert_eq!(offset(&app), settled, "the view has nowhere left to go");
        assert_eq!(app.cursor_row, 39, "and the cursor is already at the end");
    }

    #[test]
    fn z_commands_place_the_cursor_row_in_the_viewport() {
        let mut app = tall_app("zcmd.csv");
        assert_eq!(app.store.as_ref().unwrap().viewport_rows, 10);
        app.cursor_to(20).unwrap();

        press(&mut app, 'z');
        press(&mut app, 't');
        assert_eq!(offset(&app), 20, "zt puts the cursor at the top");

        press(&mut app, 'z');
        press(&mut app, 'z');
        assert_eq!(offset(&app), 15, "zz centres it");

        press(&mut app, 'z');
        press(&mut app, 'b');
        assert_eq!(offset(&app), 11, "zb puts it at the bottom");
        assert_eq!(app.cursor_row, 20, "and none of them move the cursor");
    }

    const FOURCOL: &str = "a,b,c,d\n1,2,3,4\n5,6,7,8\n";

    fn shown_columns(app: &App) -> Vec<String> {
        let store = app.store.as_ref().unwrap();
        store
            .current_view
            .get_column_names()
            .iter()
            .map(|n| n.to_string())
            .collect()
    }

    #[test]
    fn select_narrows_the_view_to_the_named_columns_in_order() {
        let mut app = app_sized("select.csv", FOURCOL, 60);
        command(&mut app, "select c a");
        assert_eq!(shown_columns(&app), ["c", "a"]);
        assert_eq!(app.store.as_ref().unwrap().column_count(), 2);

        // Each command replaces the slot rather than narrowing further.
        command(&mut app, "select b");
        assert_eq!(shown_columns(&app), ["b"]);

        command(&mut app, "reset");
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
    }

    const CATS: &str = "id,cat\n0,a\n1,b\n2,a\n3,b\n4,a\n";

    /// The scan runs on a worker thread; drain it until it finishes.
    fn settle(app: &mut App) {
        for _ in 0..2000 {
            if app.filter_rx.is_none() {
                return;
            }
            app.poll_filter();
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        panic!("the filter scan never finished");
    }

    fn filter(app: &mut App, line: &str) {
        command(app, line);
        settle(app);
    }

    #[test]
    fn a_filter_narrows_the_rows_on_show() {
        let mut app = app_sized("filter.csv", CATS, 60);
        filter(&mut app, "filter cat = a");

        let store = app.store.as_ref().unwrap();
        assert_eq!(store.row_count(), 3, "three rows say a");
        assert_eq!(store.total_rows, 5, "the file still has five");
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("0"));
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("2"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("4"));
    }

    #[test]
    fn a_bare_filter_puts_the_rows_back() {
        let mut app = app_sized("unfilter.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        assert_eq!(app.store.as_ref().unwrap().row_count(), 3);

        filter(&mut app, "filter");
        assert_eq!(app.store.as_ref().unwrap().row_count(), 5);
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("1"));
    }

    /// The reason a filter is resolved to row indices rather than composed
    /// into the frame: the edit buffer is keyed by source row, so a row picked
    /// out of a filtered view has to know which line of the file it came from.
    #[test]
    fn editing_a_filtered_row_writes_the_right_line() {
        let (mut app, path) = app_with("filteredit.csv", CATS);
        app.last_frame_width = 60;
        filter(&mut app, "filter cat = a");

        // Display row 1 is the file's row 2.
        press(&mut app, 'j');
        cell_mode(&mut app);
        press(&mut app, 'c');
        typed(&mut app, "99");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("99"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "id,cat\n0,a\n1,b\n99,a\n3,b\n4,a\n",
            "the edit belongs to the third line, not the second"
        );
    }

    #[test]
    fn a_filtered_view_can_still_be_edited() {
        let mut app = app_sized("filteditable.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        assert_eq!(
            app.store.as_ref().unwrap().edit_blocked(),
            None,
            "a filter keeps row identity, so it need not block edits"
        );
    }

    #[test]
    fn a_filter_and_a_sort_hold_at_the_same_time() {
        let mut app = app_sized("filtersort.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        assert_eq!(app.store.as_ref().unwrap().row_count(), 3);

        // Sorting a filtered view keeps the filter, and the `s` key agrees.
        command(&mut app, "sort id-");
        settle_sort(&mut app);
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.row_count(), 3, "still only the rows that matched");
        assert_eq!(store.view.sort, [(0, false)]);
        assert!(store.view.filter.is_some());

        // Descending by id: 4, 2, 0 — the matching rows, reversed.
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("4"));
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("2"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("0"));
        assert_eq!(store.edit_blocked(), None, "and it is still editable");
    }

    /// Both narrowings at once, and an edit through them still has to reach
    /// the right line of the file.
    #[test]
    fn editing_through_a_filtered_and_sorted_view_writes_the_right_line() {
        let (mut app, path) = app_with("filtersortedit.csv", CATS);
        app.last_frame_width = 60;
        filter(&mut app, "filter cat = a");
        command(&mut app, "sort id-");
        settle_sort(&mut app);

        // Display row 0 is id 4, the file's fifth row.
        cell_mode(&mut app);
        press(&mut app, 'c');
        typed(&mut app, "99");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("99"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "id,cat\n0,a\n1,b\n2,a\n3,b\n99,a\n"
        );
    }

    #[test]
    fn clearing_one_of_them_leaves_the_other_working() {
        let mut app = app_sized("filtersortclear.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        command(&mut app, "sort id-");
        settle_sort(&mut app);

        // Dropping the sort falls back to the row-set scan, filter intact.
        command(&mut app, "sort");
        settle(&mut app);
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.row_count(), 3);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("0"), "file order again");

        // Dropping the filter leaves the whole file.
        command(&mut app, "filter");
        settle(&mut app);
        assert_eq!(app.store.as_ref().unwrap().row_count(), 5);
    }

    #[test]
    fn a_filter_that_matches_nothing_shows_nothing() {
        let mut app = app_sized("nomatch.csv", CATS, 60);
        filter(&mut app, "filter cat = zzz");
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.row_count(), 0);
        assert_eq!(store.current_view.height(), 0);
        assert_eq!(
            store.current_view.width(),
            2,
            "still the right columns to draw a header from"
        );
    }

    #[test]
    fn a_filter_composes_with_a_projection() {
        let mut app = app_sized("filterselect.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        command(&mut app, "select cat");
        assert_eq!(shown_columns(&app), ["cat"]);
        assert_eq!(app.store.as_ref().unwrap().row_count(), 3);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("a"));
    }

    fn tab(app: &mut App) {
        key(app, KeyCode::Tab);
    }

    #[test]
    fn tab_completes_a_verb_then_a_column() {
        let mut app = app_sized("tabcomplete.csv", FOURCOL, 60);
        press(&mut app, ':');
        typed(&mut app, "sel");
        tab(&mut app);
        assert_eq!(app.command_buf, "select ");
        assert!(app.completion.is_none(), "one candidate needs no panel");

        typed(&mut app, "c");
        tab(&mut app);
        assert_eq!(app.command_buf, "select c ");
    }

    #[test]
    fn several_candidates_open_the_panel_and_tab_steps_through_them() {
        let mut app = app_sized("tabcycle.csv", "alpha,beta,gamma\n1,2,3\n", 60);
        press(&mut app, ':');
        typed(&mut app, "select ");

        tab(&mut app);
        let options = app.completion.as_ref().expect("a panel").options.clone();
        assert_eq!(options, ["alpha", "beta", "gamma"]);
        assert_eq!(app.panel_height(60, 24), 1, "the panel takes a row");

        // Nothing to extend — the three share no prefix — so Tab steps.
        assert_eq!(app.command_buf, "select ");
        tab(&mut app);
        assert_eq!(app.command_buf, "select alpha ");
        tab(&mut app);
        assert_eq!(app.command_buf, "select beta ");
        key(&mut app, KeyCode::BackTab);
        assert_eq!(app.command_buf, "select alpha ");
    }

    #[test]
    fn the_panel_takes_its_rows_from_the_table() {
        let mut app = app_sized("panelroom.csv", "alpha,beta,gamma\n1,2,3\n", 60);
        let before = App::viewport_rows(24, 0);
        press(&mut app, ':');
        typed(&mut app, "select ");
        tab(&mut app);
        let after = App::viewport_rows(24, app.panel_height(60, 24));
        assert_eq!(
            after,
            before - 1,
            "the table gives up exactly the panel's row"
        );
    }

    #[test]
    fn typing_or_leaving_puts_the_panel_away() {
        let mut app = app_sized("panelgone.csv", "alpha,beta,gamma\n1,2,3\n", 60);
        press(&mut app, ':');
        typed(&mut app, "select ");
        tab(&mut app);
        assert!(app.completion.is_some());

        typed(&mut app, "a");
        assert!(app.completion.is_none(), "a keystroke changes the answer");

        tab(&mut app);
        assert_eq!(app.command_buf, "select alpha ");
        key(&mut app, KeyCode::Esc);
        assert!(app.completion.is_none());
        assert_eq!(app.panel_height(60, 24), 0);
    }

    #[test]
    fn a_completed_command_actually_runs() {
        let mut app = app_sized("tabrun.csv", FOURCOL, 60);
        press(&mut app, ':');
        typed(&mut app, "sel");
        tab(&mut app);
        typed(&mut app, "d");
        tab(&mut app);
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["d"], "msg: {:?}", app.message);
    }

    #[test]
    fn dd_takes_out_the_cursor_row_and_writes_it_out() {
        let (mut app, path) = app_with("dd.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'j'); // on row 1, `b`

        press(&mut app, 'd');
        assert_eq!(app.pending_prefix, Some('d'), "one d is half a command");
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("b"), "nothing yet");

        press(&mut app, 'd');
        assert_eq!(app.store.as_ref().unwrap().row_count(), 2);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("a"));
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("c"), "c moved up");

        // Nothing has reached the file until :w.
        assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLE);
        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\nc,3\n"
        );
    }

    #[test]
    fn a_count_deletes_that_many_rows() {
        let (mut app, path) = app_with("countdd.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, '2');
        press(&mut app, 'd');
        assert_eq!(app.pending_num, "2", "the count outlives the prefix");
        press(&mut app, 'd');

        assert_eq!(app.store.as_ref().unwrap().row_count(), 1);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("c"));
        command(&mut app, "w");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "name,count\nc,3\n");
    }

    #[test]
    fn deleting_is_one_undoable_step() {
        let (mut app, _) = app_with("undodd.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, '2');
        press(&mut app, 'd');
        press(&mut app, 'd');
        assert_eq!(app.store.as_ref().unwrap().row_count(), 1);

        press(&mut app, 'u');
        assert_eq!(
            app.store.as_ref().unwrap().row_count(),
            3,
            "two rows, one undo"
        );
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("a"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
    }

    #[test]
    fn a_visual_selection_deletes_its_rows() {
        let (mut app, path) = app_with("visualdd.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'd');

        assert_eq!(app.store.as_ref().unwrap().row_count(), 1);
        assert!(app.visual_anchor.is_none(), "the selection is spent");
        command(&mut app, "w");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "name,count\nc,3\n");
    }

    #[test]
    fn deleting_past_the_end_takes_what_is_there_and_moves_the_cursor_back() {
        let (mut app, _) = app_with("ddend.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'j');
        press(&mut app, '9');
        press(&mut app, 'd');
        press(&mut app, 'd');

        assert_eq!(app.store.as_ref().unwrap().row_count(), 1);
        assert_eq!(app.cursor_row, 0, "the cursor cannot sit past the end");
        assert!(app.message.clone().unwrap().contains("deleted 2 rows"));
    }

    #[test]
    fn an_edited_cell_below_a_deleted_row_still_belongs_to_its_own_line() {
        // The edit is keyed to the file, the deletion shifts what is on
        // screen, and only the file can say whether they agree.
        let (mut app, path) = app_with("ddshift.csv", SAMPLE);
        app.last_frame_width = 60;
        cell_mode(&mut app);
        press(&mut app, 'd');
        press(&mut app, 'd'); // delete `a`, so `b` is now display row 0

        press(&mut app, 'c');
        typed(&mut app, "B");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("B"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\nB,2\nc,3\n",
            "the edit belongs to b's line, not a's"
        );
    }

    #[test]
    fn a_sorted_or_filtered_view_says_why_it_will_not_delete() {
        let mut app = app_sized("ddblocked.csv", CATS, 60);
        filter(&mut app, "filter cat = a");
        press(&mut app, 'd');
        press(&mut app, 'd');
        let message = app.message.clone().unwrap();
        assert!(message.contains("filtered or sorted"), "{message}");
        assert_eq!(app.store.as_ref().unwrap().row_count(), 3, "untouched");
    }

    #[test]
    fn o_opens_a_row_below_ready_to_type_into() {
        let (mut app, path) = app_with("open.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'o');

        assert!(matches!(app.mode, AppMode::Edit), "typing starts at once");
        assert_eq!(app.cursor_row, 1, "below the row it was on");
        assert_eq!(app.store.as_ref().unwrap().row_count(), 4);

        typed(&mut app, "new");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("new"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("b"), "b moved down");

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\nnew,\nb,2\nc,3\n"
        );
    }

    #[test]
    fn shift_o_opens_a_row_above() {
        let (mut app, path) = app_with("openabove.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'j');
        press(&mut app, 'O');
        assert_eq!(app.cursor_row, 1, "where the old row 1 was");
        typed(&mut app, "mid");
        key(&mut app, KeyCode::Enter);

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\nmid,\nb,2\nc,3\n"
        );
    }

    #[test]
    fn a_row_opened_at_the_top_lands_above_everything() {
        let (mut app, path) = app_with("opentop.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'O');
        typed(&mut app, "first");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("first"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\nfirst,\na,1\nb,2\nc,3\n",
            "under the header, above the first row"
        );
    }

    #[test]
    fn a_row_opened_at_the_end_lands_after_everything() {
        let (mut app, path) = app_with("openend.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'G');
        press(&mut app, 'o');
        typed(&mut app, "last");
        key(&mut app, KeyCode::Enter);

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\nb,2\nc,3\nlast,\n"
        );
    }

    /// `o` twice running has to give two rows in the order they were opened,
    /// which is the case that breaks if a new row is only ever appended to its
    /// anchor rather than placed within it.
    #[test]
    fn opening_below_a_new_row_keeps_them_in_order() {
        let (mut app, path) = app_with("openorder.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'o');
        typed(&mut app, "one");
        key(&mut app, KeyCode::Enter);
        press(&mut app, 'o');
        typed(&mut app, "two");
        key(&mut app, KeyCode::Enter);

        assert_eq!(shown(&app, 0, 1).as_deref(), Some("one"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("two"));
        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\none,\ntwo,\nb,2\nc,3\n"
        );
    }

    #[test]
    fn opening_a_row_is_one_undoable_step() {
        let (mut app, _) = app_with("openundo.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'o');
        key(&mut app, KeyCode::Esc);
        assert_eq!(app.store.as_ref().unwrap().row_count(), 4);

        press(&mut app, 'u');
        assert_eq!(app.store.as_ref().unwrap().row_count(), 3);
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
    }

    #[test]
    fn a_new_row_can_be_deleted_again() {
        let (mut app, path) = app_with("openthendelete.csv", SAMPLE);
        app.last_frame_width = 60;
        press(&mut app, 'o');
        typed(&mut app, "gone");
        key(&mut app, KeyCode::Enter);
        press(&mut app, 'd');
        press(&mut app, 'd');

        assert_eq!(app.store.as_ref().unwrap().row_count(), 3);
        command(&mut app, "w");
        // Asserted positively: an unchanged file is also what a *refused*
        // write leaves behind.
        assert_eq!(app.message.as_deref(), Some("wrote openthendelete.csv"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLE, "as it was");
    }

    #[test]
    fn a_bare_select_puts_the_columns_back() {
        let mut app = app_sized("bareselect.csv", FOURCOL, 60);
        command(&mut app, "select c");
        assert_eq!(shown_columns(&app), ["c"]);

        command(&mut app, "select");
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
        assert!(app.message.is_none(), "no complaint: {:?}", app.message);

        command(&mut app, "hide a");
        command(&mut app, "select *");
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
    }

    #[test]
    fn hide_drops_columns_from_what_is_on_show() {
        let mut app = app_sized("hide.csv", FOURCOL, 60);
        command(&mut app, "hide b d");
        assert_eq!(shown_columns(&app), ["a", "c"]);
    }

    #[test]
    fn a_bad_view_command_is_reported_and_changes_nothing() {
        let mut app = app_sized("badview.csv", FOURCOL, 60);
        command(&mut app, "select nope");
        assert!(app.message.clone().unwrap().contains("no column called"));
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"], "untouched");

        command(&mut app, "hide a b c d");
        assert!(app.message.clone().unwrap().contains("hide every column"));
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
    }

    /// The overlay is keyed by source column, so an edit made through a
    /// reordered view has to land on the right field of the file.
    #[test]
    fn editing_through_a_narrowed_view_writes_the_right_column() {
        let (mut app, path) = app_with("viewedit.csv", FOURCOL);
        app.last_frame_width = 60;
        command(&mut app, "select d a");
        cell_mode(&mut app);

        // Display column 0 is the file's column `d`.
        press(&mut app, 'c');
        typed(&mut app, "X");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["d", "a"]);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("X"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "a,b,c,d\n1,2,3,X\n5,6,7,8\n",
            "the edit belongs to column d, not to column a"
        );
    }

    #[test]
    fn an_edit_hidden_by_a_view_is_still_pending_and_still_written() {
        let (mut app, path) = app_with("viewhidden.csv", FOURCOL);
        app.last_frame_width = 60;
        cell_mode(&mut app);
        press(&mut app, 'c');
        typed(&mut app, "Z");
        key(&mut app, KeyCode::Enter);

        command(&mut app, "select c d");
        assert!(
            app.store.as_ref().unwrap().edited_cells().is_empty(),
            "nowhere on screen to mark it"
        );
        assert_eq!(app.store.as_ref().unwrap().dirty(), 1, "but still pending");

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "a,b,c,d\nZ,2,3,4\n5,6,7,8\n"
        );
    }

    #[test]
    fn a_narrowing_view_brings_the_cursor_back_inside_it() {
        let mut app = app_sized("clampview.csv", FOURCOL, 60);
        cell_mode(&mut app);
        press(&mut app, '$');
        assert_eq!(app.cursor_col, 3);

        command(&mut app, "select a b");
        assert_eq!(app.cursor_col, 1, "the cursor cannot point past the view");
    }

    #[test]
    fn sort_from_the_command_line_agrees_with_the_s_key() {
        let mut app = app_sized("viewsort.csv", FOURCOL, 60);
        command(&mut app, "sort b-");
        settle_sort(&mut app);
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.view.sort, [(1, false)]);
        assert_eq!(store.sort_display(), [(1, false)]);
        assert_eq!(
            app.cursor_row, 0,
            "a reorder puts the cursor back at the top"
        );

        // `:sort` goes through the same rebuild the `s` key does, so the rows
        // stay identifiable and the view stays editable.
        assert_eq!(store.edit_blocked(), None);
    }

    #[test]
    fn a_sort_key_on_a_hidden_column_keeps_working_but_is_not_drawn() {
        let mut app = app_sized("hiddensort.csv", FOURCOL, 60);
        command(&mut app, "sort d");
        command(&mut app, "select a b");
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.view.sort, [(3, true)], "the sort still applies");
        assert!(store.sort_display().is_empty(), "but has no header to mark");
    }

    #[test]
    fn a_selection_grows_with_the_motions() {
        let (mut app, _) = app_with("visual.csv", SAMPLE);
        cell_mode(&mut app);

        press(&mut app, 'v');
        assert_eq!(app.visual_range(), Some(((0, 0), (0, 0))));

        press(&mut app, 'j');
        press(&mut app, 'l');
        assert_eq!(app.visual_range(), Some(((0, 1), (0, 1))));

        // Counts work, because they are the ordinary motions.
        press(&mut app, 'v');
        assert_eq!(app.visual_range(), None, "v again cancels");
    }

    #[test]
    fn filling_a_selection_is_one_edit_and_one_undo() {
        let (mut app, _) = app_with("fill.csv", SAMPLE);
        cell_mode(&mut app);

        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'l');
        press(&mut app, 'c');
        assert!(matches!(app.mode, AppMode::Edit));
        typed(&mut app, "z");
        key(&mut app, KeyCode::Enter);

        assert_eq!(app.store.as_ref().unwrap().dirty(), 4);
        assert!(app.visual_anchor.is_none(), "the selection is spent");
        for row in 0..2 {
            for col in 0..2 {
                assert_eq!(shown(&app, col, row).as_deref(), Some("z"), "{row},{col}");
            }
        }
        // Untouched by the block.
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("c"));

        press(&mut app, 'u');
        assert_eq!(
            app.store.as_ref().unwrap().dirty(),
            0,
            "one fill, one undo — not four"
        );
    }

    #[test]
    fn i_and_a_build_on_what_each_cell_already_holds() {
        let (mut app, _) = app_with("prepend.csv", SAMPLE);
        cell_mode(&mut app);

        // Prepend down the name column.
        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'i');
        typed(&mut app, ">");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some(">a"));
        assert_eq!(shown(&app, 0, 1).as_deref(), Some(">b"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("c"), "outside the block");

        // Append over the same two cells — back to the top first, since the
        // cursor is left where the last selection ended.
        press(&mut app, 'g');
        press(&mut app, 'g');
        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'a');
        typed(&mut app, "!");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 0, 0).as_deref(), Some(">a!"));
        assert_eq!(shown(&app, 0, 1).as_deref(), Some(">b!"));
    }

    #[test]
    fn an_append_reads_rows_below_the_viewport() {
        // The page holds one row; the block covers all three. A prepend that
        // could only see the visible row would lose the other two values.
        let (mut app, path) = app_with("offpage.csv", SAMPLE);
        app.store = Some(Store::open_file(&path, 1).unwrap());
        key(&mut app, KeyCode::Tab); // column mode: every row

        press(&mut app, 'v');
        press(&mut app, 'a');
        typed(&mut app, "_x");
        key(&mut app, KeyCode::Enter);

        assert_eq!(app.store.as_ref().unwrap().dirty(), 3);
        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na_x,1\nb_x,2\nc_x,3\n"
        );
    }

    #[test]
    fn a_fill_over_numbers_warns_from_the_value_it_will_write() {
        let (mut app, _) = app_with("fillwarn.csv", SAMPLE);
        key(&mut app, KeyCode::Tab); // column mode
        press(&mut app, 'l'); // the numeric column
        press(&mut app, 'v');
        press(&mut app, 'a');
        typed(&mut app, "kg");
        key(&mut app, KeyCode::Enter);

        // "1kg" is what lands in the cell, and that is what is warned about.
        let message = app.message.clone().expect("appending to a number warns");
        assert!(message.contains("becomes text"), "{message}");
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("1kg"));
    }

    #[test]
    fn a_row_selection_covers_every_column() {
        let (mut app, _) = app_with("rowsel.csv", SAMPLE);
        assert_eq!(app.selection_mode, SelectionMode::Row);

        press(&mut app, 'v');
        press(&mut app, 'j');
        assert_eq!(app.visual_range(), Some(((0, 1), (0, 1))));

        press(&mut app, 'x');
        assert_eq!(app.store.as_ref().unwrap().dirty(), 4);
        // Row mode keeps its shape rather than being switched to cell mode.
        assert_eq!(app.selection_mode, SelectionMode::Row);
    }

    #[test]
    fn a_column_selection_covers_every_row() {
        let (mut app, _) = app_with("colsel.csv", SAMPLE);
        key(&mut app, KeyCode::Tab);
        assert_eq!(app.selection_mode, SelectionMode::Column);

        press(&mut app, 'v');
        assert_eq!(app.visual_range(), Some(((0, 2), (0, 0))), "all three rows");

        press(&mut app, 'x');
        assert_eq!(app.store.as_ref().unwrap().dirty(), 3);
        for row in 0..3 {
            assert_eq!(shown(&app, 0, row).as_deref(), Some(""), "row {row}");
        }
    }

    #[test]
    fn escape_gives_up_the_selection_before_the_search() {
        let (mut app, _) = app_with("esc.csv", SAMPLE);
        let query = SearchQuery::new("a".to_string()).unwrap();
        app.search_state = Some(SearchState::new(query, None));

        press(&mut app, 'v');
        key(&mut app, KeyCode::Esc);
        assert!(app.visual_anchor.is_none());
        assert!(app.search_state.is_some(), "one Esc, one thing given up");

        key(&mut app, KeyCode::Esc);
        assert!(app.search_state.is_none());
    }

    #[test]
    fn tab_gives_up_the_selection_rather_than_reshaping_it() {
        let (mut app, _) = app_with("tabsel.csv", SAMPLE);
        press(&mut app, 'v');
        key(&mut app, KeyCode::Tab);
        assert!(app.visual_anchor.is_none());
    }

    #[test]
    fn a_yanked_block_pastes_at_the_cursor() {
        let (mut app, path) = app_with("yank.csv", SAMPLE);
        cell_mode(&mut app);

        // Yank the first two names.
        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'y');
        assert_eq!(app.message.as_deref(), Some("yanked 2 cells"));
        assert!(app.visual_anchor.is_none());
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0, "yanking reads only");

        // Paste them one row down.
        press(&mut app, 'j');
        press(&mut app, 'p');
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("a"));
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("b"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\na,2\nb,3\n"
        );
    }

    #[test]
    fn a_visual_yank_leaves_the_cursor_where_the_selection_began() {
        let (mut app, _) = app_with("yankcursor.csv", SAMPLE);
        cell_mode(&mut app);
        press(&mut app, 'j'); // start from row 1

        press(&mut app, 'v');
        press(&mut app, 'j'); // extend down to row 2
        press(&mut app, 'y');
        assert_eq!(app.cursor_row, 1, "back to the anchor, not the far end");
    }

    /// Text from outside lands where `p` would put it, and goes through the
    /// same clipping, so there is one answer to what pasting does.
    #[test]
    fn a_paste_from_the_terminal_lands_as_a_block() {
        let (mut app, _) = app_with("extpaste.csv", "a,b,c\n1,2,3\n4,5,6\n7,8,9\n");
        cell_mode(&mut app);
        app.cursor_to(1).unwrap();
        press(&mut app, 'l');

        app.handle_paste("x\ty\nz\tw\n".to_string()).unwrap();
        assert_eq!(shown(&app, 1, 1).as_deref(), Some("x"));
        assert_eq!(shown(&app, 2, 1).as_deref(), Some("y"));
        assert_eq!(shown(&app, 1, 2).as_deref(), Some("z"));
        assert_eq!(app.message.as_deref(), Some("pasted 4 cells"));
    }

    #[test]
    fn a_paste_wider_than_the_table_says_what_fell_off() {
        let (mut app, _) = app_with("extclip.csv", "a,b\n1,2\n");
        cell_mode(&mut app);
        app.handle_paste("x\ty\tz".to_string()).unwrap();
        assert_eq!(
            app.message.as_deref(),
            Some("pasted 2 cells, 1 past the edge")
        );
    }

    /// A quoted cell comes back the cell it was, not two.
    #[test]
    fn a_paste_of_a_quoted_value_keeps_its_shape() {
        let (mut app, _) = app_with("quotedpaste.csv", "a,b\n1,2\n");
        cell_mode(&mut app);
        app.handle_paste("\"one\ttwo\"\tplain".to_string()).unwrap();
        assert_eq!(shown(&app, 0, 0).as_deref(), Some("one\ttwo"));
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("plain"));
    }

    /// An external paste is not a yank: whatever `y` put in the register is
    /// still there afterwards.
    #[test]
    fn a_paste_from_outside_leaves_the_register_alone() {
        let (mut app, _) = app_with("regkeep.csv", "a,b\n1,2\n3,4\n");
        cell_mode(&mut app);
        press(&mut app, 'y');
        let yanked = app.register.clone();

        app.handle_paste("outside".to_string()).unwrap();
        assert_eq!(app.register, yanked);
    }

    /// A paste while a line is being typed is meant for the line.
    #[test]
    fn a_paste_into_a_prompt_goes_into_the_line() {
        let (mut app, _) = app_with("promptpaste.csv", SAMPLE);
        press(&mut app, ':');
        app.handle_paste("select name".to_string()).unwrap();
        assert_eq!(app.command_buf, "select name");

        key(&mut app, KeyCode::Esc);
        press(&mut app, '/');
        // A line holds one line, so the breaks become spaces rather than
        // ending the search.
        app.handle_paste("two\nlines".to_string()).unwrap();
        assert_eq!(app.search_buf, "two lines");
    }

    #[test]
    fn yanking_without_a_selection_follows_the_mode() {
        let (mut app, _) = app_with("yankmode.csv", SAMPLE);

        // Row mode: the whole row, every column.
        press(&mut app, 'y');
        assert_eq!(app.message.as_deref(), Some("yanked 2 cells"));

        cell_mode(&mut app);
        press(&mut app, 'y');
        assert_eq!(app.message.as_deref(), Some("yanked 1 cells"));
    }

    #[test]
    fn a_paste_running_off_the_edge_is_clipped_and_says_so() {
        let (mut app, _) = app_with("clip.csv", SAMPLE);
        cell_mode(&mut app);

        press(&mut app, 'v');
        press(&mut app, 'j');
        press(&mut app, 'y');

        // Land it on the last row, so the second cell has nowhere to go.
        press(&mut app, 'G');
        press(&mut app, 'p');
        let message = app.message.clone().unwrap();
        assert_eq!(message, "pasted 1 cells, 1 past the edge");
        assert_eq!(shown(&app, 0, 2).as_deref(), Some("a"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 1);
    }

    #[test]
    fn pasting_an_empty_register_says_so() {
        let (mut app, _) = app_with("noreg.csv", SAMPLE);
        press(&mut app, 'p');
        assert_eq!(app.message.as_deref(), Some("nothing to paste"));
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
    }

    #[test]
    fn the_register_holds_pending_edits_not_what_is_on_disk() {
        let (mut app, _) = app_with("regedit.csv", SAMPLE);
        cell_mode(&mut app);

        press(&mut app, 'c');
        typed(&mut app, "edited");
        key(&mut app, KeyCode::Enter);
        press(&mut app, 'y');

        press(&mut app, 'j');
        press(&mut app, 'p');
        assert_eq!(shown(&app, 0, 1).as_deref(), Some("edited"));
    }

    #[test]
    fn a_fill_larger_than_the_buffer_should_hold_is_refused() {
        // A column selection covers every row, so on a large file it is the
        // easy way to ask for millions of overlay entries by accident.
        let rows = MAX_BLOCK / 2 + 1000;
        let mut csv = String::from("name,count\n");
        for i in 0..rows {
            csv.push_str(&format!("r{i},{i}\n"));
        }
        let (mut app, _) = app_with("huge.csv", &csv);
        key(&mut app, KeyCode::Tab); // column mode
        press(&mut app, 'v');
        press(&mut app, 'l'); // both columns, every row

        press(&mut app, 'c');
        assert!(matches!(app.mode, AppMode::Normal), "no editor opens");
        assert_eq!(app.store.as_ref().unwrap().dirty(), 0);
        let message = app.message.clone().unwrap();
        assert!(message.contains("too many"), "{message}");
    }

    /// The picker holds a working copy, so leaving it costs nothing.
    #[test]
    fn escape_leaves_the_picker_changing_nothing() {
        let mut app = app_sized("pick.csv", FOURCOL, 60);
        press(&mut app, 'C');
        assert!(matches!(app.mode, AppMode::Picker));

        press(&mut app, 'j');
        press(&mut app, '-'); // untick b
        press(&mut app, 'p'); // and pin it
        key(&mut app, KeyCode::Esc);

        assert!(matches!(app.mode, AppMode::Normal));
        assert!(app.picker.is_none());
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"], "untouched");
        assert!(app.pinned.is_empty(), "and the pin never happened");
    }

    /// Enter writes a `:select`, so the picker is a way of *typing* one rather
    /// than a second thing that decides what shows.
    #[test]
    fn the_picker_applies_its_selection_as_a_select() {
        let mut app = app_sized("pickapply.csv", FOURCOL, 60);
        press(&mut app, 'C');
        press(&mut app, 'j');
        press(&mut app, '-'); // untick b
        key(&mut app, KeyCode::Enter);

        assert!(matches!(app.mode, AppMode::Normal));
        assert_eq!(shown_columns(&app), ["a", "c", "d"]);
        // It went through the view, so the view describes it and reset undoes it.
        command(&mut app, "reset select");
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
    }

    /// A reordering `:select` has to survive a round trip: a picker that
    /// quietly discards the order would be worse than no picker.
    #[test]
    fn opening_and_applying_the_picker_preserves_the_view_order() {
        let mut app = app_sized("pickorder.csv", FOURCOL, 60);
        command(&mut app, "select c a");
        assert_eq!(shown_columns(&app), ["c", "a"]);

        press(&mut app, 'C');
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["c", "a"], "unchanged");
    }

    /// A column ticked back on lands where it is listed, which is where the
    /// user was looking when they ticked it.
    #[test]
    fn a_column_ticked_back_on_lands_where_it_was_listed() {
        let mut app = app_sized("pickback.csv", FOURCOL, 60);
        command(&mut app, "select a c");
        press(&mut app, 'C');
        // Listed a c b d — the view's two, then the hidden ones.
        press(&mut app, 'j');
        press(&mut app, 'j'); // onto b
        press(&mut app, '-');
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["a", "c", "b"]);
    }

    #[test]
    fn the_picker_carries_pins_in_and_back_out() {
        let mut app = app_sized("pickpin.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p'); // pin a the ordinary way

        press(&mut app, 'C');
        press(&mut app, 'j');
        press(&mut app, 'p'); // and b from the list
        key(&mut app, KeyCode::Enter);
        assert_eq!(app.pinned.iter().copied().collect::<Vec<_>>(), [0, 1]);

        // Unpinning from the list works the same way round.
        press(&mut app, 'C');
        press(&mut app, 'p');
        key(&mut app, KeyCode::Enter);
        assert_eq!(app.pinned.iter().copied().collect::<Vec<_>>(), [1]);
    }

    /// The view change is what the user came for, so pins that do not fit are
    /// trimmed and named rather than taking the whole apply down with them.
    #[test]
    fn pins_that_do_not_fit_are_trimmed_not_refused() {
        let mut app = app_sized("picktrim.csv", FOURCOL, 24);
        press(&mut app, 'C');
        press(&mut app, 'p'); // pin a
        press(&mut app, 'j');
        press(&mut app, 'p'); // and b
        press(&mut app, 'j');
        press(&mut app, '-'); // while also hiding c, so the view change is real
        key(&mut app, KeyCode::Enter);

        assert_eq!(
            shown_columns(&app),
            ["a", "b", "d"],
            "the view still applied"
        );
        assert!(
            app.pinned.len() < 2,
            "and the pins were trimmed to what fits: {:?}",
            app.pinned
        );
        let said = app.message.clone().unwrap();
        assert!(said.contains("no room for"), "{said}");
    }

    /// Unticking the last column is stopped where it is pressed, rather than
    /// on Enter after a whole session of ticking.
    #[test]
    fn the_picker_refuses_to_untick_the_last_column() {
        let mut app = app_sized("picklast.csv", FOURCOL, 60);
        command(&mut app, "select a");
        press(&mut app, 'C');
        press(&mut app, '-');
        let refusal = app.message.clone().unwrap();
        assert!(refusal.contains("hide every column"), "{refusal}");

        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["a"]);
    }

    /// Unlike `-`, the picker is a list of every column rather than an
    /// operation on the one under the cursor, so it needs no column cursor.
    #[test]
    fn the_picker_opens_in_row_mode() {
        let mut app = app_sized("pickrow.csv", FOURCOL, 60);
        assert_eq!(app.selection_mode, SelectionMode::Row);
        press(&mut app, 'C');
        assert!(matches!(app.mode, AppMode::Picker));
        press(&mut app, 'j');
        press(&mut app, '-');
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["a", "c", "d"]);
    }

    /// The workflow the keys exist for: start from none, tick the few wanted.
    #[test]
    fn a_and_shift_a_pick_a_handful_out_of_the_whole_list() {
        let mut app = app_sized("pickall.csv", FOURCOL, 60);
        press(&mut app, 'C');
        press(&mut app, 'j'); // onto b
        press(&mut app, 'A'); // and nothing else
        press(&mut app, 'j');
        press(&mut app, 'j'); // onto d
        press(&mut app, '-'); // tick it too
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["b", "d"]);

        press(&mut app, 'C');
        press(&mut app, 'a');
        key(&mut app, KeyCode::Enter);
        assert_eq!(
            shown_columns(&app),
            ["b", "d", "a", "c"],
            "all back, listed order"
        );
    }

    /// `q` closes a window everywhere else in vim, and a window is a view —
    /// closing one never destroys work. The picker holds changes that are not
    /// applied yet, so it cannot close harmlessly, and it does not borrow the
    /// letter for something that would throw them away.
    #[test]
    fn q_is_not_a_picker_key() {
        let mut app = app_sized("pickq.csv", FOURCOL, 60);
        press(&mut app, 'C');
        press(&mut app, 'j');
        press(&mut app, '-'); // untick b

        press(&mut app, 'q');
        assert!(matches!(app.mode, AppMode::Picker), "still open");
        assert!(!app.exit, "and it is not the app's q either");

        key(&mut app, KeyCode::Enter);
        assert_eq!(shown_columns(&app), ["a", "c", "d"], "the tick survived it");
    }

    /// The picker's keys are the least guessable in plv, and the status bar
    /// drops its hints on a narrow terminal, so `?` has to reach them.
    #[test]
    fn the_help_overlay_follows_the_picker() {
        let mut app = app_sized("pickhelp.csv", FOURCOL, 60);
        press(&mut app, 'C');
        press(&mut app, '?');
        assert!(app.help_visible);
        let sections = app.help_sections();
        assert_eq!(sections.len(), 1, "just the picker's own keys");
        let keys: Vec<&str> = sections[0].1.iter().map(|(key, _)| *key).collect();
        assert!(keys.contains(&"-") && keys.contains(&"p"), "{keys:?}");
    }

    /// `-` is `:hide <name>` without the typing, so it goes through the same
    /// slot and shows up in the same place.
    #[test]
    fn minus_hides_the_cursor_column() {
        let mut app = app_sized("hide.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab); // column mode
        press(&mut app, 'l'); // onto b

        press(&mut app, '-');
        assert_eq!(shown_columns(&app), ["a", "c", "d"]);
    }

    /// `:hide` reads the current list and filters it, so hiding twice narrows
    /// twice — where a second `:select` would replace the first.
    #[test]
    fn hiding_accumulates_rather_than_replacing() {
        let mut app = app_sized("hidetwice.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, '-');
        press(&mut app, '-');
        assert_eq!(shown_columns(&app), ["c", "d"]);
    }

    /// The cursor stays where the column was, on whatever moved into that
    /// position — as `dd` leaves it on the next row.
    #[test]
    fn the_cursor_stays_where_the_hidden_column_was() {
        let mut app = app_sized("hidecursor.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'l'); // onto b, position 1
        press(&mut app, '-');
        assert_eq!(app.cursor_col, 1, "still position 1");
        assert_eq!(shown_columns(&app)[app.cursor_col], "c", "now showing c");

        // At the right edge there is nothing to move up, so it steps back.
        press(&mut app, '$');
        let last = shown_columns(&app).len() - 1;
        assert_eq!(app.cursor_col, last);
        press(&mut app, '-');
        assert_eq!(app.cursor_col, shown_columns(&app).len() - 1);
    }

    /// Hiding everything would leave nothing to look at, and `view::apply`
    /// already refuses it — the key must not find its own way round that.
    #[test]
    fn hiding_the_last_column_is_refused() {
        let mut app = app_sized("hideall.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        for _ in 0..3 {
            press(&mut app, '-');
        }
        assert_eq!(shown_columns(&app).len(), 1);

        press(&mut app, '-');
        assert_eq!(shown_columns(&app).len(), 1, "the last one stays");
        let refusal = app.message.clone().unwrap();
        assert!(refusal.contains("hide every column"), "{refusal}");
    }

    /// There is no key that un-hides one column, so the way back has to be in
    /// front of the user at the moment they might want it.
    #[test]
    fn hiding_says_how_to_get_the_column_back() {
        let mut app = app_sized("hideback.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, '-');
        let said = app.message.clone().unwrap();
        assert!(said.contains("hid a"), "{said}");
        assert!(said.contains("reset select"), "{said}");

        command(&mut app, "reset select");
        assert_eq!(shown_columns(&app), ["a", "b", "c", "d"]);
    }

    /// `s` adopts for the same reason `-` does. The selection it reshapes is
    /// one it already clears, so there is nothing to make an exception for.
    #[test]
    fn sorting_in_row_mode_adopts_a_column_cursor() {
        let mut app = app_sized("sortrow.csv", FOURCOL, 60);
        assert_eq!(app.selection_mode, SelectionMode::Row);

        press(&mut app, 's');
        assert_eq!(app.selection_mode, SelectionMode::Cell, "as Tab would");
        settle_sort(&mut app);
        assert_eq!(
            app.store.as_ref().unwrap().view.sort,
            [(0, true)],
            "and sorted by the column it landed on"
        );
    }

    /// Row mode is what plv opens in, and a key that does nothing there is
    /// indistinguishable from one that does not exist — so it takes a column
    /// cursor the way the edit keys do.
    #[test]
    fn hiding_in_row_mode_adopts_a_column_cursor() {
        let mut app = app_sized("hiderow.csv", FOURCOL, 60);
        assert_eq!(app.selection_mode, SelectionMode::Row);

        press(&mut app, '-');
        assert_eq!(app.selection_mode, SelectionMode::Cell, "as Tab would");
        assert_eq!(shown_columns(&app), ["b", "c", "d"], "and it hid one");
    }

    /// It adopts the leftmost visible column, so scrolling sideways in row
    /// mode and pressing `-` takes off the column that is under the cursor
    /// once there is one, not the file's first.
    #[test]
    fn row_mode_hides_the_column_it_would_have_landed_on() {
        // Narrow enough that not every column fits, or row mode has nothing
        // to scroll and `col_offset` never leaves 0.
        let mut app = app_sized("hidescroll.csv", FOURCOL, 24);
        press(&mut app, 'l'); // row mode: scrolls rather than moving a cursor
        press(&mut app, 'l');
        assert_eq!(app.col_offset, 2);

        press(&mut app, '-');
        assert_eq!(
            shown_columns(&app),
            ["a", "b", "d"],
            "c, where Tab would land"
        );
    }

    /// The two column features compose: a pin on a hidden column waits, and
    /// hiding around a pin leaves it drawn.
    #[test]
    fn a_hidden_column_keeps_its_pin_for_when_it_comes_back() {
        let mut app = app_sized("hidepin.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p'); // pin a
        press(&mut app, '-'); // and hide it

        assert_eq!(shown_columns(&app), ["b", "c", "d"]);
        assert!(app.display_pins().is_empty(), "nowhere to draw it");
        assert_eq!(app.pinned.iter().copied().collect::<Vec<_>>(), [0]);

        command(&mut app, "reset select");
        assert_eq!(app.display_pins().iter().copied().collect::<Vec<_>>(), [0]);
    }

    #[test]
    fn zp_pins_the_cursor_column_and_pressing_it_again_lets_go() {
        let mut app = app_sized("pin.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab); // column mode, so there is a column cursor
        press(&mut app, 'l'); // onto b

        press(&mut app, 'z');
        press(&mut app, 'p');
        assert_eq!(app.pinned.iter().copied().collect::<Vec<_>>(), [1]);

        press(&mut app, 'z');
        press(&mut app, 'p');
        assert!(app.pinned.is_empty(), "the same key lets it go");
    }

    #[test]
    fn z_bar_unpins_everything_at_once() {
        let mut app = app_sized("unpinall.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p');
        press(&mut app, 'l');
        press(&mut app, 'z');
        press(&mut app, 'p');
        assert_eq!(app.pinned.len(), 2);

        press(&mut app, 'z');
        press(&mut app, '|');
        assert!(app.pinned.is_empty());

        // `zP` is `zp`: the prefix lowercases its second key, so a stray shift
        // toggles the cursor column rather than clearing the lot.
        press(&mut app, 'z');
        press(&mut app, 'P');
        assert_eq!(app.pinned.len(), 1);
    }

    /// A pin is kept against the source column, like a width, so reordering
    /// the view moves the pin with its column rather than leaving it on
    /// whatever now happens to sit in that position.
    #[test]
    fn a_pin_follows_its_column_through_a_select() {
        let mut app = app_sized("pinselect.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p'); // pin `a`, source 0, display 0
        assert_eq!(app.display_pins().iter().copied().collect::<Vec<_>>(), [0]);

        command(&mut app, "select c a");
        assert_eq!(shown_columns(&app), ["c", "a"]);
        assert_eq!(
            app.pinned.iter().copied().collect::<Vec<_>>(),
            [0],
            "still `a`"
        );
        assert_eq!(
            app.display_pins().iter().copied().collect::<Vec<_>>(),
            [1],
            "which `select` has moved to the second position"
        );
    }

    /// A pin on a column the view hides is not forgotten — it has nowhere to
    /// be drawn, and comes back when the column does.
    #[test]
    fn a_pin_on_a_hidden_column_waits_rather_than_being_dropped() {
        let mut app = app_sized("pinhide.csv", FOURCOL, 60);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p');

        command(&mut app, "select b c");
        assert!(app.display_pins().is_empty(), "nowhere to draw it");
        assert_eq!(app.pinned.iter().copied().collect::<Vec<_>>(), [0]);

        command(&mut app, "reset select");
        assert_eq!(app.display_pins().iter().copied().collect::<Vec<_>>(), [0]);
    }

    /// Pinning the whole width would leave a table that cannot be moved
    /// through and nothing on screen to say why, so the pin is refused and
    /// says so — the call `sort_blocked` makes.
    #[test]
    fn a_pin_that_would_leave_nothing_to_scroll_in_is_refused() {
        let mut app = app_sized("pinfull.csv", FOURCOL, 24);
        key(&mut app, KeyCode::Tab);

        let mut pinned = 0;
        for _ in 0..4 {
            press(&mut app, 'z');
            press(&mut app, 'p');
            if app.message.is_some() {
                break;
            }
            pinned += 1;
            press(&mut app, 'l');
        }
        assert!(pinned > 0, "some of them fit");
        assert!(pinned < 4, "not all of them");
        assert_eq!(app.pinned.len(), pinned, "the refused one is not kept");
        let refusal = app.message.clone().unwrap();
        assert!(refusal.contains("no room to pin"), "{refusal}");
    }

    /// A pinned column is on screen at every offset, so the cursor landing on
    /// one must not drag the view back to where that column lives.
    #[test]
    fn the_cursor_on_a_pinned_column_does_not_scroll_the_view() {
        let mut app = app_sized("pinscroll.csv", WIDE, 40);
        key(&mut app, KeyCode::Tab);
        press(&mut app, 'z');
        press(&mut app, 'p'); // pin the first column

        for _ in 0..5 {
            press(&mut app, 'l');
        }
        app.col_offset = 4;
        let before = app.col_offset;

        app.cursor_col = 0; // back onto the pin, which is drawn regardless
        app.column_left(0);
        assert_eq!(app.col_offset, before, "the view stays where it was");
    }

    #[test]
    fn an_unknown_command_says_so() {
        let (mut app, _) = app_with("unknown.csv", SAMPLE);
        command(&mut app, "nope");
        assert_eq!(app.message.as_deref(), Some("not a command: :nope"));
        assert!(!app.exit);
    }

    /// Press the two keys the strip now lives under.
    fn strip(app: &mut App) {
        press(app, 'z');
        press(app, 'k');
    }

    #[test]
    fn zk_shows_the_cursor_cell_and_follows_it() {
        let long = "a,note\n1,\"a value far too long for any column to show\"\n2,short\n";
        let mut app = app_sized("cellview.csv", long, 40);
        assert_eq!(app.panel_height(40, 24), 0, "nothing showing yet");

        strip(&mut app);
        assert!(app.cell_view);
        assert_eq!(
            app.selection_mode,
            SelectionMode::Cell,
            "a cell view needs a cell cursor, as an edit does"
        );
        let (name, value) = app.cell_under_cursor().unwrap();
        assert_eq!(name, "a");
        assert_eq!(value, "1");

        // It follows the cursor rather than freezing on one cell.
        press(&mut app, 'l');
        let (name, value) = app.cell_under_cursor().unwrap();
        assert_eq!(name, "note");
        assert!(value.starts_with("a value far too long"));
        assert!(app.panel_height(40, 24) > 1, "and takes room to show it");

        key(&mut app, KeyCode::Esc);
        assert!(!app.cell_view);
        assert_eq!(app.panel_height(40, 24), 0);
    }

    #[test]
    fn the_cell_view_gives_up_rows_to_show_itself() {
        let long = "a\n\"".to_string() + &"x".repeat(500) + "\"\n";
        let mut app = app_sized("cellroom.csv", &long, 40);
        let before = App::viewport_rows(24, 0);
        strip(&mut app);
        let panel = app.panel_height(40, 24);
        assert!(panel > 0);
        assert_eq!(
            App::viewport_rows(24, panel),
            before - panel as usize,
            "the table gives up exactly what the panel takes"
        );
        assert!(panel <= 12, "and never more than half the screen");
    }

    /// The long value used by the window's tests: more lines than any window
    /// will hold, so there is something to scroll.
    fn windowed(name: &str) -> App {
        let value: String = (1..=200).map(|n| format!("line {n}. ")).collect();
        let file = format!("a,note\n1,\"{value}\"\n");
        let mut app = app_sized(name, &file, 60);
        cell_mode(&mut app);
        press(&mut app, 'l'); // onto `note`, which is the long one
        app
    }

    #[test]
    fn k_opens_a_window_on_the_cursor_cell() {
        let mut app = windowed("cellwindow.csv");
        assert!(app.inspect.is_none(), "nothing showing yet");

        press(&mut app, 'K');
        assert!(app.inspect.is_some());
        assert_eq!(
            app.selection_mode,
            SelectionMode::Cell,
            "a cell window needs a cell cursor, as an edit does"
        );
        let (name, value) = app.cell_under_cursor().unwrap();
        assert_eq!(name, "note");
        assert!(value.starts_with("line 1."));

        // It covers rather than displaces: the table keeps every row it had.
        assert_eq!(
            app.panel_height(60, 24),
            0,
            "and takes nothing from the table"
        );

        press(&mut app, 'q');
        assert!(app.inspect.is_none(), "q closes the window");
        assert!(!app.exit, "and does not quit plv");
    }

    #[test]
    fn the_window_holds_the_keys_while_it_is_up() {
        let mut app = windowed("cellkeys.csv");
        let row = app.cursor_row;
        press(&mut app, 'K');
        app.inspect.as_mut().unwrap().rows = 10; // normally captured by `draw`

        press(&mut app, 'j');
        assert_eq!(app.inspect.as_ref().unwrap().scroll, 1);
        assert_eq!(app.cursor_row, row, "the table did not move under it");

        press(&mut app, 'k');
        press(&mut app, 'k');
        assert_eq!(
            app.inspect.as_ref().unwrap().scroll,
            0,
            "and stops at the top"
        );

        key(
            &mut app,
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.inspect.as_ref().unwrap().scroll, 5, "half a window");
        press(&mut app, 'g');
        assert_eq!(app.inspect.as_ref().unwrap().scroll, 0);

        // `G` asks for further than there is; `draw` is what clamps it.
        press(&mut app, 'G');
        assert_eq!(app.inspect.as_ref().unwrap().scroll, usize::MAX);

        key(&mut app, KeyCode::Esc);
        assert!(app.inspect.is_none());
        assert!(app.search_state.is_none(), "and the Esc stopped there");
    }

    /// Rendered through `App::draw`, so what is asserted is the screen the
    /// user gets and not the widget in isolation.
    fn drawn(app: &mut App, width: u16, height: u16) -> Vec<String> {
        let backend = ratatui::backend::TestBackend::new(width, height);
        let mut terminal = ratatui::Terminal::new(backend).unwrap();
        terminal.draw(|frame| app.draw(frame)).unwrap();
        let buf = terminal.backend().buffer().clone();
        (0..height)
            .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect())
            .collect()
    }

    /// It covers the table rather than taking rows from it, so the row under
    /// it is still there when it closes.
    #[test]
    fn the_window_is_drawn_over_the_table() {
        let mut app = windowed("celldraw.csv");
        let plain = drawn(&mut app, 60, 16);
        assert!(plain.iter().any(|line| line.contains("line 1.")));

        press(&mut app, 'K');
        let over = drawn(&mut app, 60, 16);
        let middle = over.iter().filter(|line| line.contains('')).count();
        assert!(middle > 3, "the window is on screen: {over:?}");
        assert!(
            over.iter().any(|line| line.contains("note —")),
            "titled with the column: {over:?}"
        );
        // The scroll is clamped where the layout is known, so the window has
        // told the key handler how tall it is.
        assert!(app.inspect.as_ref().unwrap().rows > 0);

        press(&mut app, 'q');
        assert_eq!(drawn(&mut app, 60, 16), plain, "and the table is back");
    }

    /// `/` in the window searches the value, and the pattern is typed at the
    /// same prompt every other search uses.
    #[test]
    fn slash_finds_inside_the_value() {
        let mut app = windowed("cellfind.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);

        press(&mut app, '/');
        assert!(
            matches!(app.mode, AppMode::Search),
            "the prompt is the same prompt"
        );
        typed(&mut app, "line 137");
        key(&mut app, KeyCode::Enter);
        assert!(matches!(app.mode, AppMode::Normal));

        // The hits are found where the wrap is known, so a frame has to have
        // been drawn before there are any.
        drawn(&mut app, 60, 16);
        let hunt = app.inspect.as_ref().unwrap().hunt.as_ref().unwrap();
        assert_eq!(hunt.hits.len(), 1);
        assert_eq!(hunt.current, Some(0));
        assert!(
            app.inspect.as_ref().unwrap().scroll > 0,
            "and the window went to it"
        );
    }

    /// The two searches are separate on purpose: the table's moves the cursor
    /// between rows, and borrowing it would mean closing the window changed
    /// which row you were on.
    #[test]
    fn the_windows_search_leaves_the_tables_alone() {
        let mut app = windowed("cellfind2.csv");
        let row = app.cursor_row;
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line 3");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 60, 16);

        assert!(app.search_state.is_none(), "the table was not searched");
        assert_eq!(app.cursor_row, row, "and did not move");
        assert!(app.inspect.as_ref().unwrap().hunt.is_some());
    }

    #[test]
    fn n_and_shift_n_step_through_the_matches() {
        let mut app = windowed("cellstep.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line 1[0-9][0-9]");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 60, 16);

        let hunt = app.inspect.as_ref().unwrap().hunt.as_ref().unwrap();
        assert_eq!(hunt.starts.len(), 100, "line 100 through line 199");
        // The window is 60 wide, so some of those runs are broken by the
        // wrap: more pieces are drawn than there are matches to step between.
        assert!(
            hunt.hits.len() > hunt.starts.len(),
            "{} pieces for {} matches",
            hunt.hits.len(),
            hunt.starts.len()
        );

        let first = app.inspect.as_ref().unwrap().scroll;
        press(&mut app, 'n');
        drawn(&mut app, 60, 16);
        let second = app.inspect.as_ref().unwrap().scroll;
        assert!(second > first, "n went forward: {first} -> {second}");

        press(&mut app, 'N');
        drawn(&mut app, 60, 16);
        assert_eq!(
            app.inspect.as_ref().unwrap().scroll,
            first,
            "and N came back"
        );
    }

    /// While the match you are on is on screen, `n` is the one after it. Once
    /// you have scrolled away, `n` is the next one from where you are looking
    /// — being sent back up the value to resume from off screen is the
    /// surprising answer.
    #[test]
    fn n_goes_on_from_where_the_reader_is_looking() {
        let mut app = windowed("cellresume.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line 1[0-9][0-9]");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 60, 16);
        let first = app.inspect.as_ref().unwrap().hunt.as_ref().unwrap().current;
        assert_eq!(first, Some(0));

        // Scroll a long way past it by hand, then step.
        press(&mut app, 'G');
        drawn(&mut app, 60, 16);
        press(&mut app, 'n');
        drawn(&mut app, 60, 16);
        let after = app.inspect.as_ref().unwrap().hunt.as_ref().unwrap();
        assert!(
            after.current.unwrap() > 50,
            "resumed from the end, not from match 1: {:?}",
            after.current
        );
    }

    /// Closing the window takes the search with it. It was a search of one
    /// value, and there is no value any more.
    #[test]
    fn closing_the_window_ends_its_search() {
        let mut app = windowed("cellend.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line 2");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 60, 16);
        assert!(app.inspect.as_ref().unwrap().hunt.is_some());

        press(&mut app, 'q');
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        assert!(
            app.inspect.as_ref().unwrap().hunt.is_none(),
            "a new window opens with no search"
        );
    }

    /// An empty pattern clears the search, which is what `/` then Enter does
    /// out in the table too.
    #[test]
    fn an_empty_pattern_clears_the_search() {
        let mut app = windowed("cellclear.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line 2");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 60, 16);

        press(&mut app, '/');
        key(&mut app, KeyCode::Enter);
        assert!(app.inspect.as_ref().unwrap().hunt.is_none());
    }

    #[test]
    fn a_bad_pattern_is_reported_rather_than_swallowed() {
        let mut app = windowed("cellbad.csv");
        press(&mut app, 'K');
        drawn(&mut app, 60, 16);
        press(&mut app, '/');
        typed(&mut app, "line [");
        key(&mut app, KeyCode::Enter);

        assert!(app.inspect.as_ref().unwrap().hunt.is_none());
        assert!(
            app.message.as_deref().unwrap_or_default().contains("regex"),
            "{:?}",
            app.message
        );
    }

    /// `r` rebuilds the lines, so the hits describing the old ones are found
    /// again rather than left pointing at rows that moved.
    #[test]
    fn switching_the_view_finds_the_matches_again() {
        let json = r#"{""alpha"":4821,""beta"":[""a"",""b""]}"#;
        let file = format!("id,note\n1,\"{json}\"\n");
        let mut app = app_sized("cellrefind.csv", &file, 80);
        cell_mode(&mut app);
        press(&mut app, 'l');
        press(&mut app, 'K');
        drawn(&mut app, 80, 20);
        press(&mut app, '/');
        typed(&mut app, "beta");
        key(&mut app, KeyCode::Enter);
        drawn(&mut app, 80, 20);
        let formatted = app
            .inspect
            .as_ref()
            .unwrap()
            .hunt
            .as_ref()
            .unwrap()
            .hits
            .clone();
        assert_eq!(formatted.len(), 1);

        press(&mut app, 'r');
        drawn(&mut app, 80, 20);
        let raw = app.inspect.as_ref().unwrap().hunt.as_ref().unwrap();
        assert_eq!(raw.hits.len(), 1, "still found in the bytes");
        assert!(
            raw.at.is_some(),
            "and found again under the view it is now in"
        );
    }

    /// A JSON cell is shown as a document, and `r` gets back to the bytes.
    #[test]
    fn r_switches_between_the_formatting_and_the_value() {
        let json = r#"{""id"":4821,""tags"":[""a"",""b""]}"#;
        let file = format!("id,note\n1,\"{json}\"\n");
        let mut app = app_sized("celljson.csv", &file, 80);
        cell_mode(&mut app);
        press(&mut app, 'l');

        press(&mut app, 'K');
        let content = &app.inspect.as_ref().unwrap().content;
        assert_eq!(content.format, ui::cell::Format::Json);
        assert!(!content.raw);
        assert!(content.lines.len() > 1, "broken out over several lines");

        press(&mut app, 'r');
        let content = &app.inspect.as_ref().unwrap().content;
        assert!(content.raw);
        assert_eq!(content.lines.len(), 1, "the cell as it is written");
        assert_eq!(
            content.format,
            ui::cell::Format::Json,
            "still known for what it is, so there is a way back"
        );

        press(&mut app, 'r');
        assert!(!app.inspect.as_ref().unwrap().content.raw);
    }

    /// A cell with nothing to recognise has nothing to switch to, and the key
    /// does not pretend otherwise.
    #[test]
    fn r_does_nothing_where_no_format_was_recognised() {
        let mut app = windowed("cellnojson.csv");
        press(&mut app, 'K');
        assert_eq!(
            app.inspect.as_ref().unwrap().content.format,
            ui::cell::Format::Text
        );
        press(&mut app, 'r');
        assert!(!app.inspect.as_ref().unwrap().content.raw);
    }

    /// End to end on a real log: it opens, the common keys are the columns,
    /// and `K` opens the nested one as the document it is.
    #[test]
    fn a_log_opens_and_its_nested_cells_are_documents() {
        let path = std::path::PathBuf::from("samples/log.jsonl");
        let mut app = App::new(Some(path.clone()));
        app.store = Some(Store::open_file(&path, 12).unwrap());
        app.last_frame_width = 120;

        let store = app.store.as_ref().unwrap();
        assert_eq!(store.row_count(), 10);
        assert!(
            store.notes().unwrap().contains("keys shown"),
            "and says what it left out"
        );

        // Every key, then walk to `job`, which is a document.
        command(&mut app, "reset select");
        cell_mode(&mut app);
        while app
            .store
            .as_ref()
            .unwrap()
            .column_info(app.cursor_col)
            .is_some_and(|(name, _)| name != "job")
        {
            press(&mut app, 'l');
        }
        app.cursor_to(2).unwrap();

        press(&mut app, 'K');
        let content = &app.inspect.as_ref().unwrap().content;
        assert_eq!(
            content.format,
            ui::cell::Format::Json,
            "the file's own bytes reached the window"
        );
        assert!(content.lines.len() > 1, "and were laid out as a document");
    }

    /// `:expand` typed on the line, the same path `:select` takes.
    #[test]
    fn expand_types_a_documents_keys_into_columns() {
        let path = std::path::PathBuf::from("samples/log.jsonl");
        let mut app = App::new(Some(path.clone()));
        app.store = Some(Store::open_file(&path, 12).unwrap());
        app.last_frame_width = 160;

        command(&mut app, "reset select");
        command(&mut app, "expand err");
        let said = app.message.clone().unwrap();
        assert!(said.contains("err expanded into"), "{said}");

        let shown = shown_columns(&app);
        assert!(shown.contains(&"err.code".to_string()), "{shown:?}");
        assert!(shown.contains(&"err.retryable".to_string()), "{shown:?}");
        assert!(
            !shown.contains(&"err".to_string()),
            "the parent gave up its place"
        );

        // Typed from what was inside it, so it filters as a number.
        let store = app.store.as_ref().unwrap();
        assert_eq!(store.schema.get("err.code"), Some(&DataType::Int64));
    }

    #[test]
    fn expand_names_the_column_it_cannot_open() {
        let path = std::path::PathBuf::from("samples/log.jsonl");
        let mut app = App::new(Some(path.clone()));
        app.store = Some(Store::open_file(&path, 12).unwrap());
        app.last_frame_width = 160;

        command(&mut app, "expand level");
        assert!(
            app.message
                .clone()
                .unwrap()
                .contains("no documents in level"),
            "{:?}",
            app.message
        );
        command(&mut app, "expand nosuchkey");
        assert!(
            app.message.clone().unwrap().contains("no column"),
            "{:?}",
            app.message
        );
    }

    /// The overlay calls itself the authoritative in-app reference, so a file
    /// that cannot be edited must still see the commands it does answer.
    #[test]
    fn the_help_for_a_read_only_file_still_names_the_view_commands() {
        // A frame with no file behind it: the viewer at its most read-only.
        let (_, path) = app_with("helpviews.csv", SAMPLE);
        let mut app = App::new(Some(path.clone()));
        let lf = crate::data::loader::load(&path).unwrap();
        app.store = Some(Store::new(lf, 12).unwrap());
        assert!(!app.store.as_ref().unwrap().is_editable());

        let headings: Vec<&str> = app.help_sections().iter().map(|(name, _)| *name).collect();
        assert!(headings.contains(&"Views"), "{headings:?}");
        assert!(
            !headings.contains(&"Edit"),
            "but not the ones it refuses: {headings:?}"
        );
    }

    /// The two views of a cell are independent: one covers, one displaces.
    #[test]
    fn the_window_and_the_strip_are_different_keys() {
        let mut app = windowed("cellboth.csv");
        strip(&mut app);
        assert!(app.cell_view);
        assert!(app.inspect.is_none(), "zk is the strip and only the strip");

        press(&mut app, 'K');
        assert!(app.inspect.is_some());
        assert!(app.cell_view, "which does not take the strip away");
    }

    #[test]
    fn a_column_can_be_widened_narrowed_and_put_back() {
        let mut app = app_sized("widths.csv", FOURCOL, 60);
        cell_mode(&mut app);
        let start = app.drawn_width(0);

        press(&mut app, 'z');
        press(&mut app, '>');
        let wider = *app.widths.get(&0).expect("a width was set");
        assert!(wider > start, "{wider} should be wider than {start}");

        press(&mut app, 'z');
        press(&mut app, '<');
        assert_eq!(*app.widths.get(&0).unwrap(), start, "back where it began");

        press(&mut app, 'z');
        press(&mut app, '=');
        assert!(app.widths.is_empty(), "and z= clears the lot");
    }

    /// `<`, `>` and `_` all need shift, and the shift goes down before the
    /// `z` does — so both keys arrive capitalised and neither half matched.
    #[test]
    fn shift_held_through_a_z_command_still_works() {
        let mut app = app_sized("shiftz.csv", FOURCOL, 60);
        cell_mode(&mut app);
        let start = app.drawn_width(0);

        // Shift held from before the prefix: `Z` then `>`.
        key(
            &mut app,
            KeyEvent::new(KeyCode::Char('Z'), KeyModifiers::SHIFT),
        );
        assert_eq!(app.pending_prefix, Some('z'), "`Z` opens the prefix too");
        key(
            &mut app,
            KeyEvent::new(KeyCode::Char('>'), KeyModifiers::SHIFT),
        );
        assert!(app.widths.get(&0).is_some_and(|&w| w > start));
    }

    #[test]
    fn a_shifted_second_key_still_reaches_the_unshifted_command() {
        // A file with room to scroll: FOURCOL has two rows, so `zt` would
        // have nowhere to put anything.
        let mut app = tall_app("shiftzz.csv");
        app.cursor_to(20).unwrap();
        // `ZT` should be `zt`, not nothing.
        key(
            &mut app,
            KeyEvent::new(KeyCode::Char('Z'), KeyModifiers::SHIFT),
        );
        key(
            &mut app,
            KeyEvent::new(KeyCode::Char('T'), KeyModifiers::SHIFT),
        );
        assert_eq!(
            app.store.as_ref().unwrap().row_offset,
            20,
            "zt put the cursor row at the top"
        );
    }

    #[test]
    fn a_width_belongs_to_the_column_not_to_its_place_on_screen() {
        // `:select` renumbers the display positions; a width set before it
        // has to follow its own column.
        let mut app = app_sized("widthview.csv", FOURCOL, 60);
        cell_mode(&mut app);
        press(&mut app, 'l'); // display 1 is source column `b`
        press(&mut app, 'z');
        press(&mut app, '>');
        let set = *app.widths.get(&1).expect("keyed by source column");

        command(&mut app, "select d b");
        assert_eq!(
            app.widths.get(&1),
            Some(&set),
            "`b` keeps its width at its new position"
        );
    }

    #[test]
    fn fitting_a_column_uses_the_widest_value_on_screen() {
        let mut app = app_sized("fit.csv", "a,b\nshort,x\nmuch longer value,y\n", 60);
        cell_mode(&mut app);
        press(&mut app, 'z');
        press(&mut app, '_');
        assert_eq!(
            app.widths.get(&0),
            Some(&"much longer value".len()),
            "the widest value on the page, not a guess"
        );
    }

    #[test]
    fn a_column_cannot_be_narrowed_away_entirely() {
        let mut app = app_sized("narrow.csv", FOURCOL, 60);
        cell_mode(&mut app);
        for _ in 0..20 {
            press(&mut app, 'z');
            press(&mut app, '<');
        }
        assert_eq!(*app.widths.get(&0).unwrap(), ui::MIN_COLUMN);
    }

    #[test]
    fn hash_switches_between_relative_and_absolute_row_numbers() {
        let (mut app, _) = app_with("gutter.csv", SAMPLE);
        assert!(app.relative_rows, "counting from the cursor is the default");

        press(&mut app, '#');
        assert!(!app.relative_rows);
        press(&mut app, '#');
        assert!(app.relative_rows);
    }

    #[test]
    fn a_question_mark_is_a_character_while_typing() {
        let (mut app, _) = app_with("help.csv", SAMPLE);

        press(&mut app, 'c');
        press(&mut app, '?');
        assert!(!app.help_visible, "'?' belongs to the cell being typed");
        assert_eq!(app.edit_buf, "?");

        key(&mut app, KeyCode::Esc);
        press(&mut app, '?');
        assert!(app.help_visible, "and opens the overlay in normal mode");
    }

    /// Sorting runs off the main thread; drain it the way the event loop does.
    fn settle_sort(app: &mut App) {
        for _ in 0..2000 {
            if app.sort_rx.is_none() {
                return;
            }
            if !app.poll_sort() {
                std::thread::sleep(std::time::Duration::from_millis(1));
            }
        }
        panic!("the sort never finished");
    }

    #[test]
    fn a_sorted_view_can_be_edited_once_the_sort_is_held() {
        let (mut app, path) = app_with("sorted.csv", SAMPLE);
        app.last_frame_width = 60;
        cell_mode(&mut app);
        press(&mut app, 's'); // by name, ascending
        settle_sort(&mut app);
        press(&mut app, 's'); // and again: descending, so `d` is on top
        settle_sort(&mut app);

        press(&mut app, 'l');
        press(&mut app, 'c');
        typed(&mut app, "99");
        key(&mut app, KeyCode::Enter);
        assert_eq!(shown(&app, 1, 0).as_deref(), Some("99"));

        command(&mut app, "w");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "name,count\na,1\nb,2\nc,99\n",
            "the top row of a descending sort is the file's last line"
        );
    }

    #[test]
    fn editing_the_caret_inside_the_buffer() {
        let (mut app, _) = app_with("caretmove.csv", SAMPLE);

        press(&mut app, 'c');
        typed(&mut app, "abc");
        key(&mut app, KeyCode::Left);
        typed(&mut app, "X");
        assert_eq!(app.edit_buf, "abXc");

        key(&mut app, KeyCode::Home);
        key(&mut app, KeyCode::Delete);
        assert_eq!(app.edit_buf, "bXc");

        key(&mut app, KeyCode::End);
        key(&mut app, KeyCode::Backspace);
        assert_eq!(app.edit_buf, "bX");
    }
}