datui-lib 0.4.0

Data Exploration in the Terminal (library)
Documentation
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
//! The home screen.
//!
//! # Design
//!
//! This is the first screen datui has that is *designed* rather than assembled, so
//! the choices are deliberate and worth stating:
//!
//! - **No boxes.** The default TUI look is borders around everything; it reads as
//!   busy and dated. Structure comes from alignment and negative space instead, with
//!   a single vertical rule where two panes genuinely need separating.
//! - **One accent, spent carefully.** The theme's accent appears in four places: the
//!   wordmark, section headers, the selection marker, and the prompt. Everything else
//!   is primary, secondary or dim text. Restraint is what reads as professional.
//! - **Metadata right-aligns into columns.** Ragged trailing text looks accidental;
//!   a clean column looks designed, and it makes datasets comparable at a glance.
//! - **Typed columns are the signature.** The schema preview colours each type with
//!   the same palette the table uses. No file picker tells you the shape of your data
//!   before you open it — this is the thing worth being known for, and it is why the
//!   preview pane earns its width.
//!
//! Everything is drawn from the active theme, so on Omarchy this inherits the desktop
//! palette and sits in the same visual family as the rest of the system.

use crate::discover::{self, Entry, EntryKind};
use crate::formats::MatchChip;
use crate::glyphs;
use crate::render::context::RenderContext;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Widget};

/// Width reserved for the right-aligned metadata columns in the list.
const META_WIDTH: u16 = 34;
/// Width given to the preview pane when there is room for it.
const PREVIEW_WIDTH: u16 = 40;
/// Below this, showing the preview would squeeze the list under [`META_MIN_WIDTH`]
/// and cost every row its size and shape. The scent is what the list is *for*, so the
/// preview yields first.
const PREVIEW_MIN_WIDTH: u16 = META_MIN_WIDTH + PREVIEW_WIDTH + 6;
/// Below this even the metadata columns have to go.
const META_MIN_WIDTH: u16 = 56;

/// Truncate from the left, keeping the tail, to at most `width` display columns.
///
/// Paths are identified by their leaf, so the end is the part worth keeping. The
/// ellipsis is measured rather than assumed to be one column: it is three characters
/// wide when datui has fallen back to ASCII.
fn truncate_start(text: &str, width: usize) -> String {
    if glyphs::display_width(text) <= width {
        return text.to_string();
    }
    let ellipsis = glyphs::get().ellipsis;
    let ellipsis_width = glyphs::display_width(ellipsis);
    if width <= ellipsis_width {
        return glyphs::take_columns_end(text, width).to_string();
    }
    let tail = glyphs::take_columns_end(text, width - ellipsis_width);
    format!("{ellipsis}{tail}")
}

/// The three metadata columns, already padded to fixed widths so they align down the
/// list. Empty strings where a fact is genuinely unknown — a CSV's row count cannot
/// be had without scanning it, and inventing one would be worse than a blank.
/// `unmeasured` puts an ellipsis where the shape would go: the row is a dataset
/// nothing has read yet, and a blank there beside rows that have a shape reads as
/// broken. The same admission the label makes for a directory nothing has looked into.
///
/// `hint` is what a catalog says the file weighs, shown as `~33 MB` until something
/// has measured it. `gone` takes the size's place for a web file that cannot be had
/// (`HTTP 404`, `no answer`): beside the name, where the choice to open it is made.
fn meta_columns(entry: &Entry, unmeasured: bool, hint: Option<u64>, gone: Option<&str>) -> String {
    // A dataset too large to count still knows its width. Showing `? x 158` says more
    // than a blank, and the `?` is an admission rather than a guess.
    let times = glyphs::get().times;
    // A column count read from a spread of a directory rather than all of it is a floor,
    // so it says so, the way the row count already says `?` when it is out of reach.
    let more = if entry.cols_sampled { "+" } else { "" };
    let shape = match (entry.rows, entry.cols) {
        (Some(r), Some(c)) => format!("{} {times} {c}{more}", discover::format_rows(r)),
        // `?` says a count is out of reach. A directory that is not one table has no row
        // count to be out of reach — a sum over unrelated tables is not a number — so
        // it shows its width alone. Named, not multiplied: `× 72` in a column whose
        // neighbours read `1.2M × 72` is an operator with nothing on its left, and a
        // bare `72` reads as a row count.
        (None, Some(c)) if entry.kind == EntryKind::Directory => format!("{c}{more} cols"),
        (None, Some(c)) => format!("? {times} {c}{more}"),
        _ if unmeasured => glyphs::get().ellipsis.to_string(),
        _ => String::new(),
    };
    let size = match (gone, entry.size, hint) {
        (Some(gone), _, _) => gone.to_string(),
        (None, Some(size), _) => discover::format_size(size),
        (None, None, Some(hint)) => format!("~{}", discover::format_size(hint)),
        (None, None, None) => String::new(),
    };
    let age = entry.modified.map(discover::format_age).unwrap_or_default();
    format!("{shape:>13}  {size:>9}  {age:>4}")
}

pub fn render(area: Rect, buf: &mut Buffer, app: &mut crate::App, ctx: &RenderContext) {
    Clear.render(area, buf);

    // One column of breathing room, no more. Vertical space is the scarce thing in a
    // terminal: every blank line here is a dataset the user cannot see.
    let padded = Rect {
        x: area.x.saturating_add(1),
        y: area.y,
        width: area.width.saturating_sub(2),
        height: area.height,
    };
    if padded.width < 20 || padded.height < 5 {
        return;
    }

    // The wordmark costs two rows more than the title bar, and twenty-five columns
    // beside the path. On a big terminal that is nothing; on a short one it is two
    // datasets, and on a narrow one the path beside it is all ellipsis — so in
    // either case the one-line bar comes back.
    let wordmark = glyphs::get()
        .wordmark
        .filter(|_| padded.height >= WORDMARK_MIN_HEIGHT && padded.width >= WORDMARK_MIN_WIDTH);
    let title_h = wordmark.map(|w| w.len() as u16).unwrap_or(1);
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(title_h), // title bar or wordmark
            Constraint::Length(1),       // prompt
            Constraint::Fill(1),         // body
        ])
        .split(padded);

    match wordmark {
        Some(lines) => render_wordmark(rows[0], buf, app, ctx, lines),
        None => render_title_bar(rows[0], buf, app, ctx),
    }
    render_prompt(rows[1], buf, app, ctx);

    let show_preview = padded.width >= PREVIEW_MIN_WIDTH;
    if show_preview {
        // The list keeps a reading measure on a wide screen, so a row's size and age sit
        // near its name; the pane, which has rows to show, takes the rest (#547 M8).
        let list_w = padded
            .width
            .saturating_sub(3 + PREVIEW_WIDTH)
            .min(LIST_MAX_WIDTH);
        let body = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(list_w),
                Constraint::Length(3), // the rule and its gutters
                Constraint::Fill(1),
            ])
            .split(rows[2]);
        render_list(body[0], buf, app, ctx);
        render_rule(body[1], buf, ctx);
        render_preview(body[2], buf, app, ctx, area.height);
    } else {
        let used = render_list(rows[2], buf, app, ctx);
        render_rows_strip(rows[2], used, buf, app, ctx, area.height);
    }
}

/// The widest the list gets. Past it the facts on the right of a row drift away from
/// its name, and the pane has better use for the columns.
const LIST_MAX_WIDTH: u16 = 84;

/// The fewest rows the bottom strip is drawn in: its heading, the column names and
/// two rows.
const STRIP_MIN_HEIGHT: usize = 4;

/// Below the pane's width, the selected file's first rows in the rows the list leaves
/// free at the bottom of the screen. Never over the list: with no rows to spare there
/// is no strip, and nothing is read for one.
fn render_rows_strip(
    area: Rect,
    used: usize,
    buf: &mut Buffer,
    app: &mut crate::App,
    ctx: &RenderContext,
    screen_height: u16,
) {
    let free = (area.height as usize).saturating_sub(used);
    if free < STRIP_MIN_HEIGHT || app.home.path_input_active {
        return;
    }
    let Some(entry) = app.home.selected_entry() else {
        return;
    };
    let Some(preview) = app.home_preview_rows(&entry, screen_height) else {
        return;
    };
    // A blank line between the list and the strip when there is one to spare.
    let room = free.saturating_sub(1).max(STRIP_MIN_HEIGHT);
    let lines = rows_block(&preview, area.width as usize, room, ctx);
    let height = lines.len() as u16;
    let strip = Rect {
        x: area.x,
        y: area.y + area.height - height,
        width: area.width,
        height,
    };
    Paragraph::new(lines).render(strip, buf);
}

/// The `ROWS` block: a heading, the leading columns' names in their types' colors, and
/// as many of the first rows as `room` lines leave, in columns as many as `width` fits.
fn rows_block(
    preview: &crate::home_preview::PreviewRows,
    width: usize,
    room: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    const CELL_W: usize = 20;
    const GAP: usize = 2;
    let g = glyphs::get();
    let null_w = glyphs::display_width(g.null);
    // Each column as wide as its name or its widest cell shown, up to a cap.
    let widths: Vec<usize> = preview
        .columns
        .iter()
        .enumerate()
        .map(|(i, (name, _))| {
            preview
                .rows
                .iter()
                .map(|row| match &row[i] {
                    Some(text) => glyphs::display_width(text),
                    None => null_w,
                })
                .chain([glyphs::display_width(name)])
                .max()
                .unwrap_or(1)
                .clamp(1, CELL_W)
        })
        .collect();
    let mut shown = 0;
    let mut used = 0;
    for w in &widths {
        let need = if shown == 0 { *w } else { GAP + *w };
        if used + need > width {
            break;
        }
        used += need;
        shown += 1;
    }
    // A first column wider than the space is cut to it rather than left out.
    let widths: Vec<usize> = if shown == 0 {
        vec![width.max(1)]
    } else {
        widths[..shown].to_vec()
    };
    let shown = widths.len().min(preview.columns.len());
    let mut lines = vec![rows_heading(shown, preview.total_columns, width, ctx)];
    let cell = |text: &str, w: usize, right: bool| -> String {
        let text = if glyphs::display_width(text) > w {
            let cut =
                glyphs::take_columns(text, w.saturating_sub(glyphs::display_width(g.ellipsis)));
            format!("{cut}{}", g.ellipsis)
        } else {
            text.to_string()
        };
        let pad = w.saturating_sub(glyphs::display_width(&text));
        if right {
            format!("{}{text}", " ".repeat(pad))
        } else {
            format!("{text}{}", " ".repeat(pad))
        }
    };
    let numeric: Vec<bool> = preview.columns[..shown]
        .iter()
        .map(|(_, dtype)| crate::numfmt::is_numeric_dtype(dtype))
        .collect();
    let mut header = Vec::new();
    for (i, (name, dtype)) in preview.columns[..shown].iter().enumerate() {
        if i > 0 {
            header.push(Span::raw(" ".repeat(GAP)));
        }
        header.push(Span::styled(
            cell(name, widths[i], numeric[i]),
            Style::default().fg(ctx.type_color(dtype)),
        ));
    }
    lines.push(Line::from(header));
    let rows_room = room.saturating_sub(lines.len());
    for row in preview.rows.iter().take(rows_room) {
        let mut spans = Vec::new();
        for (i, value) in row[..shown].iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw(" ".repeat(GAP)));
            }
            spans.push(match value {
                Some(text) => Span::styled(
                    cell(text, widths[i], numeric[i]),
                    Style::default().fg(ctx.text_primary),
                ),
                None => Span::styled(
                    cell(g.null, widths[i], numeric[i]),
                    Style::default().fg(ctx.dimmed),
                ),
            });
        }
        lines.push(Line::from(spans));
    }
    lines
}

/// `ROWS` on a rule, and how many of the columns the block shows when not all of them.
fn rows_heading(shown: usize, total: usize, width: usize, ctx: &RenderContext) -> Line<'static> {
    let note = (shown < total).then(|| format!("{shown} of {total} columns"));
    pane_heading_counted("ROWS", note.as_deref(), width, ctx)
}

/// Below this many rows the wordmark gives way to the one-line title bar.
const WORDMARK_MIN_HEIGHT: u16 = 28;
/// Below this width, the wordmark's twenty-five columns leave the path beside it
/// nothing but its own ellipsis.
const WORDMARK_MIN_WIDTH: u16 = 52;

/// Interpolate two colours, when both are RGB. Anything else — a named ANSI colour,
/// an indexed one, the terminal default — has no arithmetic, so the first stop is
/// used for every column and the wordmark is simply the accent.
fn mix(a: Color, b: Color, t: f32) -> Color {
    match (a, b) {
        (Color::Rgb(r1, g1, b1), Color::Rgb(r2, g2, b2)) => {
            let lerp =
                |x: u8, y: u8| -> u8 { (x as f32 + (y as f32 - x as f32) * t).round() as u8 };
            Color::Rgb(lerp(r1, r2), lerp(g1, g2), lerp(b1, b2))
        }
        _ => a,
    }
}

/// The wordmark: three rows of box drawing, coloured column by column along the
/// theme's gradient. Once, here, and nowhere else — a gradient on data would be
/// decoration. The location sits beside the middle row where the title bar used to
/// put it.
fn render_wordmark(
    area: Rect,
    buf: &mut Buffer,
    app: &crate::App,
    ctx: &RenderContext,
    lines: &[&str],
) {
    let location = app
        .home
        .browsing
        .as_ref()
        .map(|p| app.home.location_label(p))
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|p| crate::home::display_path(&p))
        })
        .unwrap_or_default();
    let mark_w = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
    let start = ctx.gradient_start;
    let end = ctx.gradient_end;
    for (row, line) in lines.iter().enumerate() {
        if row as u16 >= area.height {
            break;
        }
        let mut spans: Vec<Span> = Vec::with_capacity(mark_w + 2);
        spans.push(Span::raw(" "));
        for (i, ch) in line.chars().enumerate() {
            let t = if mark_w > 1 {
                i as f32 / (mark_w - 1) as f32
            } else {
                0.0
            };
            spans.push(Span::styled(
                ch.to_string(),
                Style::default()
                    .fg(mix(start, end, t))
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if row == lines.len() / 2 {
            let room = (area.width as usize).saturating_sub(mark_w + 4);
            spans.push(Span::styled(
                format!("   {}", truncate_start(&location, room)),
                Style::default().fg(ctx.text_secondary),
            ));
        }
        Paragraph::new(Line::from(spans)).render(
            Rect {
                x: area.x,
                y: area.y + row as u16,
                width: area.width,
                height: 1,
            },
            buf,
        );
    }
}

/// A filled bar carrying the name and current location, mirroring the control bar at
/// the foot of the screen so the list sits between two anchors.
fn render_title_bar(area: Rect, buf: &mut Buffer, app: &crate::App, ctx: &RenderContext) {
    let location = app
        .home
        .browsing
        .as_ref()
        .map(|p| app.home.location_label(p))
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|p| crate::home::display_path(&p))
        })
        .unwrap_or_default();

    let bar = Style::default().bg(ctx.controls_bg);
    let left = Span::styled(
        " datui ",
        bar.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
    );
    // Keep the tail of a long path; the leaf is what tells you where you are.
    let location = truncate_start(&location, (area.width as usize).saturating_sub(12));
    let pad = (area.width as usize).saturating_sub(8 + location.chars().count());
    Paragraph::new(Line::from(vec![
        left,
        Span::styled(" ".repeat(pad), bar),
        Span::styled(location, bar.fg(ctx.text_secondary)),
        Span::styled(" ", bar),
    ]))
    .render(area, buf);
}

fn render_prompt(area: Rect, buf: &mut Buffer, app: &crate::App, ctx: &RenderContext) {
    let home = &app.home;
    let g = glyphs::get();
    // Placeholders name what the field takes, rather than instructing you to type
    // in the box the cursor is already sitting in. The filter one earns its space by
    // saying the part that is not obvious: typing searches below here as well.
    let (glyph, value, hint) = if home.path_input_active {
        (" ~ ", home.path_input.as_str(), "file or directory")
    } else {
        (g.prompt, home.filter.as_str(), "narrow and search")
    };

    let mut spans = vec![Span::styled(
        glyph,
        Style::default()
            .fg(ctx.keybind_hints)
            .add_modifier(Modifier::BOLD),
    )];
    // A filter kept from before is shown selected: typing replaces it.
    let value_style = if !home.path_input_active && home.filter_selected {
        app.theme.text_selection_style()
    } else {
        Style::default().fg(ctx.text_primary)
    };
    spans.push(Span::styled(value, value_style));
    spans.push(Span::styled(
        g.cursor,
        Style::default().fg(ctx.keybind_hints),
    ));
    if value.is_empty() {
        spans.push(Span::styled(
            format!("  {hint}"),
            Style::default().fg(ctx.dimmed),
        ));
    }
    if let Some(status) = &home.status {
        // Keep the tail: these read "\"<long path>\": <reason>", and the
        // reason is the part worth the space. The name is already on the row.
        let used: usize = spans.iter().map(|s| s.content.chars().count()).sum();
        let room = (area.width as usize).saturating_sub(used + 3);
        spans.push(Span::styled(
            format!("   {}", truncate_start(status, room)),
            Style::default().fg(ctx.warning),
        ));
    }
    Paragraph::new(Line::from(spans)).render(area, buf);
}

/// A single hairline between list and preview. One rule, not two borders.
fn render_rule(area: Rect, buf: &mut Buffer, ctx: &RenderContext) {
    if area.width == 0 {
        return;
    }
    let x = area.x + area.width / 2;
    for y in area.y..area.y.saturating_add(area.height) {
        if let Some(cell) = buf.cell_mut((x, y)) {
            cell.set_symbol(glyphs::get().rule);
            cell.set_fg(ctx.column_separator);
        }
    }
}

/// Draw the list; returns how many of its lines it used, or all of them when it
/// drew a message rather than rows.
fn render_list(area: Rect, buf: &mut Buffer, app: &mut crate::App, ctx: &RenderContext) -> usize {
    if app.home.path_input_active {
        return render_path_list(area, buf, app, ctx);
    }
    // Where this frame starts and how many rows it has room for. Settled before
    // anything borrows the listing, because both the scroll below and the decision
    // about what is worth looking into are made from it.
    let height = area.height as usize;
    // With room to spare, a blank line before every header but the first. At most
    // five sections, so at most four lines, and below thirty the list is as dense as
    // it can be. The spacers come off the height the cap on RECENT is a share of.
    let spaced = height >= SPACED_LIST_HEIGHT;
    let headers = app
        .home
        .visible()
        .iter()
        .filter(|row| matches!(row, crate::home::Row::Header { .. }))
        .count();
    let spacers = if spaced { headers.saturating_sub(1) } else { 0 };
    // The height first: the cap on RECENT is a share of it, and the cursor has to be
    // put back on its row before the scroll is settled from it.
    app.home.set_view_height(height.saturating_sub(spacers));
    // Where each row lands as a line, spacers counted, so the scroll is settled in
    // lines and the selected row is on screen however many spacers sit above it.
    let row_lines: Vec<usize> = {
        let mut line = 0;
        app.home
            .visible()
            .iter()
            .enumerate()
            .map(|(i, row)| {
                if spaced && i > 0 && matches!(row, crate::home::Row::Header { .. }) {
                    line += 1;
                }
                let at = line;
                line += 1;
                at
            })
            .collect()
    };
    // The view stays where the last frame left it unless the cursor would leave it.
    let total = row_lines.last().map_or(0, |line| line + 1);
    let first_line = crate::home::settle_top(
        row_lines.get(app.home.scroll).copied().unwrap_or(total),
        row_lines.get(app.home.selected).copied().unwrap_or(0),
        height,
        total,
    );
    // As a row index, for the passes that look into what is on screen and for the
    // next frame. A view that would open on a spacer opens on the header below it.
    app.home.scroll = row_lines.partition_point(|line| *line < first_line);
    let first_line = row_lines
        .get(app.home.scroll)
        .copied()
        .unwrap_or(first_line);
    // Which row each line of the list shows, for a click; a spacer shows none.
    let lines_drawn = (0..height)
        .map(|dy| row_lines.binary_search(&(first_line + dy)).ok())
        .collect();
    app.pointer.home_list_drawn(area, lines_drawn);

    // Nothing is read here. Rows carry whatever a worker has measured so far, and
    // the request for more is made after the frame, not during it.
    app.home.pending_enrich = !app.home.unmeasured_visible(1).is_empty();
    app.home.pending_classify = !app.home.unclassified_visible(1).is_empty();
    app.home.pending_peek = !app.home.cloud_directories_to_peek(1).is_empty();
    let awaiting = app.home.awaiting_listing().map(|d| d.to_path_buf());
    let since = match awaiting {
        Some(_) => Some(
            *app.home
                .waiting_since
                .get_or_insert_with(std::time::Instant::now),
        ),
        None => {
            app.home.waiting_since = None;
            None
        }
    };
    let visible = app.home.visible();

    if let (Some(dir), Some(since), true) = (&awaiting, since, visible.is_empty()) {
        let spinner = glyphs::get().spinner;
        let mut spans = vec![
            Span::styled(
                spinner[app.throbber_frame as usize % spinner.len()],
                Style::default().fg(ctx.accent),
            ),
            Span::raw(" "),
            Span::styled(
                format!("Listing {}", crate::home::display_path(dir)),
                Style::default().fg(ctx.text_secondary),
            ),
        ];
        let secs = since.elapsed().as_secs();
        if secs >= 1 {
            spans.push(Span::styled(
                format!("  {secs}s"),
                Style::default().fg(ctx.dimmed),
            ));
        }
        Paragraph::new(Line::from(spans)).render(area, buf);
        return area.height as usize;
    }

    if app.home.listing_in_flight && visible.is_empty() {
        Paragraph::new(Line::from(Span::styled(
            "Looking...",
            Style::default().fg(ctx.dimmed),
        )))
        .render(area, buf);
        return area.height as usize;
    }

    if visible.is_empty() && !app.home.filter.is_empty() {
        // Browsed into a directory, the blank answer must say where it looked: a
        // filter that misses a sibling of the current directory reads as a bug
        // until the reader notices the header path.
        let text = match &app.home.browsing {
            Some(dir) => format!("No match under {}.", crate::home::display_path(dir)),
            None => "No match.".to_string(),
        };
        Paragraph::new(Line::from(Span::styled(
            text,
            Style::default().fg(ctx.dimmed),
        )))
        .render(area, buf);
        return area.height as usize;
    }

    // Guidance shows whenever there is nothing openable — not only when the list is
    // literally empty. A first run in a directory holding one subdirectory would
    // otherwise present a bare listing with no hint of what datui is for, which is the
    // worst possible first impression for a screen meant to be the way in.
    //
    // Counted over every section, folded or not: with everything folded the headers
    // are the content, and a hint that says there is nothing here would be wrong.
    let has_dataset = app.home.has_any_dataset();
    // Cloud sources are something to browse too, so they count as content.
    let guidance = if has_dataset || !app.home.filter.is_empty() || !app.home.cloud.is_empty() {
        Vec::new()
    } else {
        vec![
            Line::from(""),
            Line::from(Span::styled(
                "No datasets here.",
                Style::default().fg(ctx.text_secondary),
            )),
            Line::from(""),
            Line::from(vec![
                Span::styled("  ~  ", Style::default().fg(ctx.keybind_hints)),
                Span::styled("type a path", Style::default().fg(ctx.dimmed)),
            ]),
            Line::from(vec![
                Span::styled("     ", Style::default()),
                Span::styled(
                    "or list datasets in catalog.toml",
                    Style::default().fg(ctx.dimmed),
                ),
            ]),
        ]
    };

    let show_meta = area.width >= META_MIN_WIDTH;
    let name_width = if show_meta {
        area.width.saturating_sub(META_WIDTH) as usize
    } else {
        area.width as usize
    };

    // Sources a URL can name. Taken from the config rather than from the sources
    // listed so far, so a source that is hidden or still being discovered is not
    // reported as missing.
    let known_sources: Vec<String> = app
        .app_config
        .cloud
        .connections
        .iter()
        .map(|s| s.name.clone())
        .collect();
    let list = ListDraw {
        ctx,
        width: area.width as usize,
        name_width,
        show_meta,
        filter: &app.home.filter,
        frame: app.throbber_frame as usize,
    };
    let mut lines: Vec<Line> = Vec::new();
    // Only the rows on screen are drawn: a search can list a thousand, and building a
    // line for each on every frame was most of what a keystroke cost.
    let last_line = first_line + height;
    for (idx, row) in visible.iter().enumerate() {
        let at = row_lines.get(idx).copied().unwrap_or(usize::MAX);
        if at >= last_line {
            break;
        }
        let spacer = spaced && idx > 0 && matches!(row, crate::home::Row::Header { .. });
        if spacer && at > first_line {
            lines.push(Line::from(""));
        }
        if at < first_line {
            continue;
        }
        let selected = idx == app.home.selected;
        match row {
            crate::home::Row::Header {
                section,
                matches,
                collapsed,
            } => {
                lines.push(section_header(
                    &app.home.sections[*section],
                    *matches,
                    *collapsed,
                    selected,
                    &list,
                ));
            }
            crate::home::Row::Entry { entry, .. }
                if crate::home::cloud_source_id(&entry.path).is_some() =>
            {
                let source = app.home.cloud_source_of(&entry.path);
                lines.push(source_line(
                    entry,
                    source,
                    selected,
                    area.width as usize,
                    app.throbber_frame as usize,
                    &app.home.filter,
                    ctx,
                ));
            }
            crate::home::Row::Entry { entry, nested, .. } => {
                // When a row is here because of a column rather than its name, say so:
                // otherwise it reads as the filter having gone wrong.
                let via = if crate::home::fuzzy_score(&app.home.filter, &entry.name).is_some() {
                    None
                } else {
                    crate::home::matching_column(&app.home.filter, entry)
                };
                lines.push(entry_line(
                    entry,
                    selected,
                    EntryNotes {
                        matched_column: via,
                        // Inside a source the trail already names it.
                        known_sources: app
                            .home
                            .browsing
                            .is_none()
                            .then_some(known_sources.as_slice()),
                        place_kind: app.home.place_kind(&entry.path),
                        looking: looking_glyph(app, entry),
                        indent: if *nested { NEST_INDENT } else { 0 },
                        size_hint: app.home.size_hint(&entry.path),
                        gone: app.home.web_gone.get(&entry.path).map(|g| g.cell.as_str()),
                    },
                    &list,
                ));
            }
            // Drawn exactly like an entry, because to look at it is one: a row in
            // the directory's list with a name, a shape and a size. What it is not is a
            // row *of* the directory, which is why it arrives here by its own variant.
            crate::home::Row::Door { entry, .. } => {
                lines.push(entry_line(
                    entry,
                    selected,
                    EntryNotes {
                        place_kind: app.home.place_kind(&entry.path),
                        looking: looking_glyph(app, entry),
                        ..EntryNotes::default()
                    },
                    &list,
                ));
            }
            crate::home::Row::Place {
                path,
                label,
                source,
                ..
            } => {
                lines.push(place_line(
                    path,
                    label.as_deref(),
                    source.as_deref(),
                    selected,
                    name_width,
                    show_meta,
                    ctx,
                ));
            }
            crate::home::Row::More { hidden, places, .. } => {
                lines.push(more_line(
                    *hidden, *places, selected, name_width, show_meta, ctx,
                ));
            }
            crate::home::Row::Hidden { section, count } => {
                let tables = holds_tables(&app.home.sections[*section]);
                lines.push(hidden_line(
                    *count, tables, selected, name_width, show_meta, ctx,
                ));
            }
        }
    }

    let mut body: Vec<Line> = lines;
    body.extend(guidance);
    let used = body.len();
    Paragraph::new(body).render(area, buf);
    used
}

/// While `~` is typed, the list is the directory being typed: its names that the last
/// segment matches, best first, with the one ↑↓ picked on the rail (#547 M6).
fn render_path_list(
    area: Rect,
    buf: &mut Buffer,
    app: &mut crate::App,
    ctx: &RenderContext,
) -> usize {
    let g = glyphs::get();
    let height = area.height as usize;
    let width = area.width as usize;
    // No row of the home list is under the pointer meanwhile.
    app.pointer.home_list_drawn(area, vec![None; height]);
    let home = &app.home;
    let dir = crate::home::typed_dir(&home.path_input);
    let segment = &home.path_input[dir.len()..];
    let listing = home.path_listing.as_ref().filter(|l| l.dir == dir);
    let candidates = home.path_candidates();
    let shown_dir = if dir.is_empty() { "./" } else { dir };
    let count = format!("{}", candidates.len());
    let rule_w = width.saturating_sub(shown_dir.chars().count() + count.chars().count() + 6);
    let mut lines = vec![Line::from(vec![
        Span::styled(g.expanded, Style::default().fg(ctx.accent)),
        Span::styled(
            truncate_start(shown_dir, width.saturating_sub(count.len() + 8)),
            Style::default().fg(ctx.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(format!("  {count}  "), Style::default().fg(ctx.dimmed)),
        Span::styled(
            g.rule_h.repeat(rule_w),
            Style::default().fg(ctx.column_separator),
        ),
    ])];
    let note = match listing {
        None => Some(format!("Listing {shown_dir}...")),
        Some(l) if l.failed => Some(format!("Nothing to list at {shown_dir}")),
        Some(_) if candidates.is_empty() && !segment.is_empty() => {
            Some(format!("No name here starts like {segment}"))
        }
        Some(_) if candidates.is_empty() => Some("Nothing here".to_string()),
        Some(_) => None,
    };
    if let Some(note) = note {
        lines.push(Line::from(Span::styled(
            format!("  {note}"),
            Style::default().fg(ctx.dimmed),
        )));
    }
    // The picked row stays on screen: the list scrolls under it.
    let room = height.saturating_sub(lines.len());
    let pick = home.path_pick;
    let first = match pick {
        Some(p) if p >= room.saturating_sub(1) => p + 2 - room.max(1),
        _ => 0,
    };
    let hidden_after = candidates.len().saturating_sub(first + room);
    let take = if hidden_after > 0 {
        room.saturating_sub(1)
    } else {
        room
    };
    for (i, name) in candidates.iter().enumerate().skip(first).take(take) {
        let selected = pick == Some(i);
        let base = if selected {
            ctx.highlight_style()
        } else {
            Style::default()
        };
        let marker = if selected {
            g.selector
        } else {
            g.selector_blank
        };
        let mut text = name.name.clone();
        if name.dir {
            text.push('/');
        }
        let positions = crate::home::fuzzy_positions(segment, &name.name);
        let name_style = if selected {
            base.fg(ctx.text_primary).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(ctx.text_primary)
        };
        let hit_style = base
            .fg(ctx.keybind_hints)
            .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
        let mut spans = vec![Span::styled(
            marker,
            base.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
        )];
        spans.extend(highlight_spans(&text, &positions, name_style, hit_style));
        let used = glyphs::display_width(marker) + glyphs::display_width(&text);
        spans.push(Span::styled(" ".repeat(width.saturating_sub(used)), base));
        lines.push(Line::from(spans));
    }
    if hidden_after > 0 {
        lines.push(Line::from(Span::styled(
            format!("  {} {hidden_after} more", g.ellipsis),
            Style::default().fg(ctx.dimmed),
        )));
    }
    let used = lines.len();
    Paragraph::new(lines).render(area, buf);
    used
}

/// How far a row under a place is drawn in. Two cells: enough to read as "under",
/// not enough to cost a name its tail.
const NEST_INDENT: usize = 2;

/// The list height from which a blank line precedes every section header but the
/// first. Below it every row is content.
const SPACED_LIST_HEIGHT: usize = 30;

/// What [`meta_columns`] draws: shape, size and age, each right-aligned in a fixed
/// cell. A row that has no meta columns of its own is drawn to the same edge, so
/// the width is named here rather than measured on every row.
const META_COLUMNS_WIDTH: usize = 13 + 2 + 9 + 2 + 4;
/// The shape cell and the gap after it, at the head of the meta columns.
const SHAPE_COLUMNS_WIDTH: usize = 13 + 2;

/// Where an entry row drawn with `name_width` ends: the marker, the name's cells, the
/// meta columns when shown, and one cell of air. The rows that carry no meta columns
/// of their own — a place, the `more` row — are drawn to this same edge.
fn row_width(name_width: usize, show_meta: bool) -> usize {
    let marker = glyphs::get().selector_blank.chars().count();
    marker + name_width + if show_meta { META_COLUMNS_WIDTH } else { 0 } + 1
}

/// The place a group of recents lives in: its path with a trailing slash, and at the
/// far right the filesystem it is on.
///
/// Quiet on purpose. It is a heading for the rows under it, not a row to open in its
/// own right, so it takes the secondary text color and no locality glyph, and the
/// filesystem name is the one fact it carries: the same word the rows' glyph stands
/// for, spelled out once for the group rather than once per row.
fn place_line(
    path: &std::path::Path,
    label: Option<&str>,
    source: Option<&str>,
    selected: bool,
    name_width: usize,
    show_meta: bool,
    ctx: &RenderContext,
) -> Line<'static> {
    let g = glyphs::get();
    let width = row_width(name_width, show_meta);
    let marker = if selected {
        g.selector
    } else {
        g.selector_blank
    };
    let base = if selected {
        ctx.highlight_style()
    } else {
        Style::default()
    };
    let source = source.unwrap_or("").to_string();
    // Unknown or local: nothing to say. Only a place that could be slow or cost money
    // names what it is on, which is the rule the rows' own glyph follows.
    let locality = crate::locality::Locality::of_fstype(&source);
    let source = match locality {
        crate::locality::Locality::Object
        | crate::locality::Locality::Network
        | crate::locality::Locality::Memory => source,
        _ => String::new(),
    };
    let source_style = base.fg(match locality {
        crate::locality::Locality::Object => ctx.keybind_hints,
        crate::locality::Locality::Network => ctx.warning,
        crate::locality::Locality::Memory => ctx.temporal_col,
        _ => ctx.dimmed,
    });
    let mut name = crate::home::display_path(path);
    // A file of tables (a SQLite database, a NumPy archive) is a place, and a file.
    if !name.ends_with('/')
        && !crate::discover::data_format(path).is_some_and(crate::FileFormat::holds_tables)
    {
        name.push('/');
    }
    // What the place itself is, when the dataset index remembers it: `hive`, `12
    // parquet`. From the cache only; a place row never causes a directory read.
    let label = label.map(|l| format!("  {l}")).unwrap_or_default();
    // marker, name, [label,] at least one space, source, space. The padding is what
    // puts the source on the right edge, and a name cut to fit still leaves it a cell
    // of air. The label goes before the name is cut, since the name is the place.
    let fixed = marker.chars().count() + source.chars().count() + 1;
    let room = width.saturating_sub(fixed + 1).max(1);
    let label = if name.chars().count() + label.chars().count() <= room {
        label
    } else {
        String::new()
    };
    let name = truncate_start(&name, room.saturating_sub(label.chars().count()).max(1));
    let pad = width.saturating_sub(fixed + name.chars().count() + label.chars().count());
    let name_style = if selected {
        base.fg(ctx.text_secondary).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(ctx.text_secondary)
    };
    Line::from(vec![
        Span::styled(
            marker,
            base.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
        ),
        Span::styled(name, name_style),
        Span::styled(label, base.fg(ctx.dimmed)),
        Span::styled(" ".repeat(pad), base),
        Span::styled(source, source_style),
        Span::styled(" ", base),
    ])
}

/// What the cap on `RECENT` is hiding, as one row: `… 13 more in 5 places`.
fn more_line(
    hidden: usize,
    places: usize,
    selected: bool,
    name_width: usize,
    show_meta: bool,
    ctx: &RenderContext,
) -> Line<'static> {
    let text = format!(
        "{} {hidden} more in {places} {}",
        glyphs::get().ellipsis,
        if places == 1 { "place" } else { "places" }
    );
    note_row(text, selected, name_width, show_meta, ctx)
}

/// The row that stands for files datui cannot open, hidden inside a browsed directory.
fn hidden_line(
    count: usize,
    tables: bool,
    selected: bool,
    name_width: usize,
    show_meta: bool,
    ctx: &RenderContext,
) -> Line<'static> {
    let ellipsis = glyphs::get().ellipsis;
    let text = match (tables, count) {
        (true, 1) => format!("{ellipsis} 1 internal table"),
        (true, _) => format!("{ellipsis} {count} internal tables"),
        (false, 1) => format!("{ellipsis} 1 file with no reader"),
        (false, _) => format!("{ellipsis} {count} files with no reader"),
    };
    note_row(text, selected, name_width, show_meta, ctx)
}

/// Whether a section lists a database's tables rather than files.
fn holds_tables(section: &crate::home::Section) -> bool {
    section.rows.iter().any(|row| row.table.is_some())
}

/// A dimmed row that stands for rows not drawn, to the same edge as the entries.
fn note_row(
    text: String,
    selected: bool,
    name_width: usize,
    show_meta: bool,
    ctx: &RenderContext,
) -> Line<'static> {
    let g = glyphs::get();
    let width = row_width(name_width, show_meta);
    let marker = if selected {
        g.selector
    } else {
        g.selector_blank
    };
    let base = if selected {
        ctx.highlight_style()
    } else {
        Style::default()
    };
    let pad = width.saturating_sub(marker.chars().count() + text.chars().count() + 1);
    Line::from(vec![
        Span::styled(
            marker,
            base.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
        ),
        Span::styled(text, base.fg(ctx.dimmed)),
        Span::styled(" ".repeat(pad), base),
        Span::styled(" ", base),
    ])
}

/// What every row of the home list is drawn with in one frame, as opposed to what
/// each row says.
#[derive(Clone, Copy)]
struct ListDraw<'f> {
    ctx: &'f RenderContext,
    /// The list's whole width; a section header spans it.
    width: usize,
    /// What an entry's name may take beside the meta columns.
    name_width: usize,
    show_meta: bool,
    filter: &'f str,
    /// The throbber's frame, for a section still listing.
    frame: usize,
}

/// What one entry's row says beside its name, worked out by the caller.
#[derive(Default)]
struct EntryNotes<'a> {
    /// The column the filter matched, when the name did not.
    matched_column: Option<&'a str>,
    /// Sources a URL may name; `None` where the trail already names it.
    known_sources: Option<&'a [String]>,
    place_kind: Option<&'static str>,
    looking: Option<&'static str>,
    indent: usize,
    /// What a catalog says the row's file weighs, until it is measured.
    size_hint: Option<u64>,
    /// Why a web file cannot be had, in place of its size.
    gone: Option<&'a str>,
}

/// Section headers carry the collapse marker and the provenance note, so the list
/// explains itself without a legend.
fn section_header<'a>(
    section: &'a crate::home::Section,
    matches: usize,
    collapsed: bool,
    selected: bool,
    list: &ListDraw,
) -> Line<'a> {
    let ListDraw {
        ctx, width, frame, ..
    } = *list;
    let g = glyphs::get();
    let note = if section.unavailable {
        // The reason when there is one. A refused bucket listing says what to fix; a
        // share that has gone away has nothing to add beyond the word itself.
        section
            .unavailable_note
            .clone()
            .unwrap_or_else(|| "unavailable".to_string())
    } else if section.waiting {
        match &section.subtitle {
            Some(subtitle) => format!("listing {} {subtitle}", g.middot),
            None => "listing".to_string(),
        }
    } else if matches == 0
        && section.door.is_none()
        && section.origin == Some(crate::home::RootOrigin::Cwd.note())
    {
        // Launched somewhere with nothing to open, the heading says so and where to go:
        // the public rows below would otherwise read as this directory's (#547 D9).
        format!("nothing to open here {} ~ types a path", g.middot)
    } else {
        section.subtitle.clone().unwrap_or_default()
    };
    // The note is trimmed before the title is, and never takes more than half the
    // line. A note is context; the title is what the section *is*, and a search
    // heading carrying a long path would otherwise crowd the title out entirely.
    // `Found`'s title is one short word, and its note is the answer to the search.
    let note_room = if section.title == crate::home::HomeState::SEARCH_SECTION {
        width.saturating_sub(section.title.chars().count() + 16)
    } else {
        width / 2
    };
    // A callout reads from its mark and its file; the end of its message gives way.
    let note = if note.starts_with(g.warning) {
        glyphs::fit_cells(&note, note_room, g.ellipsis).into_owned()
    } else {
        truncate_start(&note, note_room)
    };
    // A title that names a place keeps its case; only the word-like headings —
    // "RECENT", "ELSEWHERE" — are shouted. A URL is a place, and uppercasing one turns
    // `s3://datui-sales` into `S3://DATUI-SALES`, which is not the bucket's name and in
    // a case-sensitive store is not even a valid one.
    let is_path = section.title.starts_with('/')
        || section.title.starts_with('~')
        || section.title.contains("://")
        // `C:\data` and `\\server\share`.
        || std::path::Path::new(&section.title).is_absolute();
    let mut title = if is_path {
        section.title.clone()
    } else {
        section.title.to_uppercase()
    };
    let marker = if collapsed { g.collapsed } else { g.expanded };
    // Shown whether folded or not: how much is in a place is worth knowing before
    // deciding to look in it, and a folded section would otherwise read as empty.
    // Until the listing is in, a count would be a guess, and a zero reads as empty.
    let chip = if section.waiting {
        let spinner = g.spinner;
        format!(" {} ", spinner[frame % spinner.len()])
    } else {
        format!(" {matches} ")
    };
    // Why the section is here, right after the count: `current directory`,
    // `configured`. A flat chip in the style of `hive`, since it is a word about the
    // section the way that is a word about a row.
    let origin = section
        .origin
        .map(|origin| format!(" {origin} "))
        .unwrap_or_default();
    let origin_cells = if origin.is_empty() {
        0
    } else {
        origin.chars().count() + 1
    };
    // marker, title, space, chip, space, [origin, space,] rule, space, note, space.
    // The title gives way to the note only down to three cells; below that the note
    // goes instead, since a heading that is all note and no title says nothing. The
    // origin chip goes before the note does: it is the shorter word and the one that
    // says what the section is. A cell of rule always stays: its weight is how
    // the cursor shows on a heading, and a long path would otherwise take it all.
    const MIN_RULE: usize = 1;
    let mut note = note;
    let mut origin = origin;
    let mut origin_cells = origin_cells;
    let mut fixed = marker.chars().count()
        + 1
        + chip.chars().count()
        + 1
        + origin_cells
        + note.chars().count()
        + 2
        + MIN_RULE;
    if width.saturating_sub(fixed) < 3 {
        note = String::new();
        fixed = marker.chars().count() + 1 + chip.chars().count() + 1 + origin_cells + 2 + MIN_RULE;
    }
    if width.saturating_sub(fixed) < 3 {
        origin = String::new();
        origin_cells = 0;
        fixed = marker.chars().count() + 1 + chip.chars().count() + 1 + 2 + MIN_RULE;
    }
    title = truncate_start(&title, width.saturating_sub(fixed));
    let rule_w = width.saturating_sub(fixed + title.chars().count()) + MIN_RULE;

    // A title on a rule, not a filled bar: the accent carries the title, the count
    // sits in a flat chip, and the rule runs out to the provenance note. The section
    // the cursor is in is brighter and its rule heavier, which is the whole of the
    // focus language — nothing moves, one thing lights up.
    let title_style = if selected {
        Style::default()
            .fg(ctx.accent_bright)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(ctx.accent).add_modifier(Modifier::BOLD)
    };
    let chip_style = Style::default().bg(ctx.controls_bg).fg(ctx.text_primary);
    let origin_style = Style::default()
        .bg(ctx.controls_bg)
        .fg(ctx.accent)
        .add_modifier(Modifier::BOLD);
    let rule_glyph = if selected { g.rule_h_focused } else { g.rule_h };
    let rule_style = Style::default().fg(if selected {
        ctx.accent
    } else {
        ctx.column_separator
    });
    let mut spans = vec![
        Span::styled(marker, Style::default().fg(ctx.accent)),
        Span::styled(title, title_style),
        Span::raw(" "),
        Span::styled(chip, chip_style),
        Span::raw(" "),
    ];
    if origin_cells > 0 {
        spans.push(Span::styled(origin, origin_style));
        spans.push(Span::raw(" "));
    }
    spans.extend([
        Span::styled(rule_glyph.repeat(rule_w), rule_style),
        Span::raw(" "),
        Span::styled(
            note,
            Style::default().fg(if section.unavailable {
                ctx.warning
            } else {
                ctx.text_secondary
            }),
        ),
        Span::raw(" "),
    ]);
    Line::from(spans)
}

/// Split `text` into spans, styling the characters at `positions` differently.
///
/// Consecutive positions are merged into one span, so a run of matched characters is
/// a single styled stretch rather than a stutter of one-character spans.
fn highlight_spans(
    text: &str,
    positions: &[usize],
    plain: Style,
    hit: Style,
) -> Vec<Span<'static>> {
    if positions.is_empty() {
        return vec![Span::styled(text.to_string(), plain)];
    }
    let marked: std::collections::HashSet<usize> = positions.iter().copied().collect();
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut run = String::new();
    let mut run_is_hit = false;

    for (i, ch) in text.chars().enumerate() {
        let is_hit = marked.contains(&i);
        if !run.is_empty() && is_hit != run_is_hit {
            spans.push(Span::styled(
                std::mem::take(&mut run),
                if run_is_hit { hit } else { plain },
            ));
        }
        run_is_hit = is_hit;
        run.push(ch);
    }
    if !run.is_empty() {
        spans.push(Span::styled(run, if run_is_hit { hit } else { plain }));
    }
    spans
}

/// A cloud source under `CLOUD`: its name, the API it speaks, how many buckets it
/// has (or why it has none) and where its login came from.
///
/// A column layout of its own rather than a dataset's. A source has no rows, columns,
/// size or age, and three blank metadata columns beside every source would say so on
/// every line.
fn source_line<'a>(
    entry: &'a Entry,
    source: Option<&crate::home::CloudSource>,
    selected: bool,
    width: usize,
    frame: usize,
    filter: &str,
    ctx: &RenderContext,
) -> Line<'a> {
    let g = glyphs::get();
    let base = if selected {
        ctx.highlight_style()
    } else {
        Style::default()
    };
    let marker = if selected {
        g.selector
    } else {
        g.selector_blank
    };
    let name_style = if selected {
        base.fg(ctx.text_primary).add_modifier(Modifier::BOLD)
    } else {
        base.fg(ctx.text_primary)
    };
    let hit_style = base
        .fg(ctx.keybind_hints)
        .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);

    let api = source.map(|s| s.api.as_str()).unwrap_or("");
    let count = match source {
        Some(s) if s.busy() => {
            let spinner = g.spinner[frame % g.spinner.len()];
            match s.count_text() {
                text if text.is_empty() => spinner.to_string(),
                text => format!("{text} {spinner}"),
            }
        }
        Some(s) => s.count_text(),
        None => String::new(),
    };
    let failed = source.is_some_and(|s| s.failed());
    let note = source.map(|s| s.note.clone()).unwrap_or_default();

    // marker, place, name, api, count, note. The name takes what it needs up to a
    // third of the line, the count a fixed column, and the note whatever is left.
    const API_W: usize = 7;
    const COUNT_W: usize = 14;
    let place = format!("{} ", g.in_object_store);
    let fixed = marker.chars().count() + place.chars().count() + API_W + COUNT_W + 3;
    let name_w = entry
        .name
        .chars()
        .count()
        .min((width / 3).max(12))
        .max(16)
        .min(width.saturating_sub(fixed));
    let mut name = entry.name.clone();
    let mut positions = crate::home::fuzzy_positions(filter, &name);
    if name.chars().count() > name_w && name_w > 1 {
        let kept = name_w - 1;
        name = name.chars().take(kept).collect::<String>() + g.ellipsis;
        positions.retain(|p| *p < kept);
    }
    let name_pad = name_w.saturating_sub(name.chars().count());
    let note_w = width.saturating_sub(fixed + name_w);
    // Cut from the end: the account or endpoint leads, and it is the part that tells
    // two sources apart.
    let note = if note.chars().count() > note_w && note_w > 1 {
        note.chars().take(note_w - 1).collect::<String>() + g.ellipsis
    } else {
        note
    };

    let mut spans = vec![
        Span::styled(
            marker,
            base.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
        ),
        Span::styled(place, base.fg(ctx.keybind_hints)),
    ];
    spans.extend(highlight_spans(&name, &positions, name_style, hit_style));
    spans.push(Span::styled(" ".repeat(name_pad + 1), base));
    spans.push(Span::styled(format!("{api:<API_W$}"), base.fg(ctx.dimmed)));
    let count_style = if failed {
        base.fg(ctx.warning)
    } else {
        base.fg(ctx.text_secondary)
    };
    let count = truncate_start(&count, COUNT_W - 1);
    spans.push(Span::styled(format!("{count:<COUNT_W$}"), count_style));
    spans.push(Span::styled(" ".to_string(), base));
    let note_pad = note_w.saturating_sub(note.chars().count());
    spans.push(Span::styled(note, base.fg(ctx.dimmed)));
    spans.push(Span::styled(" ".repeat(note_pad + 1), base));
    Line::from(spans)
}

fn entry_line<'a>(
    entry: &'a Entry,
    selected: bool,
    notes: EntryNotes<'a>,
    list: &ListDraw,
) -> Line<'a> {
    let EntryNotes {
        matched_column,
        known_sources,
        place_kind,
        looking,
        indent,
        size_hint,
        gone,
    } = notes;
    let ListDraw {
        ctx,
        name_width,
        show_meta,
        filter,
        ..
    } = *list;
    // The selection marker is the loudest thing on screen, and the only thing that
    // needs to be found instantly.
    let g = glyphs::get();
    let marker = if selected {
        g.selector
    } else {
        g.selector_blank
    };
    // A row under a place is drawn in, and the cells it is drawn in by come off the
    // name's side: the meta columns stay where every other row puts them, so the rule
    // below that gives a label up for the name fires that much sooner.
    let name_width = name_width.saturating_sub(indent);

    let mut name = entry.name.clone();
    // Nothing is there to go inside of, whatever the path looks like.
    if shows_as_a_place(entry) && place_kind != Some("missing") {
        name.push('/');
    }
    // A column hit takes the place of the kind label: both are a short note about
    // what this row is, and two of them would crowd the name.
    //
    // Inside an object store the service's own word is used, so a bucket reads as a
    // bucket rather than as a directory.
    let path_text = entry.path.to_string_lossy();
    let named_source = crate::source::split_source_id(&path_text).0;
    let described = entry.label();
    // Whether the cell ends up holding the curated word rather than a label. Only one
    // arm below reaches for it, and a row whose *path* is curated but whose kind sends
    // it elsewhere — a `multi` prefix in a catalog — is carrying a label.
    let mut shows_curated = false;
    let kind = match entry.kind {
        // A count beats the word for a bucket or container. Not the *curated* word,
        // though — `dataset` and `project` are what a source calls a place it names,
        // and that is the only thing marking it as one.
        //
        // The same order the details pane takes, or the row and the pane beside it
        // disagree about one directory.
        EntryKind::Directory => match (place_kind, entry.holds.formats.is_empty()) {
            (Some(curated), _) => {
                shows_curated = true;
                curated
            }
            (None, false) => described.as_ref(),
            // A directory in a bucket not yet looked into shows that it is being looked
            // into, rather than a word for the kind of place it is.
            (None, true) => crate::home::object_place_label(&entry.path)
                .or(looking)
                .unwrap_or(described.as_ref()),
        },
        // A catalog's local dataset that is not there says so, rather than the
        // ellipsis of a row nothing has looked at yet.
        EntryKind::Unknown if place_kind.is_some() => {
            shows_curated = true;
            place_kind.unwrap_or_default()
        }
        _ => described.as_ref(),
    };
    // Two stores can hold the same bucket and key, so a row from one that is named in
    // its URL says which, where a kind would otherwise go. A recent whose source has
    // since left the config says that instead of failing only when it is opened.
    let missing_source = named_source
        .is_some_and(|id| known_sources.is_some_and(|known| !known.iter().any(|k| k == id)));
    let missing_note = named_source.map(|id| format!("source not found: {id}"));
    // Whether the cell ends up holding the source id or the warning rather than a
    // label. The path having an id is not the same question: a peeked prefix under a
    // named source has both, and its label is a label.
    let mut shows_source = true;
    let kind: &str = match (named_source, kind, known_sources) {
        (Some(_), "", Some(_)) if missing_source => missing_note.as_deref().unwrap_or(""),
        (Some(id), "", Some(_)) => id,
        _ => {
            shows_source = false;
            kind
        }
    };
    // The row that opens the directory being browsed carries none of this: not a label,
    // not the curated word a source gives the place, not the source id that stands in
    // where a label would be. Every one of them is about the directory, and this row is
    // the door — `bigquery (all files)  dataset` says the door is the dataset, and
    // under a named source the cell filled with the id instead.
    let (kind, shows_curated, shows_source) = if entry.opens_whole_directory {
        ("", false, false)
    } else {
        (kind, shows_curated, shows_source)
    };
    // Nothing has looked into this row yet, and it has nothing else to say for itself.
    // An ellipsis says so and claims nothing: the word `dir` was a claim, and a blank
    // is what a file's empty label looks like.
    let kind = if kind.is_empty() && entry.kind == EntryKind::Unknown {
        g.ellipsis
    } else {
        kind
    };
    // Hive and multi-file datasets wear a flat chip; the rest stay as a word. Never on
    // an empty label: the chip is drawn by taking the cell apart again below, and a
    // dataset row can now have no label at all — the row that opens the directory being
    // browsed. A chip made of nothing was a panic in the renderer.
    let kind_is_chip = matched_column.is_none()
        && !kind.is_empty()
        && matches!(entry.kind, EntryKind::Hive | EntryKind::MultiFile);
    let kind_cell = match matched_column {
        Some(column) => format!(" {}{column}", g.middot),
        // `shown_column` below may cut this; both are written from the same string.
        None if kind.is_empty() => String::new(),
        None if kind_is_chip => format!("  {kind} "),
        // Two cells between a name and what it is, on every row: a place row's
        // label, a bucket's, a catalog's and a file's read the same (#547 M7).
        None => format!("  {kind}"),
    };

    // Where this row's data lives, immediately before its name. The detail pane has
    // carried this for a long time, and on a full-screen ultrawide the pane is far
    // enough from the cursor that a cloud path reads as a local one at a glance.
    let locality = entry
        .cost
        .source
        .as_deref()
        .map(crate::locality::Locality::of_fstype);
    let place = match locality {
        Some(crate::locality::Locality::Object) => g.in_object_store,
        Some(crate::locality::Locality::Network) => g.over_network,
        Some(crate::locality::Locality::Memory) => g.in_memory,
        Some(crate::locality::Locality::Local) => g.here,
        Some(crate::locality::Locality::Unknown) | None => g.place_unknown,
    };
    let place_cell = format!("{place} ");

    // A recent from a store or a share that nothing has measured: the probe that
    // measures remote rows runs over roots, and a recent's place is not one, so what it
    // shows is what an open or a listing remembered — or, until then, that nothing is
    // known.
    let unmeasured = indent > 0
        && place_kind.is_none()
        && entry.rows.is_none()
        && entry.cols.is_none()
        && entry.kind != EntryKind::Unknown
        && matches!(
            locality,
            Some(crate::locality::Locality::Object | crate::locality::Locality::Network)
        );
    let meta = show_meta.then(|| meta_columns(entry, unmeasured, size_hint, gone));
    // A row with nothing to say in the meta columns (a public dataset, a directory not
    // looked into) gives them to its name rather than cutting it beside blank cells
    // (#648).
    // An empty shape cell goes to the name the same way; size and age keep their
    // columns.
    let (name_width, meta) = match meta {
        Some(meta) if meta.trim().is_empty() => (name_width + META_COLUMNS_WIDTH, None),
        Some(meta) if meta.chars().take(SHAPE_COLUMNS_WIDTH).all(|c| c == ' ') => (
            name_width + SHAPE_COLUMNS_WIDTH,
            Some(meta.chars().skip(SHAPE_COLUMNS_WIDTH).collect()),
        ),
        meta => (name_width, meta),
    };

    // A label counts now — `5000+ parquet` is thirteen characters where `iceberg` was
    // seven — and on a narrow screen it can leave the name nothing to be truncated
    // into, which puts the meta columns out of their alignment and clips them. The name
    // is what identifies a row and the label only describes it, so the label goes. It
    // goes for good at these widths — the details pane is not drawn below a hundred and
    // two columns, and this fires far below that — which is the trade a screen with
    // room for one of the two forces. The test is the one truncation already makes, so
    // there is no width here to pick.
    //
    // Only a label. A column note says *why this row is in the list*, and the draw site
    // writes it from `matched_column` rather than from this cell, so blanking the cell
    // would hand the name a budget the note then overruns — the misalignment this
    // exists to stop, one column wider. And `source not found:` is a warning the pane
    // does not carry, so dropping it leaves a broken recent looking like a working one.
    // Not a source id or a `source not found:` either: two stores can hold the same
    // bucket and key, and that chip is the only thing that says which this row came
    // from. Asked of what the cell holds, not of what the path carries.
    //
    // Nor the curated word. `dataset` and `project` are what a source calls a place it
    // names, and the match above prefers them to the count for that reason; dropping
    // them here would take away the one thing marking a curated row. Asked of the cell
    // and not of the path, the same as the source id: a `multi` row under a public
    // source has a curated path and a count in its cell, and a count gives way.
    let is_label = matched_column.is_none() && !shows_source && !shows_curated;
    let fits = |cell: &str| {
        name_width.saturating_sub(2 + place_cell.chars().count() + cell.chars().count() + 1) > 1
    };
    // A column note says why the row is in the list and may not go, but it is as long
    // as somebody's column name: `transaction_amount` is twenty cells, which at the
    // narrowest width that draws meta leaves the name nothing to be cut into. Its head
    // is the identifying part, so the tail goes and the marks that fell in it go with
    // it — the same shape the name's own truncation takes.
    // The ellipsis is one character in the Unicode set and three in the ASCII one, so
    // the room it takes is asked for rather than assumed. Assuming one made the cut
    // note two characters longer than it was allowed under `unicode = never`, which
    // collapsed the name's budget — the misalignment this is all for, reached through
    // the fix for it.
    let ellipsis = glyphs::get().ellipsis;
    let ellipsis_len = ellipsis.chars().count();
    // The note as it will be drawn, and with it how many of those characters are the
    // note rather than the ellipsis standing for the rest. The draw site needs that
    // number to drop the marks the cut left behind, and carrying it from here is the
    // point: subtracting an ellipsis there means knowing its length in two places, and
    // the two only agree in one of the glyph sets.
    let shown_column: Option<(String, usize)> = matched_column.map(|column| {
        let room = name_width.saturating_sub(2 + place_cell.chars().count() + 1 + 2 + 2);
        let whole = column.chars().count();
        // Cut only where a letter survives the ellipsis: `checked_sub` rather than a
        // test of `room` against the ellipsis, so the subtraction cannot be reached
        // without room for it. `…` is one character and `...` is three, which made the
        // difference between a guard and a panic under `unicode = never`.
        match room.checked_sub(ellipsis_len) {
            Some(kept) if kept > 0 && whole > room => (
                column.chars().take(kept).collect::<String>() + ellipsis,
                kept,
            ),
            _ => (column.to_string(), whole),
        }
    });
    let kind_cell = match &shown_column {
        Some((column, _)) => format!(" {}{column}", g.middot),
        None => kind_cell,
    };
    let (kind_cell, kind_is_chip) = if fits(&kind_cell) {
        (kind_cell, kind_is_chip)
    } else if is_label {
        (String::new(), false)
    } else if shows_source && matched_column.is_none() {
        // A source id and a `source not found:` are as long as somebody's
        // configuration, and this cell may not go — so it is cut to the longest that
        // leaves the name room, which is the same test read backwards. The curated
        // word is not cut: it is one of two words, `dataset` or `project`, and `d…t`
        // says nothing at all where the whole of it still fits in eight cells.
        //
        // And not when a column matched, because then the cell is the note and the
        // draw site writes that from `shown_column`: cutting the cell here would leave
        // the two disagreeing about the width, which is how the columns come unstuck.
        let room = name_width.saturating_sub(2 + place_cell.chars().count() + 1 + 2);
        (crate::discover::shorten(&kind_cell, room), false)
    } else {
        (kind_cell, kind_is_chip)
    };

    // How Enter will read a file that is not scanned where it is, in the cell a file's
    // empty label leaves. Lazy rows, most of them, stay quiet. It gives way before the
    // name is cut at all: the pane beside it says the same.
    let kind_cell = match discover::how_read(entry).and_then(read_marker) {
        Some(marker) if matched_column.is_none() && kind_cell.is_empty() => {
            let cell = format!("  {marker}");
            let room = name_width.saturating_sub(2 + place_cell.chars().count() + 1);
            if name.chars().count() + cell.chars().count() <= room {
                cell
            } else {
                kind_cell
            }
        }
        _ => kind_cell,
    };

    // Positions are taken from the untruncated name, because that is what matched.
    // Truncation then shifts them, and dropping the ones that fall outside is exactly
    // right: a character no longer on screen cannot be highlighted.
    //
    // Only when the name is *why* this row is here — a row matched by one of its
    // columns would otherwise get marks scattered over letters that had nothing to do
    // with it.
    let mut name_positions = if matched_column.is_none() {
        crate::home::fuzzy_positions(filter, &name)
    } else {
        Vec::new()
    };

    // Truncate the name, never the metadata: the columns must stay aligned. A row
    // whose name is a path keeps its tail, since the leaf is what identifies it;
    // an ordinary filename keeps its head, where the distinguishing part usually is.
    let budget =
        name_width.saturating_sub(2 + place_cell.chars().count() + kind_cell.chars().count() + 1);
    // The door's name is the directory, which the section title already says, and what
    // Enter opens, which nothing else does: the directory gives way first.
    let door_cut = name
        .rfind(" (")
        .filter(|_| entry.opens_whole_directory)
        .map(|at| name.split_at(at))
        .map(|(base, what)| (base.to_string(), what.to_string()));
    if name.chars().count() > budget
        && budget > ellipsis_len
        && let Some((base, what)) = door_cut
    {
        name = if budget > what.chars().count() + ellipsis_len {
            let room = budget - what.chars().count() - ellipsis_len;
            let kept: String = base.chars().take(room).collect();
            format!("{kept}{}{what}", g.ellipsis)
        } else {
            // Narrower still: the directory goes entirely, and what Enter opens keeps
            // its head.
            let what = what.trim_start();
            if what.chars().count() <= budget {
                what.to_string()
            } else {
                let kept: String = what.chars().take(budget - ellipsis_len).collect();
                format!("{kept}{}", g.ellipsis)
            }
        };
        name_positions.clear();
    } else if name.chars().count() > budget && budget > 1 {
        let original_len = name.chars().count();
        // A relative path too (a search hit under a directory): its leaf is the file.
        if name.starts_with('/')
            || name.starts_with('~')
            || name.trim_end_matches('/').contains('/')
        {
            name = truncate_start(&name, budget);
            // The tail survived: shift every position left by what was dropped, and
            // right by the ellipsis now standing in for it.
            let kept = name.chars().count();
            let ellipsis = g.ellipsis.chars().count();
            let dropped = original_len + ellipsis - kept;
            name_positions.retain(|p| *p >= dropped);
            for p in &mut name_positions {
                *p = *p - dropped + ellipsis;
            }
        } else {
            let kept = budget - 1;
            name = name.chars().take(kept).collect::<String>() + g.ellipsis;
            // The head survived, so surviving positions keep their index.
            name_positions.retain(|p| *p < kept);
        }
    }
    let pad = name_width.saturating_sub(2 + name.chars().count() + kind_cell.chars().count());

    // The selected row is tinted across its full width and carries the rail, the way
    // the table marks its current row. Tinted rather than reversed so the colours
    // that say what a row is survive on the row you are looking at. A theme that
    // asks for "reversed" gets the old look.
    let base = if selected {
        ctx.highlight_style()
    } else {
        Style::default()
    };
    // A file datui cannot read is listed so the directory reads as it is, and dimmed
    // so the eye passes over it to the data.
    let name_fg = if entry.kind == EntryKind::Other {
        ctx.dimmed
    } else {
        ctx.text_primary
    };
    let name_style = if selected {
        base.fg(name_fg).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(name_fg)
    };
    let kind_style = if matched_column.is_some() {
        base.fg(ctx.keybind_hints)
    } else if missing_source {
        base.fg(ctx.warning)
    } else {
        match entry.kind {
            EntryKind::Hive | EntryKind::MultiFile => Style::default()
                .bg(ctx.controls_bg)
                .fg(ctx.accent)
                .add_modifier(Modifier::BOLD),
            _ => base.fg(ctx.dimmed),
        }
    };

    let hit_style = base
        .fg(ctx.keybind_hints)
        .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);

    // Loud enough to find, quiet enough to ignore. Somewhere that can stall or cost
    // money is coloured; a local disk, which is the overwhelming majority of rows, is
    // dimmed so the column reads as texture rather than as a warning repeated on every
    // line.
    let place_style = base.fg(match locality {
        Some(crate::locality::Locality::Object) => ctx.keybind_hints,
        Some(crate::locality::Locality::Network) => ctx.warning,
        Some(crate::locality::Locality::Memory) => ctx.temporal_col,
        _ => ctx.dimmed,
    });

    let mut spans = vec![
        Span::styled(
            marker,
            base.fg(ctx.keybind_hints).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ".repeat(indent), base),
        Span::styled(place_cell, place_style),
    ];
    spans.extend(highlight_spans(
        &name,
        &name_positions,
        name_style,
        hit_style,
    ));
    // The column note is a substring match, so its highlight has to be one too.
    match matched_column {
        Some(column) => {
            spans.push(Span::styled(format!(" {}", g.middot), kind_style));
            // The note as it was cut to fit, and the marks the cut left standing: a
            // character no longer on screen cannot be highlighted. `kept` counts the
            // note's own characters, so an uncut note keeps the mark on its final
            // letter and a cut one puts none on the ellipsis.
            let (shown, kept) = match &shown_column {
                Some((shown, kept)) => (shown.as_str(), *kept),
                None => (column, column.chars().count()),
            };
            let mut positions = crate::home::substring_positions(filter, column);
            positions.retain(|p| *p < kept);
            spans.extend(highlight_spans(shown, &positions, kind_style, hit_style));
        }
        None if kind_is_chip => {
            // One cell of the row's own background, then the chip.
            spans.push(Span::styled(" ".to_string(), base));
            // The cell's own leading space, given the row's background instead of the
            // chip's. Stripped rather than sliced: a cell with nothing in it is a
            // panic, and whether one can reach here is a question the next change to
            // `kind_is_chip` gets to answer wrongly.
            let chip = kind_cell.strip_prefix(' ').unwrap_or(&kind_cell);
            spans.push(Span::styled(chip.to_string(), kind_style));
        }
        None => spans.push(Span::styled(kind_cell.clone(), kind_style)),
    }
    match meta {
        Some(meta) => {
            spans.push(Span::styled(" ".repeat(pad), base));
            spans.push(Span::styled(meta, base.fg(ctx.dimmed)));
        }
        // The meta columns went to the name: padded across them, so the selection bar
        // still runs to the edge.
        None if show_meta => spans.push(Span::styled(" ".repeat(pad), base)),
        None => {}
    }
    // Carry the reverse to the edge, so the bar is a bar and not a ragged highlight.
    spans.push(Span::styled(" ", base));
    Line::from(spans)
}

/// The word a file row carries for how opening it reads it: `converts` or `in memory`,
/// or `downloads` for a remote file copied whole first. `None` for a file scanned where
/// it is, which is most of them.
fn read_marker(how: discover::HowRead) -> Option<&'static str> {
    if how.download {
        return Some("downloads");
    }
    how.mode.marker()
}

/// The pane's `read` line: [`crate::ReadMode::label`], after the download when there
/// is one.
fn read_words(how: discover::HowRead) -> String {
    let mode = how.mode.label();
    if how.download {
        format!("download {} {mode}", glyphs::get().arrow_right)
    } else {
        mode.to_string()
    }
}

/// A filled heading inside the preview pane.
///
/// The same grammar as the list's section headers — a filled bar, not a box — so the
/// two halves of the screen read as one program.
fn pane_heading(text: &str, width: usize, ctx: &RenderContext) -> Line<'static> {
    pane_heading_counted(text, None, width, ctx)
}

/// A pane heading with a flat chip after its title, as the list's sections carry
/// their counts: `COLUMNS [20]`, `ROWS [5 of 20 columns]`. The title is always a
/// noun, the count always in the chip.
fn pane_heading_counted(
    text: &str,
    chip: Option<&str>,
    width: usize,
    ctx: &RenderContext,
) -> Line<'static> {
    let g = glyphs::get();
    let label = text.to_string();
    let mut used = label.chars().count() + 2;
    let mut spans = vec![
        Span::styled(
            label,
            Style::default().fg(ctx.accent).add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
    ];
    if let Some(chip) = chip {
        let chip = format!(" {chip} ");
        used += chip.chars().count() + 1;
        spans.push(Span::styled(
            chip,
            Style::default().bg(ctx.controls_bg).fg(ctx.text_primary),
        ));
        spans.push(Span::raw(" "));
    }
    spans.push(Span::styled(
        g.rule_h.repeat(width.saturating_sub(used)),
        Style::default().fg(ctx.column_separator),
    ));
    Line::from(spans)
}

/// The most column notes the details pane lists a line each.
const CODEBOOK_ROWS: usize = 12;

/// What a documented file's columns mean, in the details pane: each column and its
/// note, wrapped when the pane has `room` rows for all of it, else a line a column cut
/// to the pane. Ctrl+E shows the whole page.
fn column_notes_block(
    columns: &[(String, crate::catalog::ColumnNote)],
    width: usize,
    room: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let mut lines = vec![Line::from(""), pane_heading("COLUMNS", width, ctx)];
    let key_w = key_column(columns.iter().map(|(name, _)| name.as_str())).min(22);
    let style = Style::default().fg(ctx.text_secondary);
    // A column with only a legend (a spec's enum) says how long it is, as the page does.
    let about = |note: &crate::catalog::ColumnNote| match note.about() {
        about if about.is_empty() && !note.values.is_empty() => {
            format!("{} values", note.values.len())
        }
        about => about,
    };
    let wrapped: Vec<Line<'static>> = columns
        .iter()
        .flat_map(|(name, note)| fact_lines(name, about(note), key_w, width, style, ctx))
        .collect();
    if lines.len() + wrapped.len() <= room {
        lines.extend(wrapped);
        return lines;
    }
    let value_w = width.saturating_sub(key_w + 2);
    // A row kept for the count of the rest.
    let fits = room.saturating_sub(lines.len() + 1).clamp(1, CODEBOOK_ROWS);
    for (name, note) in columns.iter().take(fits) {
        let name = glyphs::fit_cells(name, key_w, glyphs::get().ellipsis);
        lines.push(Line::from(vec![
            Span::styled(format!("{name:<key_w$}  "), Style::default().fg(ctx.dimmed)),
            Span::styled(
                glyphs::fit_cells(&about(note), value_w, glyphs::get().ellipsis).into_owned(),
                style,
            ),
        ]));
    }
    if columns.len() > fits {
        lines.push(Line::from(Span::styled(
            format!("{} {} more", glyphs::get().ellipsis, columns.len() - fits),
            Style::default().fg(ctx.dimmed),
        )));
    }
    lines
}

/// How many rows a line takes once the pane has wrapped it.
///
/// Word-wrapped, the way `Wrap { trim: false }` does it: a word that will not fit goes
/// whole to the next row, so dividing the width into the length is a floor and not an
/// answer — and the one line this is asked about, `holds`, is a list of words.
///
/// A space at the end of a row is counted, where the renderer drops it, so this errs
/// one high on a line that happens to break there. Which way it errs matters: what it
/// feeds is a budget, and a row too few leaves a blank line where a row too many draws
/// over the bottom of the pane.
pub(crate) fn wrapped_rows(line: &Line<'_>, width: usize) -> usize {
    use unicode_width::UnicodeWidthStr;
    let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
    if width == 0 {
        return 1;
    }
    let mut rows = 1;
    let mut used = 0;
    for word in text.split_inclusive(' ') {
        // Cells, not characters: the pane wraps by what a glyph occupies, and a
        // skipped file can be named in a script where one character is two cells.
        let len = UnicodeWidthStr::width(word);
        if used + len > width && used > 0 {
            rows += 1;
            used = 0;
        }
        used += len;
        // A single word longer than the pane wraps inside itself.
        while used > width {
            rows += 1;
            used -= width;
        }
    }
    rows
}

/// As many of a schema's columns as `room` rows will hold, and how many that was.
///
/// Counted as they are built, because a schema line wraps too — `created_at
/// datetime[μs, America/New_York]` is past the forty cells the pane has. Taking a
/// column per row draws the tail past the bottom and sends the `… N more` line over
/// the edge with it, which is the loss the count exists to report.
fn schema_lines(
    schema: &[(String, polars::prelude::DataType)],
    name_w: usize,
    width: usize,
    room: usize,
    ctx: &RenderContext,
) -> (usize, Vec<Line<'static>>) {
    let g = glyphs::get();
    let mut lines = Vec::new();
    let mut used = 0;
    for (name, dtype) in schema {
        let mut display = name.clone();
        if display.chars().count() > name_w {
            display = display.chars().take(name_w - 1).collect::<String>() + g.ellipsis;
        }
        let line = Line::from(vec![
            Span::styled(
                format!("{display:<name_w$}  "),
                Style::default().fg(ctx.text_secondary),
            ),
            Span::styled(
                format!("{dtype}"),
                Style::default().fg(ctx.type_color(dtype)),
            ),
        ]);
        let takes = wrapped_rows(&line, width);
        if used + takes > room {
            break;
        }
        used += takes;
        lines.push(line);
    }
    (lines.len(), lines)
}

/// One `key   value` fact, with the value carrying the emphasis. A value longer than the
/// pane wraps under itself, not under the key: a URL or a description that ran back to
/// column 0 read as a new fact (#547 D6).
fn fact_lines(
    key: &str,
    value: String,
    key_w: usize,
    width: usize,
    style: Style,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let indent = key_w + 2;
    let room = width.saturating_sub(indent);
    let key_span = Span::styled(format!("{key:<key_w$}  "), Style::default().fg(ctx.dimmed));
    // Too narrow to hang anything under: the pane's own wrap does what it can.
    if room < 12 || value.chars().count() <= room {
        return vec![Line::from(vec![key_span, Span::styled(value, style)])];
    }
    let pieces = crate::render::overlays::wrap_help_line(&value, room);
    pieces
        .into_iter()
        .enumerate()
        .map(|(i, piece)| {
            let lead = if i == 0 {
                key_span.clone()
            } else {
                Span::raw(" ".repeat(indent))
            };
            Line::from(vec![lead, Span::styled(piece, style)])
        })
        .collect()
}

/// The width of the key column for a pane's facts: one column for all of them, so the
/// values line up down the pane.
fn key_column<'a>(keys: impl IntoIterator<Item = &'a str>) -> usize {
    keys.into_iter()
        .map(|k| k.chars().count())
        .max()
        .unwrap_or(0)
}

/// A compression ratio, when it is worth stating.
///
/// Below about 1.2x the number is noise; above it, it is the difference between what
/// a file weighs and what it will weigh once open.
fn ratio_of(size: Option<u64>, uncompressed: Option<u64>) -> Option<f64> {
    let (on_disk, in_memory) = (size?, uncompressed?);
    if on_disk == 0 {
        return None;
    }
    let ratio = in_memory as f64 / on_disk as f64;
    (ratio >= 1.2).then_some(ratio)
}

/// What stands in for the label of a directory in a bucket that has not said what it
/// holds: `…` before it is asked about, a spinner while it is, `?` when asking failed.
fn looking_glyph(app: &crate::App, entry: &Entry) -> Option<&'static str> {
    let g = glyphs::get();
    Some(match app.home.cloud_look(entry)? {
        crate::home::CloudLook::Waiting => g.ellipsis,
        crate::home::CloudLook::Looking => g.spinner[app.throbber_frame as usize % g.spinner.len()],
        crate::home::CloudLook::Failed => "?",
    })
}

/// What a row is, in words, for the pane's `kind` line. The list's labels are terse
/// because they share a row with the name (`dir`, `mixed`, `12 parquet`); the pane has
/// the room to say it, and what is inside goes on the `contains` line.
fn kind_words(
    entry: &Entry,
    place_kind: Option<&'static str>,
    looking: Option<crate::home::CloudLook>,
) -> String {
    // The door into this directory is an action, not a thing: see
    // `Entry::opens_whole_directory`. Its name and the line under the facts say it.
    if entry.opens_whole_directory {
        return String::new();
    }
    if let Some(table) = &entry.table {
        let of = match (&entry.format_spec, table.format) {
            (Some(spec), _) => spec.clone(),
            (None, Some(format)) => format.name().to_string(),
            (None, None) => String::new(),
        };
        return format!("{of} {}", table.kind).trim_start().to_string();
    }
    match entry.kind {
        EntryKind::File => match crate::FileFormat::from_path(&entry.path) {
            _ if entry.format_spec.is_some() => {
                format!("{} file", entry.format_spec.as_deref().unwrap_or_default())
            }
            Some(format) => format!("{} file", format.name()),
            // Named nothing, and found by its bytes to be data.
            None => "data file".to_string(),
        },
        EntryKind::Other => String::new(),
        EntryKind::Hive => "hive table".to_string(),
        EntryKind::MultiFile => "multi-file table".to_string(),
        k if k.is_lake_table() => {
            format!("{} table", k.lake_name().unwrap_or_default().to_lowercase())
        }
        EntryKind::Directory => match place_kind {
            Some(curated) => curated.to_string(),
            None if looking == Some(crate::home::CloudLook::Failed) => {
                format!("? {} listing failed, Ctrl+R retries", glyphs::get().middot)
            }
            // Nothing to say yet; the row's spinner says it is being found out.
            None if looking.is_some() => String::new(),
            None => crate::home::object_place_label(&entry.path)
                .unwrap_or("directory")
                .to_string(),
        },
        // A local dataset of a catalog that is not there.
        EntryKind::Unknown if place_kind == Some("missing") => "missing".to_string(),
        _ => String::new(),
    }
}

/// [`preview_head_keyed`] with nothing below it to line up with, as the tests check it.
#[cfg(test)]
fn preview_head(
    entry: &Entry,
    place_kind: Option<&'static str>,
    looking: Option<crate::home::CloudLook>,
    width: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    preview_head_keyed(entry, place_kind, looking, None, width, 0, ctx).0
}

/// The name, the path, and everything known about the dataset, its key column at least
/// `key_w` wide so facts drawn below it line up with its own; and the key column used.
///
/// Split out from the pane so it can be checked without an application behind it.
fn preview_head_keyed(
    entry: &Entry,
    place_kind: Option<&'static str>,
    looking: Option<crate::home::CloudLook>,
    spec: Option<&crate::formats::Spec>,
    width: usize,
    key_w: usize,
    ctx: &RenderContext,
) -> (Vec<Line<'static>>, usize) {
    let g = glyphs::get();
    let mut lines: Vec<Line> = vec![
        Line::from(Span::styled(
            entry.name.clone(),
            Style::default()
                .fg(ctx.text_primary)
                .add_modifier(Modifier::BOLD),
        )),
        // One line, tail kept: a wrapped path costs three rows to say what the leaf
        // already said.
        Line::from(Span::styled(
            truncate_start(&crate::home::display_path(&entry.path), width),
            Style::default().fg(ctx.dimmed),
        )),
    ];

    // One list, in the order a sidebar reads: what it is, where it lives, what is in
    // it, what reading it will take, and when it last changed.
    let mut facts: Vec<(&str, String, Style)> = Vec::new();
    let plain = Style::default().fg(ctx.text_secondary);

    let kind = kind_words(entry, place_kind, looking);
    if !kind.is_empty() {
        facts.push(("kind", kind, plain));
    }
    // The spec that reads it, and what about the file says so: drawn after `kind`, a
    // path cut in its middle and the conditions as chips, neither wrapped mid-word.
    let spec_at = facts.len();
    let spec_path = spec
        .and_then(|s| s.path.as_deref())
        .map(crate::home::display_path);
    let chips = spec.map(|s| s.match_chips_for(&entry.path));
    if let Some(how) = discover::how_read(entry) {
        facts.push(("read", read_words(how), plain));
    }
    if let Some(source) = entry
        .cost
        .source
        .as_deref()
        .map(crate::locality::Source::from_fstype)
    {
        // The filesystem's own name and nothing else. Colour carries the warning:
        // a sentence explaining that a network is a network is a sentence the
        // reader has to skip on every row they look at.
        let style = match source.locality {
            crate::locality::Locality::Network | crate::locality::Locality::Object => {
                Style::default().fg(ctx.warning)
            }
            crate::locality::Locality::Memory => Style::default().fg(ctx.success),
            _ => plain,
        };
        facts.push(("storage", source.label().to_string(), style));
    }
    // What there is to open inside. Without the partition count when the `partitions`
    // fact below carries one: they count the same thing under different caps, and two
    // adjacent numbers that ought to agree and do not are worse than one.
    //
    // A directory that was looked into and holds nothing to open says so, rather than
    // leaving the reader to wonder whether anything was looked at.
    match entry.holds.line(entry.cost.partitions.is_none()) {
        // One part to a line, under the one label: joined, `1 parquet · 1 csv · 1
        // directory` broke in the middle of a count at the pane's width.
        Some(line) => {
            for (i, part) in line.split(" · ").enumerate() {
                let key = if i == 0 { "contains" } else { "" };
                facts.push((key, part.to_string(), plain));
            }
        }
        None if entry.kind == EntryKind::Directory
            && place_kind.is_none()
            && looking.is_none()
            && !entry.opens_whole_directory =>
        {
            facts.push(("contains", "no data files".to_string(), plain));
        }
        None => {}
    }
    // A spec's variants are record types, which its own `records` line counts.
    if let Some(n) = entry.cost.tables.filter(|_| entry.format_spec.is_none()) {
        let what = if n == 1 { "table" } else { "tables" };
        facts.push(("contains", format!("{n} {what}"), plain));
    }
    // A door that is not one table reads part of the directory: which part, and what it
    // leaves out, where the user decides whether to press Enter.
    if entry.opens_whole_directory
        && let Some((reads, skips)) = crate::home::door_reads(entry)
    {
        facts.push(("reads", reads, plain));
        if let Some(skips) = skips {
            facts.push(("skips", skips, plain));
        }
    }
    if let Some(rows) = entry.rows {
        facts.push(("rows", discover::format_rows(rows), plain));
    }
    if let Some(cols) = entry.cols {
        let more = if entry.cols_sampled { "+" } else { "" };
        facts.push(("columns", format!("{cols}{more}"), plain));
    }
    if let Some(size) = entry.size {
        facts.push(("on disk", discover::format_size(size), plain));
    }
    if let Some(uncompressed) = entry.cost.uncompressed {
        // The one number nothing else here implies: 200 MB of zstd Parquet is two
        // gigabytes once it is open.
        facts.push((
            "in memory",
            discover::format_size(uncompressed),
            Style::default().fg(ctx.float_col),
        ));
    }
    let ratio = ratio_of(entry.size, entry.cost.uncompressed).map(|r| format!("{r:.1}{}", g.times));
    match (&entry.cost.codec, ratio) {
        (Some(codec), Some(r)) => facts.push(("compression", format!("{codec}, {r}"), plain)),
        (Some(codec), None) => facts.push(("compression", codec.clone(), plain)),
        (None, Some(r)) => facts.push(("compression", r, plain)),
        (None, None) => {}
    }
    if let Some(groups) = entry.cost.row_groups {
        // One enormous row group cannot be read in parallel or skipped through; a
        // thousand tiny ones cost more in overhead than they save.
        facts.push(("row groups", groups.to_string(), plain));
    }
    if let Some(parts) = &entry.cost.partitions {
        let count = if parts.more {
            format!("{}+", parts.count)
        } else {
            parts.count.to_string()
        };
        facts.push((
            "partitions",
            format!("{count} by {}", parts.keys.join(", ")),
            Style::default().fg(ctx.temporal_col),
        ));
        if let (Some(first), Some(last)) = (
            parts.first_key_values.first(),
            parts.first_key_values.last(),
        ) {
            let key = parts.keys.first().map(String::as_str).unwrap_or("");
            // Spelled rather than drawn: an arrow glyph here would be the only one
            // on the screen, and "to" reads the same on every terminal.
            let range = if first == last {
                first.clone()
            } else {
                format!("{first} to {last}")
            };
            facts.push(("range", format!("{key} {range}"), plain));
        }
    }
    if let Some(modified) = entry.modified {
        // "now" already reads as a time; "now ago" does not.
        let age = discover::format_age(modified);
        if age == "now" {
            facts.push(("modified", age, plain));
        } else if !age.is_empty() {
            facts.push(("modified", format!("{age} ago"), plain));
        }
    }

    let spec_keys = spec_path
        .as_ref()
        .map(|_| "spec")
        .into_iter()
        .chain(chips.as_ref().map(|_| "match"));
    let key_w = key_column(facts.iter().map(|(k, _, _)| *k).chain(spec_keys)).max(key_w);
    if !facts.is_empty() || chips.is_some() {
        lines.push(Line::from(""));
        lines.push(pane_heading("DETAILS", width, ctx));
        let mut spec_lines = Vec::new();
        if let Some(path) = &spec_path {
            let room = width.saturating_sub(key_w + 2);
            spec_lines.extend(fact_lines(
                "spec",
                elide_path(path, room),
                key_w,
                width,
                plain,
                ctx,
            ));
        }
        if let Some(chips) = &chips {
            let filled = chips_filled(ctx);
            spec_lines.extend(chip_fact_lines("match", chips, key_w, width, filled, ctx));
        }
        let mut spec_lines = Some(spec_lines);
        for (i, (key, value, style)) in facts.into_iter().enumerate() {
            if i == spec_at {
                lines.extend(spec_lines.take().unwrap_or_default());
            }
            lines.extend(fact_lines(key, value, key_w, width, style, ctx));
        }
        lines.extend(spec_lines.take().unwrap_or_default());
    }

    (lines, key_w)
}

/// `path` in `width` columns, cut between its components so the file name stays:
/// `~/…/formats/demo-mktdata.toml`. The first component stays when there is room for it;
/// a name too long on its own keeps its end. Cut at the platform's separators (`\`
/// as well as `/` on Windows), each kept as the path spells it.
fn elide_path(path: &str, width: usize) -> String {
    if glyphs::display_width(path) <= width {
        return path.to_string();
    }
    let ellipsis = glyphs::get().ellipsis;
    // Each separator, and where the component after it starts.
    let seps: Vec<(char, usize)> = path
        .char_indices()
        .filter(|(_, c)| std::path::is_separator(*c))
        .map(|(i, c)| (c, i + c.len_utf8()))
        .collect();
    let Some(&(first_sep, after_first)) = seps.first() else {
        return truncate_start(path, width);
    };
    let first = &path[..after_first - first_sep.len_utf8()];
    // The most trailing components that fit after `first/…/`, then after `…/`.
    for with_first in [true, false] {
        for &(sep, start) in &seps[1..] {
            let tail = &path[start..];
            let cut = if with_first {
                format!("{first}{first_sep}{ellipsis}{sep}{tail}")
            } else {
                format!("{ellipsis}{sep}{tail}")
            };
            if glyphs::display_width(&cut) <= width {
                return cut;
            }
        }
    }
    let (_, last) = seps[seps.len() - 1];
    truncate_start(&path[last..], width)
}

/// Whether chips are drawn on the chrome tier: a UTF-8 terminal whose header tint
/// shows. Otherwise they are bracketed, and text values quoted.
fn chips_filled(ctx: &RenderContext) -> bool {
    glyphs::get().unicode && crate::config::tint_shows(Some(ctx.table_header_bg)).is_some()
}

/// One condition of a spec's match as spans, at most `room` columns: a flat chip on the
/// header tier, name dimmed and value in its type's color, or `[name value]` where no
/// tint shows. Too long for the line, the name is cut before the value, which keeps at
/// least its first character.
fn chip_spans(
    chip: &MatchChip,
    room: usize,
    filled: bool,
    ctx: &RenderContext,
) -> (Vec<Span<'static>>, usize) {
    use crate::formats::ChipKind;
    let value_color = match chip.kind {
        ChipKind::Int | ChipKind::Hex => ctx.int_col,
        ChipKind::Magic | ChipKind::Text | ChipKind::Glob => ctx.str_col,
    };
    let base = if filled {
        Style::default().bg(ctx.table_header_bg)
    } else {
        Style::default()
    };
    let dim = base.fg(ctx.dimmed);
    let (open, close) = if filled { (" ", " ") } else { ("[", "]") };
    let ellipsis = glyphs::get().ellipsis;
    let value = chip.value_text(!filled);
    let (name_w, value_w) = (
        glyphs::display_width(&chip.name),
        glyphs::display_width(&value),
    );
    let inner = room.saturating_sub(3);
    // A chip that says `exchange_feed_sequence_version` and not its number says
    // nothing: the value keeps up to half the chip, the name what is left (a letter
    // and the marker at least), and a long value takes what the name leaves.
    let name_floor = name_w.min(1 + glyphs::display_width(ellipsis));
    let name_room = name_w.min(inner.saturating_sub(value_w.min(inner / 2)).max(name_floor));
    let name = glyphs::fit_cells(&chip.name, name_room, ellipsis).into_owned();
    let name_w = glyphs::display_width(&name);
    let value = glyphs::fit_cells(&value, inner.saturating_sub(name_w), ellipsis).into_owned();
    let value_w = glyphs::display_width(&value);
    let width = 3 + name_w + value_w;
    let spans = vec![
        Span::styled(open, dim),
        Span::styled(name, dim),
        Span::styled(" ", base),
        Span::styled(value, base.fg(value_color)),
        Span::styled(close, dim),
    ];
    (spans, width)
}

/// The `match` fact: its chips laid out under the value column, wrapping between whole
/// chips and never inside one. `no match` when the spec has none.
fn chip_fact_lines(
    key: &str,
    chips: &[MatchChip],
    key_w: usize,
    width: usize,
    filled: bool,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    if chips.is_empty() {
        let said = crate::formats::FORMAT_ONLY.to_string();
        let style = Style::default().fg(ctx.text_secondary);
        return fact_lines(key, said, key_w, width, style, ctx);
    }
    let indent = key_w + 2;
    let room = width.saturating_sub(indent).max(1);
    let mut rows: Vec<(Vec<Span<'static>>, usize)> = vec![(Vec::new(), 0)];
    for chip in chips {
        let (spans, w) = chip_spans(chip, room, filled, ctx);
        let row = rows.last_mut().expect("one row at least");
        if row.1 > 0 && row.1 + 1 + w > room {
            rows.push((spans, w));
        } else {
            if row.1 > 0 {
                row.0.push(Span::raw(" "));
                row.1 += 1;
            }
            row.0.extend(spans);
            row.1 += w;
        }
    }
    rows.into_iter()
        .enumerate()
        .map(|(i, (spans, _))| {
            let lead = if i == 0 {
                Span::styled(format!("{key:<key_w$}  "), Style::default().fg(ctx.dimmed))
            } else {
                Span::raw(" ".repeat(indent))
            };
            Line::from(std::iter::once(lead).chain(spans).collect::<Vec<_>>())
        })
        .collect()
}

/// The details pane for a cloud source: what it points at, how it logs in, and when
/// its buckets were listed. When listing failed, the whole message, since the row only
/// had room for a word of it.
/// A catalog's heading: what the catalog is, where it comes from, and how to hide
/// it. Delete hides only the catalog that comes with datui; any catalog hides for
/// good by its id in `[home] hide`.
fn catalog_details(
    catalog: &crate::home::ShownCatalog,
    width: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let plain = Style::default().fg(ctx.text_secondary);
    let middot = glyphs::get().middot;
    let mut lines: Vec<Line> = vec![
        Line::from(Span::styled(
            catalog.label.clone(),
            Style::default()
                .fg(ctx.text_primary)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        pane_heading("DETAILS", width, ctx),
    ];
    let bundled = catalog.origin == crate::catalog::Origin::Bundled;
    let for_good = format!("[home] hide = [\"{}\"]", catalog.id);
    let mut facts: Vec<(&str, String)> = vec![("datasets", catalog.datasets.len().to_string())];
    match (&catalog.file, bundled) {
        (_, true) => facts.push((
            "source",
            format!(
                "{} {middot} datui catalog show {}",
                crate::home::BUNDLED_ORIGIN,
                catalog.id
            ),
        )),
        (Some(file), false) => facts.push(("file", crate::home::display_path(file))),
        (None, false) => {}
    }
    if !catalog.description.is_empty() {
        facts.push(("about", catalog.description.clone()));
    }
    if bundled {
        facts.push(("hide", "Del hides it until datui cache clear".to_string()));
        facts.push(("", format!("{for_good} for good")));
    } else {
        facts.push(("hide", for_good));
    }
    let key_w = key_column(facts.iter().map(|(k, _)| *k));
    for (key, value) in facts {
        lines.extend(fact_lines(key, value, key_w, width, plain, ctx));
    }
    lines
}

fn source_details(
    entry: &Entry,
    source: &crate::home::CloudSource,
    width: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let plain = Style::default().fg(ctx.text_secondary);
    let mut lines: Vec<Line> = vec![Line::from(Span::styled(
        entry.name.clone(),
        Style::default()
            .fg(ctx.text_primary)
            .add_modifier(Modifier::BOLD),
    ))];
    let mut facts: Vec<(String, String, Style)> = source
        .details
        .iter()
        .map(|(k, v)| (k.clone(), v.clone(), plain))
        .collect();
    let middot = glyphs::get().middot;
    let listed = match source.listed_at.map(discover::format_age) {
        Some(age) if age == "now" => format!(" {middot} listed now"),
        Some(age) if !age.is_empty() => format!(" {middot} listed {age} ago"),
        _ => String::new(),
    };
    let noun = match source.api.as_str() {
        "azure" => "accounts",
        _ => "buckets",
    };
    match &source.status {
        crate::home::CloudStatus::Listing if source.buckets.is_empty() => {
            facts.push((noun.to_string(), "listing".to_string(), plain));
        }
        crate::home::CloudStatus::Unlisted if source.buckets.is_empty() => {
            facts.push((noun.to_string(), "not listed".to_string(), plain));
        }
        _ => facts.push((
            noun.to_string(),
            format!("{}{listed}", source.buckets.len()),
            plain,
        )),
    }
    lines.push(Line::from(""));
    lines.push(pane_heading("DETAILS", width, ctx));
    let key_w = key_column(facts.iter().map(|(k, _, _)| k.as_str()));
    for (key, value, style) in facts {
        lines.extend(fact_lines(&key, value, key_w, width, style, ctx));
    }
    if let crate::home::CloudStatus::Failed { short, detail } = &source.status {
        lines.push(Line::from(""));
        lines.push(pane_heading(&short.to_uppercase(), width, ctx));
        lines.push(Line::from(Span::styled(
            detail.clone(),
            Style::default().fg(ctx.warning),
        )));
    }
    lines
}

fn render_preview(
    area: Rect,
    buf: &mut Buffer,
    app: &mut crate::App,
    ctx: &RenderContext,
    screen_height: u16,
) {
    let width = area.width as usize;
    // The list is the typed directory's meanwhile; a row's details would be about
    // something not on screen.
    if app.home.path_input_active {
        return;
    }
    if let Some(crate::home::Row::Place {
        path, source, held, ..
    }) = app.home.selected_row()
    {
        Paragraph::new(place_details(&path, source.as_deref(), held, width, ctx))
            .wrap(ratatui::widgets::Wrap { trim: false })
            .render(area, buf);
        return;
    }
    if let Some(crate::home::Row::Hidden { section, count }) = app.home.selected_row() {
        let names: Vec<&str> = app.home.sections[section]
            .rows
            .iter()
            .filter(|row| row.hidden_by_default())
            .map(|row| row.name.as_str())
            .collect();
        let tables = holds_tables(&app.home.sections[section]);
        Paragraph::new(hidden_details(
            &names,
            count,
            tables,
            area.height as usize,
            ctx,
        ))
        .render(area, buf);
        return;
    }
    if let Some(catalog) = app.home.selected_catalog() {
        Paragraph::new(catalog_details(catalog, width, ctx))
            .wrap(ratatui::widgets::Wrap { trim: false })
            .render(area, buf);
        return;
    }
    let Some(entry) = app.home.selected_entry() else {
        return;
    };
    if crate::home::cloud_source_id(&entry.path).is_some() {
        if let Some(source) = app.home.cloud_source_of(&entry.path) {
            Paragraph::new(source_details(&entry, source, width, ctx))
                .wrap(ratatui::widgets::Wrap { trim: false })
                .render(area, buf);
        }
        return;
    }
    let g = glyphs::get();
    // What the source's listing said about this place: an Azure account's subscription,
    // a catalog dataset's publisher. Drawn below the facts, in their key column.
    let place_details = app.home.place_details(&entry.path).map(<[_]>::to_vec);
    let key_w = place_details
        .as_ref()
        .map(|details| key_column(details.iter().map(|(k, _)| k.as_str())))
        .unwrap_or(0);
    // The spec that reads a file, which the spec alone describes without reading it.
    let spec = entry
        .format_spec
        .as_deref()
        .filter(|_| entry.kind == EntryKind::File && entry.table.is_none())
        .and_then(|name| app.home.formats.get(name))
        .cloned();
    let (mut lines, key_w) = preview_head_keyed(
        &entry,
        app.home.place_kind(&entry.path),
        app.home.cloud_look(&entry),
        spec.as_deref(),
        width,
        key_w,
        ctx,
    );
    // That the row that reads a bucket directory whole cannot, before Enter is pressed:
    // what it holds is on the row already, and Enter says why at length.
    #[cfg(feature = "cloud")]
    if entry.opens_whole_directory && crate::App::why_a_door_reads_nothing(&entry).is_some() {
        lines.push(Line::from(Span::styled(
            format!("{} prefix opens Parquet only", g.warning),
            Style::default().fg(ctx.warning),
        )));
    }
    if let Some(details) = place_details {
        for (key, value) in details {
            let style = if key == "network" || key == "shared keys" || key == "access" {
                Style::default().fg(ctx.warning)
            } else {
                Style::default().fg(ctx.text_secondary)
            };
            lines.extend(fact_lines(&key, value, key_w, width, style, ctx));
        }
    }
    // What the columns mean, merged as the Documentation page merges them: the
    // catalog's note over the format spec's. A file inside a catalog dataset gets no
    // catalog notes here: they are the dataset's columns, which need not be the file's.
    if let Some((_, mut doc)) = app.home_documented_row().filter(|(p, _)| *p == entry.path) {
        if app.home.catalog_dataset(&entry.path).is_none()
            && app.home.bookmark(&entry.path).is_none()
        {
            doc.catalog = None;
        }
        let columns = doc.columns();
        if !columns.is_empty() {
            let drawn: usize = lines.iter().map(|line| wrapped_rows(line, width)).sum();
            let room = (area.height as usize).saturating_sub(drawn);
            lines.extend(column_notes_block(&columns, width, room, ctx));
        }
    }

    // ---- Rows --------------------------------------------------------------------
    // Before the schema: a few real values say more about a file than its types. At
    // most the block's own rows, so the columns below keep their room.
    if let Some(preview) = app.home_preview_rows(&entry, screen_height) {
        let drawn: usize = lines.iter().map(|line| wrapped_rows(line, width)).sum();
        let room = (area.height as usize)
            .saturating_sub(drawn + 1)
            .min(2 + crate::home_preview::PREVIEW_ROWS);
        if room >= STRIP_MIN_HEIGHT {
            lines.push(Line::from(""));
            lines.extend(rows_block(&preview, width, room, ctx));
        }
    }

    // ---- Schema ------------------------------------------------------------------
    lines.push(Line::from(""));
    match app.home_schema(&entry) {
        Some(schema) if !schema.is_empty() => {
            lines.push(pane_heading_counted(
                "COLUMNS",
                Some(&crate::numfmt::group_chrome(schema.len())),
                width,
                ctx,
            ));

            let name_w = schema
                .iter()
                .map(|(n, _)| n.chars().count())
                .max()
                .unwrap_or(0)
                .min(22);
            // The rows the lines so far will *occupy*, not how many there are: the
            // pane wraps, and a fact longer than its width takes two rows. Counting
            // lines drew the tail of the schema past the bottom and reported `… N
            // more` as if nothing had been lost.
            let drawn: usize = lines.iter().map(|line| wrapped_rows(line, width)).sum();
            let room = (area.height as usize).saturating_sub(drawn + 1);
            let (shown, mut schema_lines) = schema_lines(&schema, name_w, width, room, ctx);
            lines.append(&mut schema_lines);
            if schema.len() > shown {
                lines.push(Line::from(Span::styled(
                    format!("{} {} more", g.ellipsis, schema.len() - shown),
                    Style::default().fg(ctx.dimmed),
                )));
            }
        }
        _ => {
            // One fragment, or none. The details list above already says what this
            // is, and the control bar already says what Enter does; a sentence
            // repeating either is a sentence to read past on every row.
            let reading =
                app.home_schema_pending(&entry.path) || app.home_preview_pending(&entry.path);
            // Whether there will actually be a door in there to point at. An empty
            // directory gets none, nor does one holding only a writer's own markers, and
            // promising a row that is not there is worse than saying nothing — it is
            // the row a new user would go looking for on the strength of this sentence.
            //
            // The filter on *this* listing is not a reason to withhold it: stepping into
            // a directory clears the filter before the listing inside it is built, so the
            // door will be there — and a user with a filter typed is the one most likely
            // to be lost.
            let door_in_there = !crate::home::holds_nothing_to_open(&entry.holds);
            let web_gone = app.home.web_gone.get(&entry.path);
            let footer_unreadable = entry.kind == EntryKind::File
                && entry.rows.is_none()
                && discover::is_parquet_path(&entry.path)
                && app.home.enriched.contains_key(&entry.path);
            // A file of tables that opens one of them, as its format's descriptor says.
            let opens = discover::data_format(&entry.path)
                .and_then(|f| f.descriptor().tables.as_ref())
                .and_then(|t| t.opens);
            // What → lists: a spec's variants are record types, a real file's members
            // tables.
            let inside = if entry.format_spec.is_some() {
                (g.arrow_right, "its record types".to_string())
            } else {
                (g.arrow_right, "its tables".to_string())
            };
            // What the spec says the file holds: its variants, or its columns.
            let variants = spec
                .as_deref()
                .filter(|s| s.lists_variants())
                .map(crate::members::variant_tables);
            let spec_columns = spec
                .as_deref()
                .and_then(crate::formats::Spec::static_columns)
                .filter(|c| !c.is_empty());
            let step_in = |then: &str| format!("step in {} {then}", g.middot);
            let notes: Vec<(&str, String)> = match entry.kind {
                // The door itself. It is the row the other notes point at, so it says
                // what it does rather than where to find it.
                _ if entry.opens_whole_directory => {
                    let does = match crate::home::door_kind(&entry) {
                        crate::home::DoorKind::Lake => DOOR_OF_A_LAKE_TABLE,
                        crate::home::DoorKind::Hive => DOOR_OF_A_HIVE_TABLE,
                        crate::home::DoorKind::SchemasDiffer => DOOR_OF_FILES_THAT_DIFFER,
                        crate::home::DoorKind::Mixed | crate::home::DoorKind::Single => {
                            DOOR_OF_A_MIX
                        }
                        crate::home::DoorKind::OneSchema | crate::home::DoorKind::Unknown => {
                            THE_DOOR
                        }
                    };
                    vec![("Enter", does.to_string())]
                }
                // Where the other door is. A directory datui will not read as one table
                // is the row a new user is most likely to be stuck on — the label says
                // what is in there, Enter steps into it, and nothing until now said that
                // the way to read the whole of it is one row further in.
                // A web file a HEAD settled cannot be had: why, before Enter is pressed
                // on it. A callout, as an unreadable footer is.
                _ if web_gone.is_some() => {
                    if let Some(gone) = web_gone {
                        lines.push(Line::from(Span::styled(
                            format!("{} {}", g.warning, gone.message),
                            Style::default().fg(ctx.warning),
                        )));
                    }
                    Vec::new()
                }
                EntryKind::Directory if door_in_there => {
                    vec![("Enter", step_in(INSIDE_AND_THE_DOOR))]
                }
                EntryKind::Directory => Vec::new(),
                // A catalog's local dataset that is not there: the kind line says so.
                EntryKind::Unknown if app.home.missing.contains(&entry.path) => Vec::new(),
                EntryKind::Unknown => vec![("schema", "not read".to_string())],
                EntryKind::Other => {
                    vec![("format", format!("unknown {} Enter shows hex", g.middot))]
                }
                EntryKind::File if entry.enter_lists_tables() => {
                    vec![("Enter", "its tables".to_string())]
                }
                // The spec's variants are the spec's to say, whatever a measurement or a
                // cached record left in the row's count.
                EntryKind::File
                    if variants.is_some() || entry.cost.tables.is_some_and(|n| n > 1) =>
                {
                    let opens = opens.filter(|_| entry.cost.opens_one);
                    let mut notes = vec![
                        ("Enter", opens.unwrap_or("every record").to_string()),
                        inside,
                    ];
                    if let Some(variants) = &variants {
                        let n = variants.len();
                        let what = if n == 1 { "type" } else { "types" };
                        notes.push(("records", format!("{n} {what} (spec)")));
                    }
                    notes
                }
                // The log says which files are live, and datui does not read it.
                k if k.is_lake_table() && door_in_there => {
                    vec![("Enter", step_in(INSIDE_A_LAKE_TABLE))]
                }
                k if k.is_lake_table() => vec![("Enter", step_in("log not read"))],
                // Measured, and its footer said nothing: the open will most likely fail
                // the same way, and saying so before Enter beats a pane promising columns
                // (#547 D8). A callout rather than a fact: it is the surprise.
                EntryKind::File if footer_unreadable => {
                    lines.push(Line::from(Span::styled(
                        format!("{} {FOOTER_UNREADABLE}", g.warning),
                        Style::default().fg(ctx.warning),
                    )));
                    Vec::new()
                }
                _ if spec_columns.is_some() => {
                    let n = spec_columns.as_ref().map_or(0, Vec::len);
                    let what = if n == 1 { "column" } else { "columns" };
                    vec![("schema", format!("{n} {what} (spec)"))]
                }
                _ if reading => vec![("schema", "reading...".to_string())],
                // Only Parquet says its columns without being read; everything else is
                // read when it is opened, which is nothing to warn about.
                _ => vec![("schema", "on open".to_string())],
            };
            let note_w = key_column(notes.iter().map(|(k, _)| *k)).max(key_w);
            let style = Style::default().fg(ctx.text_secondary);
            let said_spec = notes.iter().any(|(_, v)| v.ends_with("(spec)"));
            for (key, value) in notes {
                lines.extend(fact_lines(key, value, note_w, width, style, ctx));
            }
            if said_spec {
                let drawn: usize = lines.iter().map(|line| wrapped_rows(line, width)).sum();
                let room = (area.height as usize).saturating_sub(drawn + 1);
                lines.extend(spec_schema_lines(
                    variants.as_deref(),
                    spec_columns.as_deref(),
                    note_w + 2,
                    width,
                    room,
                    ctx,
                ));
            }
        }
    }

    Paragraph::new(lines)
        .wrap(ratatui::widgets::Wrap { trim: false })
        .render(area, buf);
}

/// What a spec says a file holds, under its `records` or `schema` line: its record
/// types and their column counts packed under the value column (`Status 6 · OrderAdd 9
/// · …`), wrapping between whole items; or each column and its type. As many as `room`
/// rows hold.
fn spec_schema_lines(
    variants: Option<&[crate::members::Table]>,
    columns: Option<&[(String, polars::prelude::DataType)]>,
    indent: usize,
    width: usize,
    room: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    if let Some(variants) = variants {
        return variant_lines(variants, indent, width, room, ctx);
    }
    let Some(columns) = columns else {
        return Vec::new();
    };
    let name_w = columns
        .iter()
        .map(|(n, _)| n.chars().count())
        .max()
        .unwrap_or(0)
        .min(22);
    let (_, mut lines) = schema_lines(columns, name_w, width, room, ctx);
    if columns.len() > lines.len() {
        if lines.len() == room && !lines.is_empty() {
            lines.pop();
        }
        lines.push(Line::from(Span::styled(
            format!(
                "{} {} more",
                glyphs::get().ellipsis,
                columns.len() - lines.len()
            ),
            Style::default().fg(ctx.dimmed),
        )));
    }
    lines
}

/// A spec's variants as `name count` items under the value column, ` · ` between them,
/// a line breaking only between items; `… N more` when `room` rows do not hold them.
fn variant_lines(
    variants: &[crate::members::Table],
    indent: usize,
    width: usize,
    room: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let g = glyphs::get();
    let avail = width.saturating_sub(indent).max(1);
    let sep = format!(" {} ", g.middot);
    let sep_w = glyphs::display_width(&sep);
    let name_style = Style::default().fg(ctx.text_secondary);
    let count_style = Style::default().fg(ctx.dimmed);
    let mut rows: Vec<(Vec<Span<'static>>, usize, usize)> = Vec::new();
    for variant in variants {
        let count = variant.columns.len().to_string();
        let count_w = count.len() + 1;
        let name = glyphs::fit_cells(&variant.name, avail.saturating_sub(count_w), g.ellipsis)
            .into_owned();
        let w = glyphs::display_width(&name) + count_w;
        let item = [
            Span::styled(name, name_style),
            Span::styled(format!(" {count}"), count_style),
        ];
        match rows.last_mut() {
            Some((spans, used, n)) if *used + sep_w + w <= avail => {
                spans.push(Span::styled(sep.clone(), count_style));
                spans.extend(item);
                *used += sep_w + w;
                *n += 1;
            }
            _ => rows.push((item.to_vec(), w, 1)),
        }
    }
    if room == 0 {
        return Vec::new();
    }
    let mut shown = 0;
    let mut lines: Vec<Line<'static>> = Vec::new();
    let lead = || Span::raw(" ".repeat(indent));
    for (spans, _, n) in rows.iter().take(room) {
        lines.push(Line::from(
            std::iter::once(lead())
                .chain(spans.iter().cloned())
                .collect::<Vec<_>>(),
        ));
        shown += n;
    }
    if shown < variants.len() {
        if lines.len() == room {
            if let Some((_, _, n)) = rows.get(lines.len() - 1) {
                shown -= n;
            }
            lines.pop();
        }
        lines.push(Line::from(vec![
            lead(),
            Span::styled(
                format!("{} {} more", g.ellipsis, variants.len() - shown),
                count_style,
            ),
        ]));
    }
    lines
}

/// The callout on a Parquet file whose footer could not be read, after the warning glyph.
const FOOTER_UNREADABLE: &str = "footer unreadable";

/// What `Enter` does on a directory it steps into rather than opens, after `step in`.
const INSIDE_AND_THE_DOOR: &str = "first row opens all";

/// The same, for a lake table, whose files are not its rows.
const INSIDE_A_LAKE_TABLE: &str = "first row reads files, log ignored";

/// What `Enter` does on the `(all files)` row itself.
const THE_DOOR: &str = "all files as one table";

/// The same, in a hive directory.
const DOOR_OF_A_HIVE_TABLE: &str = "all partitions as one table";

/// The same, in a lake table, whose log decides which files are live.
const DOOR_OF_A_LAKE_TABLE: &str = "all files, log ignored";

/// The same, where the files' columns disagree.
const DOOR_OF_FILES_THAT_DIFFER: &str = "files stacked, columns matched by name";

/// The same, where only part of the directory is read: the `reads` line says which.
const DOOR_OF_A_MIX: &str = "matching files as one table";

/// Every value the pane offers as guidance, for the test that reads them.
#[cfg(test)]
fn guidance_notes() -> [&'static str; 8] {
    [
        FOOTER_UNREADABLE,
        INSIDE_AND_THE_DOOR,
        INSIDE_A_LAKE_TABLE,
        THE_DOOR,
        DOOR_OF_A_HIVE_TABLE,
        DOOR_OF_A_LAKE_TABLE,
        DOOR_OF_FILES_THAT_DIFFER,
        DOOR_OF_A_MIX,
    ]
}

/// The pane for the row standing in for hidden files: which files they are, as many
/// as fit, so the count is never all there is to go on.
fn hidden_details(
    names: &[&str],
    count: usize,
    tables: bool,
    height: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let g = glyphs::get();
    let (title, what) = match (tables, count) {
        (true, 1) => ("Hidden tables", "1 internal SQLite table".to_string()),
        (true, _) => ("Hidden tables", format!("{count} internal SQLite tables")),
        (false, 1) => ("Hidden files", "1 file with no reader".to_string()),
        (false, _) => ("Hidden files", format!("{count} files with no reader")),
    };
    let mut lines: Vec<Line> = vec![
        Line::from(Span::styled(
            title.to_string(),
            Style::default()
                .fg(ctx.text_primary)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(what, Style::default().fg(ctx.dimmed))),
        Line::from(""),
    ];
    // The rows left, less one for the `… N more` line when not all of them fit.
    let room = height.saturating_sub(lines.len());
    let shown = if names.len() > room {
        room.saturating_sub(1)
    } else {
        names.len()
    };
    for name in &names[..shown] {
        lines.push(Line::from(Span::styled(
            name.to_string(),
            Style::default().fg(ctx.text_secondary),
        )));
    }
    if shown < names.len() {
        lines.push(Line::from(Span::styled(
            format!("{} {} more", g.ellipsis, names.len() - shown),
            Style::default().fg(ctx.dimmed),
        )));
    }
    lines
}

/// The pane for a place under `RECENT`: what it is, where, and how many recents it
/// holds. From what the listing already knows; a place is never read for this.
fn place_details(
    path: &std::path::Path,
    source: Option<&str>,
    held: usize,
    width: usize,
    ctx: &RenderContext,
) -> Vec<Line<'static>> {
    let plain = Style::default().fg(ctx.text_secondary);
    // Named like any row: its last component, or the whole of it at a root or a
    // bucket, which have none.
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| crate::home::display_path(path));
    let mut lines: Vec<Line> = vec![
        Line::from(Span::styled(
            name,
            Style::default()
                .fg(ctx.text_primary)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(
            truncate_start(&crate::home::display_path(path), width),
            Style::default().fg(ctx.dimmed),
        )),
    ];
    let mut facts: Vec<(&str, String, Style)> = Vec::new();
    if let Some(source) = source.map(crate::locality::Source::from_fstype) {
        let style = match source.locality {
            crate::locality::Locality::Network | crate::locality::Locality::Object => {
                Style::default().fg(ctx.warning)
            }
            crate::locality::Locality::Memory => Style::default().fg(ctx.success),
            _ => plain,
        };
        facts.push(("storage", source.label().to_string(), style));
    }
    facts.push(("opened here", held.to_string(), plain));
    // Said before Enter is pressed rather than after: Enter does nothing here.
    if !crate::home::place_is_browsable(path) {
        facts.push(("listing", "none over HTTP".to_string(), plain));
    }
    let key_w = key_column(facts.iter().map(|(k, _, _)| *k));
    for (key, value, style) in facts {
        lines.extend(fact_lines(key, value, key_w, width, style, ctx));
    }
    lines
}

/// Whether a row's name is drawn with a trailing slash.
///
/// A row nothing has looked into is still a place: a listing datui made itself only ever
/// puts a directory on one, so `project.old` and `v1.2` keep their slash however many
/// dots are in the name. A remote row — a bucket, an HTTP URL, a path on a share — is
/// the one nothing can stat, and there the name is all there is — so a name with an extension is a file even when it is one datui does not
/// read (`export.txt`), and everything else is a prefix.
///
/// Said up front so the name does not change shape a frame later when the label lands;
/// the `…` beside it already carries the part that is not known.
fn shows_as_a_place(entry: &Entry) -> bool {
    // The row that opens the directory being browsed is an action, not a place: → does
    // nothing on it, so a trailing slash offers a step that is not there.
    if entry.opens_whole_directory {
        return false;
    }
    // A dataset that is a directory is still one: `events/  hive` reads as the place
    // it is, the way `data/  3 dirs` does.
    if matches!(
        entry.kind,
        EntryKind::Directory | EntryKind::Hive | EntryKind::MultiFile
    ) || entry.kind.is_lake_table()
    {
        return true;
    }
    if entry.kind != EntryKind::Unknown {
        return false;
    }
    !crate::home::is_remote_path(&entry.path)
        || (!crate::discover::is_data_file(&entry.path) && entry.path.extension().is_none())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::discover::Entry;
    use crate::home::Section;

    /// The list as an entry row is drawn in, at `name_width`.
    fn rows<'f>(
        ctx: &'f RenderContext,
        name_width: usize,
        show_meta: bool,
        filter: &'f str,
    ) -> ListDraw<'f> {
        ListDraw {
            ctx,
            width: name_width,
            name_width,
            show_meta,
            filter,
            frame: 0,
        }
    }

    /// The list as a section header is drawn in, `width` wide.
    fn header_row(ctx: &RenderContext, width: usize) -> ListDraw<'_> {
        rows(ctx, width, true, "")
    }

    /// The pane's guidance is a value, not a sentence: short, lower case, unpunctuated,
    /// with no gap left by a wrapped literal (`cargo fmt` once joined a `\` continuation
    /// back up and kept the indentation with it).
    #[test]
    fn the_pane_s_guidance_is_a_value_not_a_sentence() {
        for note in guidance_notes() {
            assert!(
                !note.contains("  "),
                "a run of spaces in the middle of {note:?}"
            );
            assert!(
                !note.ends_with('.') && !note.contains('\n') && !note.contains(';'),
                "a value, not a sentence: {note:?}"
            );
            assert!(
                note.chars().count() <= 40,
                "short enough for the pane: {note:?}"
            );
        }
    }

    fn row(path: &str, kind: crate::discover::EntryKind) -> Entry {
        Entry {
            path: std::path::PathBuf::from(path),
            kind,
            name: path.rsplit('/').next().unwrap_or(path).to_string(),
            size: None,
            modified: None,
            rows: None,
            cols: None,
            cols_sampled: false,
            columns: Vec::new(),
            cost: Default::default(),
            holds: Default::default(),
            opens_whole_directory: false,
            format_spec: None,
            table: None,
        }
    }

    /// A row with nothing in the meta columns gives them to its name, and an empty
    /// shape cell gives its columns too, size and age staying aligned; a relative path
    /// keeps its leaf (#648).
    #[test]
    fn blank_meta_columns_go_to_the_name() {
        let ctx = RenderContext::for_test();
        let text = |entry: &Entry| -> String {
            entry_line(
                entry,
                false,
                EntryNotes::default(),
                &rows(&ctx, 26, true, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
        };
        let mut public = row("/data/food_nutrition.csv", EntryKind::File);
        public.name = "Food nutrition (fast food)".to_string();
        assert!(text(&public).contains("Food nutrition (fast food)"));

        let mut sized = row("/data/chart_export_overwrite_test.csv", EntryKind::File);
        sized.size = Some(25);
        let mut shaped = sized.clone();
        shaped.rows = Some(3);
        shaped.cols = Some(2);
        let (sized, shaped) = (text(&sized), text(&shaped));
        assert!(
            sized.contains("chart_export_overwrite_test.csv"),
            "{sized:?}"
        );
        assert!(
            !shaped.contains("chart_export_overwrite_test.csv"),
            "{shaped:?}"
        );
        assert_eq!(
            sized.chars().count(),
            shaped.chars().count(),
            "the same width either way"
        );
        assert_eq!(
            sized.find("25 B").map(|at| sized[..at].chars().count()),
            shaped.find("25 B").map(|at| shaped[..at].chars().count()),
            "size stays in its column"
        );

        let mut hit = row(
            "/data/tests/sample-data/sales_by_region.csv",
            EntryKind::File,
        );
        hit.name = "tests/sample-data/sales_by_region.csv".to_string();
        hit.size = Some(25);
        hit.rows = Some(3);
        hit.cols = Some(2);
        assert!(text(&hit).contains("region.csv"), "{:?}", text(&hit));
    }

    /// The row and the pane beside it say the same word about one directory. They are two
    /// renderers with the same question to answer, and answering it in two orders is
    /// how a list says `12 parquet` while the pane says `dataset`.
    #[test]
    fn the_row_and_the_pane_agree_on_what_a_directory_is() {
        let ctx = RenderContext::for_test();
        let mut entry = row("s3://bucket/occurrence", EntryKind::Directory);
        entry.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 12)],
            ..Default::default()
        };
        for curated in [None, Some("dataset"), Some("project")] {
            let line = entry_line(
                &entry,
                false,
                EntryNotes {
                    place_kind: curated,
                    ..EntryNotes::default()
                },
                &rows(&ctx, 40, false, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<Vec<_>>()
            .join("");
            let pane: String = preview_head(&entry, curated, None, 60, &ctx)
                .iter()
                .flat_map(|l| l.spans.iter())
                .map(|s| s.content.as_ref())
                .collect();
            let word = curated.unwrap_or("12 parquet");
            assert!(
                pane.contains(word),
                "the pane {pane:?} does not name it {word:?}"
            );
            assert!(
                line.contains(word),
                "the row {line:?} does not name it {word:?}"
            );
        }
    }

    /// A directory in a bucket reads like a local one: a spinner while it is looked
    /// into, `…` before, and then what it holds, or `dir`. Never `prefix`, which said
    /// nothing a user could act on. A bucket keeps its word.
    #[test]
    fn a_cloud_directory_is_labelled_by_what_it_holds() {
        let ctx = RenderContext::for_test();
        let drawn = |entry: &Entry, looking: Option<&'static str>| -> String {
            entry_line(
                entry,
                false,
                EntryNotes {
                    looking,
                    ..EntryNotes::default()
                },
                &rows(&ctx, 40, false, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<Vec<_>>()
            .join("")
        };
        let g = glyphs::get();
        let spinner = g.spinner[0];

        let mut directory = row("s3://bucket/exports", EntryKind::Directory);
        let text = drawn(&directory, Some(spinner));
        assert!(text.contains(spinner), "{text}");
        assert!(!text.contains("dir") && !text.contains("prefix"), "{text}");
        let text = drawn(&directory, Some(g.ellipsis));
        assert!(text.contains(g.ellipsis), "{text}");

        // Looked into, and nothing counted: a directory of directories.
        let text = drawn(&directory, None);
        assert!(text.contains(" dir"), "{text}");
        assert!(!text.contains("prefix"), "{text}");

        directory.holds = crate::discover::Holds {
            formats: vec![("csv".to_string(), 12)],
            ..Default::default()
        };
        let text = drawn(&directory, None);
        assert!(text.contains("12 csv"), "{text}");

        let bucket = row("s3://bucket", EntryKind::Directory);
        assert!(drawn(&bucket, Some(g.ellipsis)).contains("bucket"));
        let container = row(
            "abfss://data@acct.dfs.core.windows.net/",
            EntryKind::Directory,
        );
        assert!(drawn(&container, Some(g.ellipsis)).contains("container"));
        let inside = row(
            "abfss://data@acct.dfs.core.windows.net/jolpica",
            EntryKind::Directory,
        );
        assert!(!drawn(&inside, None).contains("prefix"));
    }

    /// One grammar on every row: the name, a slash when it is a place to go into, two
    /// cells, and what it is. Local, catalog and bucket rows alike, a directory of
    /// directories counting them (#547 M7).
    #[test]
    fn every_row_reads_name_slash_two_spaces_label() {
        let ctx = RenderContext::for_test();
        let drawn = |entry: &Entry, place_kind: Option<&'static str>| -> String {
            entry_line(
                entry,
                false,
                EntryNotes {
                    place_kind,
                    ..EntryNotes::default()
                },
                &rows(&ctx, 60, true, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<Vec<_>>()
            .join("")
        };
        let mut local = row("/data/project/data", EntryKind::Directory);
        local.holds.directories = 3;
        let mut hive = row("/data/project/events", EntryKind::Hive);
        hive.holds.partitions = 2;
        let mut parquet = row("/data/project/processed", EntryKind::MultiFile);
        parquet.holds.formats = vec![("parquet".to_string(), 2)];
        let mut prefix = row("s3://bucket/exports", EntryKind::Directory);
        prefix.holds.formats = vec![("csv".to_string(), 12)];
        let bucket = row("s3://noaa-ghcn-pds", EntryKind::Directory);
        let mut noaa = row("s3://noaa-ghcn-pds/parquet/", EntryKind::Directory);
        noaa.name = "NOAA daily weather".to_string();
        let mut penguins = row("https://example.com/csv/penguins.csv", EntryKind::File);
        penguins.name = "Palmer penguins".to_string();
        for (entry, place_kind, expect) in [
            (&local, None, "data/  3 dirs"),
            (&hive, None, "events/  hive"),
            (&parquet, None, "processed/  2 parquet"),
            (&prefix, None, "exports/  12 csv"),
            (&bucket, None, "noaa-ghcn-pds/  bucket"),
            (&noaa, Some("dataset"), "NOAA daily weather/  dataset"),
            (&penguins, None, "Palmer penguins  csv"),
        ] {
            let text = drawn(entry, place_kind);
            assert!(text.contains(expect), "{expect:?} in {text:?}");
        }
    }

    /// And the pane beside it says the same word. The two take the same order through
    /// two separate matches, so a directory with nothing counted in it can read `prefix`
    /// on the row and `dir` in the pane — the one disagreement this is all arranged to
    /// stop, on the row a search is about.
    /// The row that opens the directory being browsed has no label, and in a bucket a
    /// directory of Parquet files is a kind that wears its label as a chip. The chip is
    /// drawn by taking the cell apart again, so a chip made of nothing indexed past the
    /// end of an empty string and brought the renderer down — on a real GCS prefix,
    /// where CI found it and no test here had put the two together.
    #[test]
    fn the_row_that_opens_a_directory_draws_without_a_label() {
        let ctx = RenderContext::for_test();
        let mut drawn: Vec<(EntryKind, String)> = Vec::new();
        for kind in [EntryKind::MultiFile, EntryKind::Hive, EntryKind::Directory] {
            let mut door = row("gs://cloud-samples-data/bigquery/us-states", kind);
            door.name = "us-states (all files)".to_string();
            door.opens_whole_directory = true;
            door.holds = crate::discover::Holds {
                formats: vec![("parquet".to_string(), 9)],
                ..Default::default()
            };
            assert_eq!(door.label(), "", "{kind:?}");

            // Every width, because the crash was in taking the cell apart and the
            // widths are where the cell is rewritten. Nothing here asserts a shape:
            // drawing at all is the thing that was not happening.
            for width in 1..=60usize {
                let line = entry_line(
                    &door,
                    false,
                    EntryNotes::default(),
                    &rows(&ctx, width, true, ""),
                );
                let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                assert!(!text.is_empty(), "at {width} cells, {kind:?}");
            }
            // And with room to spare it reads as itself, with no label beside it.
            let line = entry_line(
                &door,
                false,
                EntryNotes::default(),
                &rows(&ctx, 40, true, ""),
            );
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(text.contains("us-states (all files)"), "{kind:?}: {text:?}");
            assert!(!text.contains("parquet"), "{kind:?}: {text:?}");
            drawn.push((kind, text));
        }

        // Nor does a curated place word or a source id stand in for the label it does
        // not have. Both are about the directory; this row is the door into it, and
        // `bigquery (all files)  dataset` says the door is the dataset.
        let mut door = row("s3://lab@bucket/exports", EntryKind::Directory);
        door.name = "exports (all files)".to_string();
        door.opens_whole_directory = true;
        let known = ["lab".to_string()];
        let text: String = entry_line(
            &door,
            false,
            EntryNotes {
                known_sources: Some(&known),
                place_kind: Some("dataset"),
                ..EntryNotes::default()
            },
            &rows(&ctx, 60, true, ""),
        )
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect();
        assert!(text.contains("exports (all files)"), "{text:?}");
        assert!(
            !text.contains("dataset"),
            "curated word on a door: {text:?}"
        );
        assert!(!text.contains("lab"), "source id on a door: {text:?}");

        // And the pane beside it says the same nothing. It takes the place word through
        // a second match of its own, which is how the row and the pane come to disagree
        // about one directory.
        let mut door = row("s3://bucket/warehouse", EntryKind::Directory);
        door.name = "warehouse (all files)".to_string();
        door.opens_whole_directory = true;
        let pane = preview_text(&door, 60);
        assert!(pane.contains("warehouse (all files)"), "{pane}");
        assert!(
            !pane.lines().any(|l| l.trim_start().starts_with("kind")),
            "a kind stood in for the label it does not have: {pane}"
        );

        // And all three draw the same row. A hive or multi-file kind wears its label as
        // a chip, which is a space of the row's own background and then the label — so
        // with no label, a kind that would have worn one leaves the space behind and
        // the row sits one cell right of every other door.
        let (_, first) = &drawn[0];
        for (kind, text) in &drawn[1..] {
            assert_eq!(first, text, "{kind:?} drew a different row");
        }
    }

    /// And the pane beside it agrees: no kind while it is being looked into, `?` with
    /// why when looking failed, `directory` once it has been, and the count on the
    /// `contains` line when there is one.
    #[test]
    fn the_pane_calls_a_cloud_directory_what_the_row_calls_it() {
        use crate::home::CloudLook;
        let ctx = RenderContext::for_test();
        let pane = |entry: &Entry, looking: Option<CloudLook>| -> Vec<String> {
            preview_head(entry, None, looking, 60, &ctx)
                .iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.as_ref())
                        .collect::<String>()
                })
                .collect()
        };
        let kind_line = |lines: &[String]| {
            lines
                .iter()
                .find(|l| l.trim_start().starts_with("kind"))
                .cloned()
        };

        let mut directory = row("s3://bucket/warehouse", EntryKind::Directory);
        assert_eq!(kind_line(&pane(&directory, Some(CloudLook::Waiting))), None);
        assert_eq!(kind_line(&pane(&directory, Some(CloudLook::Looking))), None);
        let failed = kind_line(&pane(&directory, Some(CloudLook::Failed))).expect("a kind");
        assert!(failed.contains("listing failed"), "{failed}");
        let looked = kind_line(&pane(&directory, None)).expect("a kind");
        assert!(looked.trim_end().ends_with("directory"), "{looked}");

        directory.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 12)],
            ..Default::default()
        };
        let lines = pane(&directory, None);
        let contains = lines
            .iter()
            .find(|l| l.trim_start().starts_with("contains"))
            .expect("a contains line");
        assert!(contains.contains("12 parquet"), "{contains}");
    }

    /// A row count that is out of reach says `?`. A directory that is not one table has
    /// none to be out of reach, and must not read like a dataset too big to count.
    #[test]
    fn a_directory_of_separate_tables_shows_its_width_without_a_question_mark() {
        let mut directory = row("/data/consolidated", EntryKind::Directory);
        directory.cols = Some(72);
        let shape = meta_columns(&directory, false, None, None);
        assert!(shape.contains("72 cols"), "{shape}");
        assert!(!shape.contains('?'), "{shape}");
        assert!(
            !shape.contains(glyphs::get().times),
            "an operator with nothing on its left: {shape}"
        );

        let mut big = row("/data/events", EntryKind::Hive);
        big.cols = Some(72);
        assert!(
            meta_columns(&big, false, None, None).contains('?'),
            "a hive dataset still says ?"
        );
    }

    /// A schema line wraps too, so the budget counts the rows they take rather than
    /// one per column. Taking a column per row draws the tail past the bottom of the
    /// pane and sends the `… N more` line over the edge with it — the loss the count
    /// exists to report.
    #[test]
    fn a_wrapping_schema_line_is_paid_for_at_its_real_height() {
        use polars::prelude::DataType;
        let ctx = RenderContext::for_test();
        // Forty cells is what the pane has; this type alone is past it.
        let long = (0..6).fold(DataType::Int64, |inner, _| DataType::List(Box::new(inner)));
        assert!(
            format!("{long}").chars().count() > 18,
            "a type past the pane's forty cells beside a name: {long}"
        );
        let schema: Vec<(String, DataType)> = (0..10)
            .map(|i| (format!("created_at_{i}"), long.clone()))
            .collect();

        let (shown, lines) = schema_lines(&schema, 22, 40, 6, &ctx);
        let rows: usize = lines.iter().map(|l| wrapped_rows(l, 40)).sum();
        assert!(rows <= 6, "{rows} rows drawn into six: {shown} columns");
        assert!(shown < 6, "each column takes more than one row: {shown}");
        assert!(shown > 0, "and at least one still fits");
    }

    /// The pane word-wraps, so a row count taken by dividing the width into the length
    /// is a floor: a word that will not fit goes whole to the next row. The schema list
    /// is drawn in what is left, and under-counting drew its tail past the bottom while
    /// `… N more` reported nothing lost.
    #[test]
    fn a_wrapped_line_is_counted_by_the_rows_it_takes() {
        let line = |text: &str| Line::from(vec![Span::raw(text.to_string())]);
        assert_eq!(wrapped_rows(&line("short"), 40), 1);
        // Five four-letter words at a width of six. Dividing twenty-four characters
        // into six says four rows; each row can hold one word and the two cells left
        // beside it are cells no word can use, so it takes five.
        assert_eq!(
            wrapped_rows(&line("aaaa aaaa aaaa aaaa aaaa"), 6),
            5,
            "the room left at the end of a row is room a word cannot use"
        );
        // A single word longer than the pane wraps inside itself.
        assert_eq!(wrapped_rows(&line(&"x".repeat(25)), 10), 3);
        // Cells, not characters. Three glyphs of two cells each do not fit in five,
        // and counting characters would say they do — a skipped file can be named in
        // a script where that is true of every letter.
        assert_eq!(
            wrapped_rows(&line("漢字漢"), 5),
            2,
            "three characters, six cells"
        );
    }

    /// A label describes and a name identifies, so on a screen too narrow for both the
    /// label goes. Before this a `5000+ parquet` chip left the name nothing to be
    /// truncated into and shoved the size and modified columns out of alignment.
    #[test]
    fn a_label_gives_way_to_the_name_on_a_narrow_screen() {
        let ctx = RenderContext::for_test();
        let mut entry = row("/data/exports", crate::discover::EntryKind::MultiFile);
        // Real metadata, so the meta columns are a string the offset can be found by.
        entry.size = Some(4096);
        entry.rows = Some(12);
        // A shape too: a row with an empty shape cell gives it to the name (#648).
        entry.cols = Some(3);
        entry.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 5000)],
            truncated: true,
            ..Default::default()
        };
        assert_eq!(entry.label(), "5000+ parquet");

        // Where the meta columns begin: everything drawn before them. It must not
        // depend on how long a row's label is, or the columns stop lining up.
        let offset_of_meta = |line: Line<'_>, entry: &Entry| -> usize {
            let meta = meta_columns(entry, false, None, None);
            let at = line
                .spans
                .iter()
                .position(|s| s.content == meta)
                .expect("the meta columns are drawn");
            line.spans[..at]
                .iter()
                .map(|s| s.content.chars().count())
                .sum()
        };
        let meta_starts_at = |entry: &Entry, width: usize| -> usize {
            let line = entry_line(
                entry,
                false,
                EntryNotes::default(),
                &rows(&ctx, width, true, ""),
            );
            offset_of_meta(line, entry)
        };

        // The same kind, so only the label's length differs: a `Directory` row carries
        // a trailing slash and would be a character wider for a reason of its own.
        let mut short = row("/data/exports", crate::discover::EntryKind::MultiFile);
        short.size = Some(4096);
        short.rows = Some(12);
        short.cols = Some(3);
        short.holds = crate::discover::Holds {
            formats: vec![("csv".to_string(), 2)],
            ..Default::default()
        };
        assert_eq!(short.label(), "2 csv");

        for width in [22usize, 24, 30, 48, 100] {
            assert_eq!(
                meta_starts_at(&entry, width),
                meta_starts_at(&short, width),
                "the meta columns must start in the same place at {width}"
            );
        }

        // The curated word is not a label to give up. `dataset` and `project` are what
        // a source calls a place it names, and the only thing marking a curated row.
        let mut named = row("s3://bucket/occurrence", EntryKind::Directory);
        named.size = Some(4096);
        named.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 5000)],
            truncated: true,
            ..Default::default()
        };
        let curated = |width: usize| -> String {
            entry_line(
                &named,
                false,
                EntryNotes {
                    place_kind: Some("dataset"),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<Vec<_>>()
            .join("")
        };
        // Narrow enough that the guard fires: the word is eight cells with its space,
        // so anything at or under fourteen leaves the name nothing to be cut into.
        for width in [10usize, 12, 14, 22, 30] {
            assert!(
                curated(width).contains("dataset"),
                "at {width}: {}",
                curated(width)
            );
        }

        // And a row whose *path* is curated but whose kind never reaches for the word
        // is carrying a label, which gives way like any other. Only a `Directory` row
        // consults `place_kind`; a `multi` prefix in a catalog does not.
        let mut curated_multi = row("s3://bucket/occurrence", EntryKind::MultiFile);
        curated_multi.size = Some(4096);
        curated_multi.rows = Some(12);
        curated_multi.cols = Some(3);
        curated_multi.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 5000)],
            truncated: true,
            ..Default::default()
        };
        let with_curated_path = |width: usize| -> usize {
            let line = entry_line(
                &curated_multi,
                false,
                EntryNotes {
                    place_kind: Some("dataset"),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            );
            offset_of_meta(line, &curated_multi)
        };
        for width in [20usize, 22, 24, 30] {
            assert_eq!(
                with_curated_path(width),
                meta_starts_at(&short, width),
                "a count under a curated path still gives way at {width}"
            );
        }

        // A cell the guard may not drop is cut instead. A `source not found:` is as
        // long as somebody's configuration, and a name with nothing left to be cut
        // into is the misalignment all of this is for.
        let mut gone = row("s3://averylongsourcename@bucket/exports", EntryKind::File);
        gone.size = Some(4096);
        gone.rows = Some(12);
        gone.cols = Some(3);
        let known: [String; 1] = ["other".to_string()];
        let missing = |width: usize| -> usize {
            let line = entry_line(
                &gone,
                false,
                EntryNotes {
                    known_sources: Some(&known),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            );
            offset_of_meta(line, &gone)
        };
        for width in [22usize, 24, 30, 48] {
            assert_eq!(
                missing(width),
                meta_starts_at(&short, width),
                "a warning too long for the row is cut, not left to push the columns \
                 out, at {width}"
            );
        }

        // An uncut note keeps the mark on its last letter. The subtraction that makes
        // room for the ellipsis applies only where there is one.
        let marks = |width: usize| -> Vec<String> {
            entry_line(
                &short,
                false,
                EntryNotes {
                    matched_column: Some("amount"),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, "amount"),
            )
            .spans
            .iter()
            .filter(|s| s.style.add_modifier.contains(Modifier::UNDERLINED))
            .map(|s| s.content.to_string())
            .collect()
        };
        assert_eq!(
            marks(200).join(""),
            "amount",
            "every letter of the match is marked when the note is whole"
        );

        // A label under a named source is still a label. The path carrying a source id
        // is a different question from the cell showing one, and a peeked prefix under
        // `s3://prod@bucket` has both.
        let mut named = row("s3://prod@bucket/exports", EntryKind::MultiFile);
        named.size = Some(4096);
        named.rows = Some(12);
        named.cols = Some(3);
        named.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 12000)],
            ..Default::default()
        };
        let sources = ["prod".to_string()];
        let offset = |width: usize| -> usize {
            let line = entry_line(
                &named,
                false,
                EntryNotes {
                    known_sources: Some(&sources),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            );
            offset_of_meta(line, &named)
        };
        for width in [22usize, 24, 30] {
            assert_eq!(
                offset(width),
                meta_starts_at(&short, width),
                "a label under a named source gives way like any other, at {width}"
            );
        }

        // A column note is not a label: it says why the row is in the list, and the
        // draw site writes it from `matched_column` rather than from the cell, so
        // blanking the cell would hand the name a budget the note then overruns.
        let noted = |entry: &Entry, width: usize| -> usize {
            let line = entry_line(
                entry,
                false,
                EntryNotes {
                    matched_column: Some("transaction_amount"),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            );
            offset_of_meta(line, entry)
        };
        for width in [20usize, 24, 30, 48] {
            assert_eq!(
                noted(&entry, width),
                noted(&short, width),
                "a matched row is drawn by its note, whatever its label would say, \
                 at {width}"
            );
            // And the note itself is cut to fit, not left to push the columns out.
            assert_eq!(
                noted(&short, width),
                meta_starts_at(&short, width),
                "a column note too long for the row is cut, at {width}"
            );
        }
    }

    /// A dot in a directory's name does not make it a file. A local row nothing has
    /// looked into came from a listing that saw a directory, so the name is not the
    /// evidence.
    /// Launched where there is nothing to open, the directory's heading says so and
    /// points at `~`, rather than a bare `0` above the public rows (#547 D9).
    #[test]
    fn an_empty_current_directory_says_so_and_points_at_the_path_prompt() {
        let ctx = RenderContext::for_test();
        let section = Section {
            door: None,
            title: "/home/me/empty".to_string(),
            subtitle: None,
            origin: Some(crate::home::RootOrigin::Cwd.note()),
            rows: Vec::new(),
            unavailable: false,
            unavailable_note: None,
            folded_by_default: false,
            remote_root: None,
            waiting: false,
            grouped_by_place: false,
            place_labels: Default::default(),
            root: None,
        };
        let text = |matches: usize, section: &Section| -> String {
            section_header(section, matches, false, false, &header_row(&ctx, 80))
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect()
        };
        let empty = text(0, &section);
        assert!(empty.contains("nothing to open here"), "{empty:?}");
        assert!(empty.contains("~ types a path"), "{empty:?}");
        assert!(!text(3, &section).contains("nothing to open"));
        let configured = Section {
            origin: Some("configured"),
            ..section
        };
        assert!(!text(0, &configured).contains("nothing to open"));
    }

    #[test]
    fn the_origin_chip_sits_by_the_count_and_the_state_by_the_rule() {
        let ctx = RenderContext::for_test();
        let section = Section {
            door: None,
            title: "/mnt/data".to_string(),
            subtitle: Some("nfs4".to_string()),
            origin: Some("configured"),
            rows: Vec::new(),
            unavailable: false,
            unavailable_note: None,
            folded_by_default: false,
            remote_root: None,
            waiting: false,
            grouped_by_place: false,
            place_labels: Default::default(),
            root: None,
        };
        let text = |width: usize| -> String {
            section_header(&section, 12, false, false, &header_row(&ctx, width))
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect()
        };
        let wide = text(80);
        let count = wide.find(" 12 ").expect("count chip");
        let origin = wide.find(" configured ").expect("origin chip");
        let state = wide.find("nfs4").expect("state note");
        assert!(count < origin && origin < state, "{wide:?}");
        assert_eq!(wide.chars().count(), 80);

        // At forty columns both chips and the note still fit beside the title.
        let narrow = text(40);
        assert_eq!(narrow.chars().count(), 40, "{narrow:?}");
        assert!(
            narrow.contains(" configured ") && narrow.contains("nfs4"),
            "{narrow:?}"
        );
        assert!(narrow.contains("/mnt/data"), "{narrow:?}");

        // Squeezed further: the title keeps at least three cells while the note and
        // then the chip give way, and once both are gone the whole title is back.
        for width in [30usize, 24, 16] {
            let tight = text(width);
            assert_eq!(tight.chars().count(), width, "{tight:?}");
            assert!(tight.contains("ta"), "{width}: {tight:?}");
        }
        let bare = text(20);
        assert!(bare.contains("/mnt/data"), "{bare:?}");
        assert!(
            !bare.contains("configured") && !bare.contains("nfs4"),
            "{bare:?}"
        );
    }

    /// A path longer than the line still leaves the rule a cell, so the cursor on the
    /// heading shows (#575).
    #[test]
    fn a_long_path_leaves_the_focused_heading_its_rule() {
        let ctx = RenderContext::for_test();
        let g = glyphs::get();
        let section = Section {
            door: None,
            title: format!("/var/folders/{}", "x".repeat(120)),
            subtitle: None,
            origin: Some("configured"),
            rows: Vec::new(),
            unavailable: false,
            unavailable_note: None,
            folded_by_default: false,
            remote_root: None,
            waiting: false,
            grouped_by_place: false,
            place_labels: Default::default(),
            root: None,
        };
        for width in [40usize, 80, 120] {
            let text: String = section_header(&section, 60, false, true, &header_row(&ctx, width))
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect();
            assert_eq!(text.chars().count(), width, "{text:?}");
            assert!(text.contains(g.rule_h_focused), "{width}: {text:?}");
        }
    }

    #[test]
    fn an_unmeasured_recent_from_a_store_shows_an_ellipsis_for_its_shape() {
        let ctx = RenderContext::for_test();
        let g = glyphs::get();
        let mut entry = row("s3://bucket/sales/", EntryKind::MultiFile);
        entry.cost.source = Some("s3".to_string());
        let text = |entry: &Entry, indent: usize| -> String {
            entry_line(
                entry,
                false,
                EntryNotes {
                    indent,
                    ..EntryNotes::default()
                },
                &rows(&ctx, 60, true, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
        };
        // Under a place, with nothing measured: the shape cell is an admission.
        let meta = meta_columns(&entry, true, None, None);
        assert!(text(&entry, NEST_INDENT).contains(&meta));
        assert!(meta.contains(g.ellipsis), "{meta:?}");
        // The same row in a directory listing, where the probe measures it, and a
        // local row, which is measured in place: blank, as before.
        assert!(!text(&entry, 0).contains(g.ellipsis));
        let mut local = row("/data/sales.csv", EntryKind::File);
        local.cost.source = Some("ext4".to_string());
        local.size = Some(10);
        assert!(!text(&local, NEST_INDENT).contains(g.ellipsis));
        // Once measured, the shape.
        entry.rows = Some(20);
        entry.cols = Some(3);
        assert!(!text(&entry, NEST_INDENT).contains(g.ellipsis));
    }

    #[test]
    fn a_place_row_carries_the_label_the_index_remembers_and_drops_it_before_the_path() {
        let ctx = RenderContext::for_test();
        let text = |label: Option<&str>, name_width: usize| -> String {
            place_line(
                std::path::Path::new("/mnt/data/sets/bitcoin"),
                label,
                Some("nfs4"),
                false,
                name_width,
                false,
                &ctx,
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
        };
        let wide = text(Some("2 parquet"), 60);
        assert!(wide.contains("bitcoin/  2 parquet"), "{wide:?}");
        assert!(wide.trim_end().ends_with("nfs4"), "{wide:?}");
        assert_eq!(wide.chars().count(), row_width(60, false));
        // No room for both: the path stays, the label goes.
        let tight = text(Some("2 parquet"), 22);
        assert!(!tight.contains("parquet"), "{tight:?}");
        assert!(tight.contains("bitcoin/"), "{tight:?}");
        assert_eq!(tight.chars().count(), row_width(22, false));
    }

    #[test]
    fn a_nested_row_keeps_the_meta_columns_where_the_place_row_ends() {
        // A row two cells in under a place must not push its meta columns two cells
        // to the right, or the column of shapes and sizes zigzags down RECENT. The
        // indent comes off the name's side, and the narrow-screen rule that gives a
        // label up for the name fires that much sooner.
        let ctx = RenderContext::for_test();
        let mut entry = row("/data/exports", EntryKind::MultiFile);
        entry.size = Some(4096);
        entry.rows = Some(12);
        // A shape too: a row with an empty shape cell gives it to the name (#648).
        entry.cols = Some(3);
        entry.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 5000)],
            truncated: true,
            ..Default::default()
        };
        let meta = meta_columns(&entry, false, None, None);
        let meta_at = |indent: usize, width: usize| -> usize {
            let line = entry_line(
                &entry,
                false,
                EntryNotes {
                    indent,
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, ""),
            );
            let at = line
                .spans
                .iter()
                .position(|s| s.content == meta)
                .expect("the meta columns are drawn");
            line.spans[..at]
                .iter()
                .map(|s| s.content.chars().count())
                .sum()
        };
        for width in [24usize, 30, 48, 100] {
            assert_eq!(
                meta_at(NEST_INDENT, width),
                meta_at(0, width),
                "at {width} the indented row's meta columns start where a plain row's do"
            );
        }
        // And the place row above it ends where the entry row ends, so its right-hand
        // cell sits on the edge the age column sits on. `row_width` names the entry
        // row's width rather than measuring it, and this is what keeps the two honest.
        assert_eq!(meta.chars().count(), META_COLUMNS_WIDTH);
        let drawn = |line: Line<'_>| -> usize {
            line.spans.iter().map(|s| s.content.chars().count()).sum()
        };
        // With the meta columns shown, which is when there is an edge to share. Without
        // them an entry row stops after its label, and the place row fills its width
        // alone so the selection tint reaches the edge.
        for name_width in [60usize, 24] {
            let entry_width = drawn(entry_line(
                &entry,
                false,
                EntryNotes {
                    indent: NEST_INDENT,
                    ..EntryNotes::default()
                },
                &rows(&ctx, name_width, true, ""),
            ));
            assert_eq!(entry_width, row_width(name_width, true));
            let place = place_line(
                std::path::Path::new("/data"),
                None,
                Some("nfs4"),
                false,
                name_width,
                true,
                &ctx,
            );
            assert_eq!(drawn(place), entry_width, "{name_width}");
            let more = more_line(3, 2, false, name_width, true, &ctx);
            assert_eq!(drawn(more), entry_width, "{name_width}");
        }
    }

    #[test]
    fn a_place_row_names_only_a_filesystem_worth_naming() {
        // A local disk is the overwhelming majority of places, and `ext4` beside
        // every one would be texture. A share or a store is worth a word, in the
        // color the rows' own glyph uses for it.
        let ctx = RenderContext::for_test();
        let text = |source: Option<&str>| -> String {
            place_line(
                std::path::Path::new("/data/x"),
                None,
                source,
                false,
                40,
                false,
                &ctx,
            )
            .spans
            .iter()
            .map(|s| s.content.to_string())
            .collect::<String>()
        };
        assert!(
            text(Some("ext4")).trim_end().ends_with("/data/x/"),
            "{:?}",
            text(Some("ext4"))
        );
        assert!(
            text(Some("nfs4")).trim_end().ends_with("nfs4"),
            "{:?}",
            text(Some("nfs4"))
        );
        assert!(
            text(Some("s3")).trim_end().ends_with("s3"),
            "{:?}",
            text(Some("s3"))
        );
        assert!(
            text(None).trim_end().ends_with("/data/x/"),
            "{:?}",
            text(None)
        );
        // A long path keeps its tail, which is the part that says where it is.
        let long = place_line(
            std::path::Path::new("/very/deeply/nested/place/on/a/share/somewhere/far"),
            None,
            Some("nfs4"),
            false,
            27,
            false,
            &ctx,
        );
        let drawn: String = long.spans.iter().map(|s| s.content.to_string()).collect();
        assert_eq!(drawn.chars().count(), row_width(27, false), "{drawn:?}");
        assert!(drawn.contains("far/"), "{drawn:?}");
    }

    #[test]
    fn the_more_row_counts_rows_and_places() {
        let ctx = RenderContext::for_test();
        let text = |hidden: usize, places: usize| -> String {
            more_line(hidden, places, false, 40, false, &ctx)
                .spans
                .iter()
                .map(|s| s.content.to_string())
                .collect::<String>()
                .trim_end()
                .to_string()
        };
        let g = glyphs::get();
        assert_eq!(
            text(13, 5),
            format!("{}{} 13 more in 5 places", g.selector_blank, g.ellipsis)
        );
        assert_eq!(
            text(1, 1),
            format!("{}{} 1 more in 1 place", g.selector_blank, g.ellipsis)
        );
    }

    #[test]
    fn a_local_directory_keeps_its_slash_however_its_name_is_spelled() {
        for name in ["project.old", "v1.2", "site.com", "datui.git", "plain"] {
            let entry = row(&format!("/home/derek/{name}"), EntryKind::Unknown);
            assert!(
                shows_as_a_place(&entry),
                "{name} is a directory the listing saw"
            );
        }
    }

    /// Remote, the name is all there is. One with an extension is a file even when it
    /// is one datui does not read, and one without is a prefix.
    #[test]
    fn a_remote_row_is_read_as_a_prefix_only_when_its_name_is_not_a_file() {
        // A path on a network mount takes the same branch, but whether one *is* a
        // network mount is a question about this machine's mount table, so the two
        // URL schemes are what a test can say.
        for prefix in ["s3://bucket", "https://host"] {
            for name in ["export.txt", "part-00000.parquet", "notes.md"] {
                assert!(
                    !shows_as_a_place(&row(&format!("{prefix}/{name}"), EntryKind::Unknown)),
                    "{prefix}/{name} is named like a file"
                );
            }
        }
        for prefix in ["s3://bucket", "https://host"] {
            for name in ["exports", "2024", "raw"] {
                assert!(
                    shows_as_a_place(&row(&format!("{prefix}/{name}"), EntryKind::Unknown)),
                    "{prefix}/{name} is a prefix"
                );
            }
        }
    }

    fn header_width(section: &Section, width: usize) -> usize {
        let ctx = RenderContext::for_test();
        let line = section_header(section, 3, false, false, &header_row(&ctx, width));
        line.spans.iter().map(|s| s.content.chars().count()).sum()
    }

    #[test]
    fn a_long_note_never_pushes_the_header_past_the_screen() {
        // A search heading carries the path it searched, which is easily longer than
        // the terminal. The note is context; the title is what the section is.
        let section = Section {
            door: None,
            title: "Found".to_string(),
            subtitle: Some(
                "/very/deeply/nested/path/that/goes/on/and/on/for/quite/a/while · 99999 searched"
                    .to_string(),
            ),
            origin: None,
            rows: Vec::new(),
            unavailable: false,
            unavailable_note: None,
            folded_by_default: false,
            remote_root: None,
            waiting: false,
            grouped_by_place: false,
            place_labels: Default::default(),
            root: None,
        };

        for width in [20usize, 40, 80, 120] {
            let rendered = header_width(&section, width);
            assert!(
                rendered <= width,
                "a {width}-wide screen produced a {rendered}-character header"
            );
        }
    }

    #[test]
    fn a_recent_from_a_source_names_it_or_says_it_is_gone() {
        let ctx = RenderContext::for_test();
        let path = std::path::Path::new("s3://lab@data/sales.parquet");
        let mut entry = Entry::for_test(path, "sales.parquet");
        entry.kind = EntryKind::Unknown;
        let text = |known: Option<&[String]>| -> String {
            entry_line(
                &entry,
                false,
                EntryNotes {
                    known_sources: known,
                    ..EntryNotes::default()
                },
                &rows(&ctx, 80, false, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.to_string())
            .collect()
        };
        let lab = ["lab".to_string()];
        assert!(text(Some(&lab)).contains("sales.parquet  lab"));
        assert!(text(Some(&[])).contains("source not found: lab"));
        // Inside a source the trail already says which, so nothing is added.
        assert!(!text(None).contains("lab"));
    }

    /// Where the meta columns begin, in cells. Everything left of them is the name
    /// half of the row, and it is one width for every row on screen or the columns are
    /// not columns.
    fn meta_offset(line: &Line) -> usize {
        // The meta text is second from the end; the last span carries the tint to the
        // edge.
        let spans = &line.spans[..line.spans.len().saturating_sub(2)];
        spans
            .iter()
            .map(|s| unicode_width::UnicodeWidthStr::width(s.content.as_ref()))
            .sum()
    }

    #[test]
    fn the_pane_does_not_say_what_a_directory_holds_twice() {
        let mut entry = Entry::for_test(std::path::Path::new("/data/consolidated"), "consolidated");
        entry.kind = EntryKind::Directory;
        // A directory of one format and nothing else: the label and the line are the same
        // words, and `kind  12 parquet` above `holds  12 parquet` says it twice.
        entry.holds = crate::discover::Holds {
            formats: vec![("parquet".to_string(), 12)],
            ..Default::default()
        };
        let text = preview_text(&entry, 60);
        assert!(text.contains("12 parquet"), "{text}");
        assert_eq!(
            text.matches("12 parquet").count(),
            1,
            "the label and the line are the same words: {text}"
        );

        // With anything else beside them the line carries that too.
        entry.holds.directories = 3;
        let text = preview_text(&entry, 60);
        assert!(text.contains("contains"), "{text}");
        assert!(text.contains("3 directories"), "{text}");

        // Files datui cannot open are not counted here: inside, a row says so.
        entry.holds = crate::discover::Holds {
            not_read: 10,
            ..Default::default()
        };
        let text = preview_text(&entry, 60);
        assert!(!text.contains("10"), "{text}");
        assert!(text.contains("no data files"), "{text}");
    }

    #[test]
    fn no_mark_ever_lands_on_a_cut_notes_ellipsis() {
        // The note says why a row is in the list, and the marks say which letters
        // matched. The ellipsis standing for the rest of the note matched nothing, so a
        // mark on it is the row claiming a hit it does not have. `kept` counts the
        // note's own characters and the marks stop there — this is what says so, since
        // the comparison between the two rows below cannot see a change that moves
        // both of them.
        let ctx = RenderContext::for_test();
        let entry = Entry::for_test(std::path::Path::new("/tmp/x"), "x");
        let g = glyphs::get();
        for width in 1..=40usize {
            let line = entry_line(
                &entry,
                false,
                EntryNotes {
                    matched_column: Some("transaction_amount_usd"),
                    known_sources: Some(&[]),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, false, "usd"),
            );
            let marked: String = line
                .spans
                .iter()
                .filter(|s| s.style.add_modifier.contains(Modifier::UNDERLINED))
                .map(|s| s.content.to_string())
                .collect();
            assert!(
                !marked.contains(g.ellipsis),
                "at {width} cells a mark landed on the cut note's ellipsis: {marked:?}"
            );
            // And a note cut down to nothing but the ellipsis is not a note. Where
            // there is no room for a letter beside it the whole note stays and the name
            // gives way instead, the same reasoning that keeps `dataset` from becoming
            // `d…t`.
            let sep = format!(" {}", g.middot);
            let note: String = line
                .spans
                .iter()
                .skip_while(|s| s.content != sep)
                .skip(1)
                .map(|s| s.content.to_string())
                .collect();
            assert_ne!(
                note.trim_end(),
                g.ellipsis,
                "at {width} cells the note was cut down to an ellipsis and said nothing"
            );
            // A note that fits is not cut. The cut one is always shorter than the
            // whole, so a drawn note as long as the column can only be the column
            // itself — which is what catches a boundary set one cell the wrong way,
            // where the ellipsis replaces the last letter and changes nothing else.
            let note = note.trim_end();
            if note.chars().count() >= "transaction_amount_usd".chars().count() {
                assert_eq!(
                    note, "transaction_amount_usd",
                    "at {width} cells a note that fitted was cut anyway"
                );
            }
        }
    }

    #[test]
    fn a_column_note_on_a_row_from_a_source_leaves_the_meta_columns_alone() {
        let ctx = RenderContext::for_test();
        let known = ["prod".to_string()];
        // The same row in every way but the source id, so the only thing that can
        // move the meta columns is the cell the id goes in.
        let mut plain = Entry::for_test(
            std::path::Path::new("s3://bucket/sales.parquet"),
            "sales.parquet",
        );
        plain.kind = EntryKind::Unknown;
        let mut sourced = Entry::for_test(
            std::path::Path::new("s3://prod@bucket/sales.parquet"),
            "sales.parquet",
        );
        sourced.kind = EntryKind::Unknown;

        // Two cells hold this row's note: the source id, which is as long as somebody's
        // configuration and so is cut when it stops fitting, and the column that put
        // the row in the list. Only one of them is drawn. Cutting the other moved the
        // meta columns of this row and no other — the columns coming unstuck on the one
        // row a search was about.
        for width in 6..=30usize {
            let with_note = entry_line(
                &sourced,
                false,
                EntryNotes {
                    matched_column: Some("customer_identifier"),
                    known_sources: Some(&known),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, "cust"),
            );
            let without = entry_line(
                &plain,
                false,
                EntryNotes {
                    matched_column: Some("customer_identifier"),
                    known_sources: Some(&[]),
                    ..EntryNotes::default()
                },
                &rows(&ctx, width, true, "cust"),
            );
            assert_eq!(
                meta_offset(&with_note),
                meta_offset(&without),
                "at {width} cells the source id moved the meta columns"
            );
        }
    }

    /// The row's spans, as (text, is_highlighted) pairs.
    fn row_spans(name: &str, filter: &str, column: Option<&str>) -> Vec<(String, bool)> {
        let ctx = RenderContext::for_test();
        let entry = Entry::for_test(std::path::Path::new("/tmp/x"), name);
        let line = entry_line(
            &entry,
            false,
            EntryNotes {
                matched_column: column,
                known_sources: Some(&[]),
                ..EntryNotes::default()
            },
            &rows(&ctx, 60, false, filter),
        );
        line.spans
            .iter()
            .skip(1) // the selection marker
            .map(|s| {
                (
                    s.content.to_string(),
                    s.style.add_modifier.contains(Modifier::UNDERLINED),
                )
            })
            .collect()
    }

    fn highlighted_text(spans: &[(String, bool)]) -> String {
        spans
            .iter()
            .filter(|(_, hit)| *hit)
            .map(|(t, _)| t.as_str())
            .collect()
    }

    fn preview_text(entry: &Entry, width: usize) -> String {
        let ctx = RenderContext::for_test();
        preview_head(entry, None, None, width, &ctx)
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn costed(name: &str, cost: crate::discover::Cost, size: Option<u64>) -> Entry {
        let mut e = Entry::for_test(std::path::Path::new("/tmp/x"), name);
        e.size = size;
        e.cost = cost;
        e
    }

    /// A file of tables says how many it contains; a spec's file does not, whose
    /// variants are record types its `records` line counts.
    #[test]
    fn only_a_file_of_real_tables_contains_tables() {
        let db = costed(
            "shop.db",
            crate::discover::Cost {
                tables: Some(3),
                ..Default::default()
            },
            None,
        );
        let shown = preview_text(&db, 60);
        assert!(
            shown
                .lines()
                .any(|l| l.starts_with("contains") && l.ends_with(" 3 tables")),
            "{shown}"
        );
        let mut spec_file = costed(
            "day.ord",
            crate::discover::Cost {
                tables: Some(5),
                ..Default::default()
            },
            None,
        );
        spec_file.format_spec = Some("acme.orders".into());
        let shown = preview_text(&spec_file, 60);
        assert!(!shown.contains("tables"), "{shown}");
        assert!(shown.contains("acme.orders file"), "{shown}");
    }

    #[test]
    fn a_network_source_is_named_rather_than_described() {
        // The filesystem's own name and nothing else. A sentence explaining that a
        // network is a network is a sentence to skip on every row.
        let e = costed(
            "prices.parquet",
            crate::discover::Cost {
                source: Some("nfs4".into()),
                ..Default::default()
            },
            None,
        );
        let text = preview_text(&e, 44);
        assert!(text.contains("nfs4"), "{text}");
    }

    #[test]
    fn local_disk_gets_no_warning() {
        let e = costed(
            "prices.parquet",
            crate::discover::Cost {
                source: Some("ext4".into()),
                ..Default::default()
            },
            None,
        );
        let text = preview_text(&e, 44);
        assert!(text.contains("ext4"), "{text}");
        assert!(
            !text.contains("network"),
            "an ordinary disk should say nothing alarming: {text}"
        );
    }

    #[test]
    fn what_a_file_weighs_open_is_stated_with_its_ratio() {
        // The number nothing else on screen implies.
        let e = costed(
            "prices.parquet",
            crate::discover::Cost {
                source: Some("ext4".into()),
                uncompressed: Some(2_000_000_000),
                codec: Some("zstd".into()),
                row_groups: Some(12),
                ..Default::default()
            },
            Some(200_000_000),
        );
        let text = preview_text(&e, 44);
        assert!(text.contains("in memory"), "{text}");
        assert!(text.contains("zstd"), "{text}");
        assert!(text.contains("10.0"), "the ratio should be stated: {text}");
        assert!(text.contains("row groups"), "{text}");
    }

    #[test]
    fn a_ratio_too_small_to_matter_is_left_out() {
        // Below about 1.2x the number is noise dressed as insight.
        let e = costed(
            "prices.parquet",
            crate::discover::Cost {
                source: Some("ext4".into()),
                uncompressed: Some(1_050_000),
                codec: Some("uncompressed".into()),
                ..Default::default()
            },
            Some(1_000_000),
        );
        let text = preview_text(&e, 44);
        assert!(!text.contains("1.0×") && !text.contains("1.1×"), "{text}");
    }

    #[test]
    fn a_partition_layout_names_its_keys_and_its_range() {
        let e = costed(
            "events",
            crate::discover::Cost {
                source: Some("nfs4".into()),
                partitions: Some(crate::discover::Partitions {
                    keys: vec!["year".into(), "region".into()],
                    first_key_values: vec!["2023".into(), "2024".into(), "2025".into()],
                    count: 3,
                    more: false,
                }),
                ..Default::default()
            },
            None,
        );
        let text = preview_text(&e, 44);
        assert!(text.contains("3 by year, region"), "{text}");
        assert!(text.contains("year 2023 to 2025"), "{text}");
    }

    #[test]
    fn a_bounded_partition_count_says_it_is_a_floor() {
        let e = costed(
            "daily",
            crate::discover::Cost {
                partitions: Some(crate::discover::Partitions {
                    keys: vec!["day".into()],
                    first_key_values: vec!["0001".into()],
                    count: 512,
                    more: true,
                }),
                ..Default::default()
            },
            None,
        );
        assert!(preview_text(&e, 44).contains("512+"));
    }

    #[test]
    fn the_preview_never_draws_past_its_pane() {
        let e = costed(
            "a_dataset_with_a_very_long_name_indeed.parquet",
            crate::discover::Cost {
                source: Some("fuse.sshfs".into()),
                uncompressed: Some(9_000_000_000),
                codec: Some("zstd".into()),
                row_groups: Some(1024),
                partitions: Some(crate::discover::Partitions {
                    keys: vec!["year".into(), "month".into(), "day".into()],
                    first_key_values: vec!["2001".into(), "2025".into()],
                    count: 9999,
                    more: true,
                }),
                tables: None,
                opens_one: false,
                ipc_stream: false,
            },
            Some(400_000_000),
        );
        for width in [24usize, 40, 80] {
            let ctx = RenderContext::for_test();
            for line in preview_head(&e, None, None, width, &ctx) {
                // The pane wraps rather than clips, so a long value is allowed to run
                // on; what must not happen is a *heading* bar overrunning its width.
                let text: String = l_text(&line);
                if text.trim_start().starts_with("OPENING") {
                    assert!(
                        text.chars().count() <= width,
                        "a {width}-wide pane drew a {}-character heading",
                        text.chars().count()
                    );
                }
            }
        }
    }

    fn l_text(line: &Line<'_>) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn the_matched_characters_are_the_highlighted_ones() {
        let spans = row_spans("sales_2024.parquet", "sales", None);
        assert_eq!(highlighted_text(&spans), "sales");
        // Reassembling the spans must give back exactly the name; highlighting is a
        // change of style, never of text. The locality marker sits between the
        // selection marker and the name, so the name is what follows it rather than
        // what the row starts with.
        let text: String = spans.iter().map(|(t, _)| t.as_str()).collect();
        assert!(text.contains("sales_2024.parquet"), "got {text:?}");
    }

    #[test]
    fn a_scattered_match_highlights_each_run_separately() {
        let spans = row_spans("sales_by_region.parquet", "sreg", None);
        assert_eq!(highlighted_text(&spans), "sreg");
        let runs = spans.iter().filter(|(_, hit)| *hit).count();
        assert!(
            runs >= 2,
            "a match spread across the name should be several runs, got {runs}"
        );
    }

    #[test]
    fn consecutive_matches_become_one_span_not_a_stutter() {
        let spans = row_spans("sales.parquet", "sales", None);
        let runs = spans.iter().filter(|(_, hit)| *hit).count();
        assert_eq!(runs, 1, "five adjacent characters are one run, got {runs}");
    }

    #[test]
    fn nothing_is_highlighted_without_a_filter() {
        let spans = row_spans("sales.parquet", "", None);
        assert_eq!(highlighted_text(&spans), "");
    }

    #[test]
    fn a_row_matched_by_a_column_highlights_the_column_not_the_name() {
        // Marks scattered over a name that had nothing to do with the match read as
        // the filter having gone wrong.
        let spans = row_spans("orders.parquet", "cust", Some("customer_id"));
        assert_eq!(highlighted_text(&spans), "cust");
        let text: String = spans.iter().map(|(t, _)| t.as_str()).collect();
        let note = format!("{}customer_id", glyphs::get().middot);
        assert!(
            text.contains(&note),
            "the column note should still read whole, got {text:?}"
        );
    }

    #[test]
    fn the_title_survives_a_note_that_wants_the_whole_line() {
        // Trimming the note first is the point: a header that says only where it
        // looked, and not what it is, has lost the more useful half.
        let section = Section {
            door: None,
            title: "Found".to_string(),
            subtitle: Some("x".repeat(200)),
            origin: None,
            rows: Vec::new(),
            unavailable: false,
            unavailable_note: None,
            folded_by_default: false,
            remote_root: None,
            waiting: false,
            grouped_by_place: false,
            place_labels: Default::default(),
            root: None,
        };
        let ctx = RenderContext::for_test();
        let line = section_header(&section, 3, false, false, &header_row(&ctx, 40));
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            text.contains("FOUND"),
            "the title should still be readable, got {text:?}"
        );
    }

    /// At 80 columns the open-all row keeps what it opens and cuts the directory's
    /// name, which the section title above it already carries; at 200 it is whole.
    #[test]
    fn the_door_keeps_what_it_opens_when_its_name_is_cut() {
        let ctx = RenderContext::for_test();
        let mut door = row("/data/same_schema/", EntryKind::MultiFile);
        door.name = "same_schema (3 Parquet files, one schema)".to_string();
        door.opens_whole_directory = true;
        door.rows = Some(6);
        door.cols = Some(2);
        let drawn = |width: usize| -> String {
            entry_line(
                &door,
                true,
                EntryNotes::default(),
                &rows(&ctx, width.saturating_sub(META_WIDTH as usize), true, ""),
            )
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
        };
        // An 80-column terminal leaves the list 78.
        let narrow = drawn(78);
        assert!(
            narrow.contains("(3 Parquet files, one schema)"),
            "{narrow:?}"
        );
        assert!(!narrow.contains("same_schema ("), "{narrow:?}");
        assert!(
            narrow.contains("6 × 2") || narrow.contains("6 x 2"),
            "{narrow:?}"
        );
        assert_eq!(
            narrow.chars().count(),
            row_width(78 - META_WIDTH as usize, true),
            "the columns stay where they are: {narrow:?}"
        );
        // At 60 the directory goes and what Enter opens keeps its head.
        let narrowest = drawn(58);
        assert!(narrowest.contains("(3 Parquet files"), "{narrowest:?}");
        assert!(!narrowest.contains("same_"), "{narrowest:?}");
        assert_eq!(
            narrowest.chars().count(),
            row_width(58 - META_WIDTH as usize, true),
            "{narrowest:?}"
        );
        let wide = drawn(200);
        assert!(
            wide.contains("same_schema (3 Parquet files, one schema)"),
            "{wide:?}"
        );
    }

    fn texts(lines: &[Line]) -> Vec<String> {
        lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// A path too long for the pane loses its middle, between components, and keeps its
    /// file name; one that fits is left alone.
    #[test]
    fn a_long_path_is_cut_in_the_middle_not_wrapped() {
        let e = glyphs::get().ellipsis;
        let path = "~/.config/datui/formats/demo-mktdata.toml";
        assert_eq!(elide_path(path, 60), path);
        assert_eq!(
            elide_path(path, 30),
            format!("~/{e}/formats/demo-mktdata.toml")
        );
        assert!(elide_path(path, 30).chars().count() <= 30);
        assert_eq!(elide_path(path, 22), format!("~/{e}/demo-mktdata.toml"));
        assert_eq!(
            elide_path("/a/b/c/long-name.toml", 17),
            format!("/{e}/long-name.toml")
        );
        // Only the name's end fits.
        let cut = elide_path(path, 10);
        assert!(cut.ends_with("ta.toml"), "{cut}");
        assert!(glyphs::display_width(&cut) <= 10, "{cut}");
    }

    /// Windows' `\` separates components too, and is kept where the path has it.
    #[cfg(windows)]
    #[test]
    fn a_windows_path_is_cut_at_its_backslashes() {
        let e = glyphs::get().ellipsis;
        let path = r"~\.config\datui\formats\demo-mktdata.toml";
        assert_eq!(
            elide_path(path, 30),
            format!(r"~\{e}\formats\demo-mktdata.toml")
        );
    }

    fn spec_chips() -> Vec<MatchChip> {
        let spec = crate::formats::Spec::parse(
            r#"name = "acme.chips"
match = { glob = ["*.bin", "*.dat"], magic = "MKTD", where = { "header.version" = 1, "header.kind" = "A" } }
[header]
fields = [
  { name = "magic", type = "str", size = 4 },
  { name = "version", type = "u2" },
  { name = "kind", type = "str", size = 1 },
]
[records]
fields = [{ name = "x", type = "u1" }]
"#,
            None,
        )
        .unwrap();
        spec.match_chips()
    }

    /// The match line wraps between chips, never inside one, at any width; on the
    /// chrome tier where the tint shows, bracketed with text quoted where it does not.
    #[test]
    fn match_chips_wrap_between_whole_chips() {
        let ctx = RenderContext::for_test();
        let chips = spec_chips();
        for filled in [true, false] {
            for width in [24, 30, 40, 80] {
                let lines = chip_fact_lines("match", &chips, 5, width, filled, &ctx);
                let shown = texts(&lines);
                for line in &shown {
                    assert!(
                        glyphs::display_width(line) <= width,
                        "{line:?} wider than {width}"
                    );
                }
                let kind = if filled { "kind A" } else { "kind \"A\"" };
                let whole: &[&str] = if width < 30 {
                    &[]
                } else {
                    &["magic MKTD", "version 1", kind, "glob *.bin *.dat"]
                };
                for chip in whole {
                    assert!(
                        shown.iter().any(|l| l.contains(chip)),
                        "{chip:?} whole on one line at {width}: {shown:#?}"
                    );
                }
                assert!(shown[0].starts_with("match  "), "{shown:?}");
                assert!(
                    shown[1..].iter().all(|l| l.starts_with("       ")),
                    "wrapped under the value: {shown:#?}"
                );
            }
        }
        let wide = texts(&chip_fact_lines("match", &chips, 5, 80, false, &ctx));
        assert_eq!(
            wide,
            ["match  [magic MKTD] [kind \"A\"] [version 1] [glob *.bin *.dat]"]
        );
        let wide = chip_fact_lines("match", &chips, 5, 80, true, &ctx);
        let magic = &wide[0].spans[1..6];
        assert!(
            magic
                .iter()
                .all(|s| s.style.bg == Some(ctx.table_header_bg)),
            "{magic:?}"
        );
        assert_eq!(magic[1].style.fg, Some(ctx.dimmed));
        assert_eq!(magic[3].style.fg, Some(ctx.str_col));
        let one = wide[0]
            .spans
            .iter()
            .find(|s| s.content == "1")
            .expect("the version");
        assert_eq!(one.style.fg, Some(ctx.int_col), "{wide:?}");
    }

    #[test]
    fn a_spec_without_a_match_says_so() {
        let ctx = RenderContext::for_test();
        let lines = chip_fact_lines("match", &[], 5, 40, true, &ctx);
        assert_eq!(texts(&lines), ["match  no match"]);
    }

    /// A field name too long for the line is cut, not the value, and the chip stays on
    /// its line whole: never past the pane, never broken in two.
    #[test]
    fn a_long_field_name_is_cut_before_its_value() {
        use crate::formats::ChipKind;
        let ctx = RenderContext::for_test();
        let e = glyphs::get().ellipsis;
        let chips = [
            MatchChip {
                name: "magic".to_string(),
                value: "MKTD".to_string(),
                kind: ChipKind::Magic,
                offset: None,
            },
            MatchChip {
                name: "exchange_feed_sequence_version".to_string(),
                value: "3".to_string(),
                kind: ChipKind::Int,
                offset: None,
            },
        ];
        for filled in [true, false] {
            let shown = texts(&chip_fact_lines("match", &chips, 8, 40, filled, &ctx));
            assert_eq!(shown.len(), 2, "{shown:#?}");
            for line in &shown {
                assert!(glyphs::display_width(line) <= 40, "{line:?}");
            }
            let long = &shown[1];
            assert!(long.starts_with("          "), "{shown:#?}");
            let chip = long.trim();
            let (open, close) = if filled { ("", "") } else { ("[", "]") };
            assert!(
                chip.starts_with(&format!("{open}exchange_feed")),
                "{chip:?}"
            );
            assert!(chip.ends_with(&format!("{e} 3{close}")), "{chip:?}");
        }
        // A long value with a short name still cuts the value.
        let glob = MatchChip {
            name: "glob".to_string(),
            value: "*.alpha *.bravo *.charlie *.delta *.echo".to_string(),
            kind: ChipKind::Glob,
            offset: None,
        };
        let shown = texts(&chip_fact_lines("match", &[glob], 5, 30, false, &ctx));
        assert_eq!(shown.len(), 1, "{shown:#?}");
        assert!(shown[0].starts_with("match  [glob *.alpha"), "{shown:#?}");
        assert!(shown[0].ends_with(&format!("{e}]")), "{shown:#?}");
        assert_eq!(glyphs::display_width(&shown[0]), 30, "{shown:#?}");
    }

    /// Variants pack under the value column, `name count` each, a line breaking only
    /// between them, counted when the rows run out.
    #[test]
    fn variants_pack_densely_and_break_between_items() {
        let ctx = RenderContext::for_test();
        let table = |name: &str, n: usize| crate::members::Table {
            name: name.to_string(),
            kind: "record type".to_string(),
            internal: false,
            columns: (0..n).map(|i| (format!("c{i}"), String::new())).collect(),
        };
        let variants = [
            table("Status", 6),
            table("OrderAdd", 9),
            table("OrderCancel", 6),
            table("Trade", 9),
            table("Fill", 9),
        ];
        let m = glyphs::get().middot;
        let wide = texts(&variant_lines(&variants, 8, 80, 10, &ctx));
        assert_eq!(
            wide,
            [format!(
                "        Status 6 {m} OrderAdd 9 {m} OrderCancel 6 {m} Trade 9 {m} Fill 9"
            )]
        );
        let narrow = texts(&variant_lines(&variants, 8, 40, 10, &ctx));
        assert!(narrow.len() > 1, "{narrow:#?}");
        for line in &narrow {
            assert!(glyphs::display_width(line) <= 40, "{line:?}");
            assert!(!line.trim_end().ends_with(m), "{line:?}");
        }
        for item in [
            "Status 6",
            "OrderAdd 9",
            "OrderCancel 6",
            "Trade 9",
            "Fill 9",
        ] {
            assert!(
                narrow.iter().any(|l| l.contains(item)),
                "{item}: {narrow:#?}"
            );
        }
        let cut = texts(&variant_lines(&variants, 8, 30, 2, &ctx));
        assert_eq!(cut.len(), 2, "{cut:#?}");
        assert!(cut[1].trim_start().ends_with("more"), "{cut:#?}");
    }

    /// Every pane heading reads the same way: a noun on the rule, and any count
    /// in a flat chip after it, as the list's sections carry theirs.
    #[test]
    fn pane_headings_put_counts_in_a_chip() {
        let ctx = RenderContext::for_test();
        let text = |line: &Line| {
            line.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
        };
        let rows = rows_heading(5, 20, 40, &ctx);
        assert!(
            text(&rows).starts_with("ROWS  5 of 20 columns  "),
            "{:?}",
            text(&rows)
        );
        let chip = rows
            .spans
            .iter()
            .find(|s| s.content.contains("5 of 20"))
            .unwrap();
        assert_eq!(chip.style.bg, Some(ctx.controls_bg));
        assert!(text(&rows_heading(5, 5, 40, &ctx)).starts_with("ROWS "));
        let columns = pane_heading_counted("COLUMNS", Some("1,200"), 40, &ctx);
        assert!(
            text(&columns).starts_with("COLUMNS  1,200  "),
            "{:?}",
            text(&columns)
        );
        assert_eq!(
            text(&columns).chars().count(),
            39,
            "as wide as a heading without one"
        );
    }

    /// The pane's column notes sit under COLUMNS, a line each, with no key hint among
    /// them (the footer has `^E Docs`); cut to the pane, the rest are counted.
    #[test]
    fn column_notes_are_listed_under_columns_and_counted_when_cut() {
        let ctx = RenderContext::for_test();
        let columns: Vec<(String, crate::catalog::ColumnNote)> = (0..6)
            .map(|i| {
                let note = crate::catalog::ColumnNote {
                    description: format!("Note {i}"),
                    unit: if i == 0 { "USD".into() } else { String::new() },
                    values: Vec::new(),
                    ty: String::new(),
                };
                (format!("col{i}"), note)
            })
            .collect();
        let whole = texts(&column_notes_block(&columns, 50, 20, &ctx));
        assert!(whole[1].starts_with("COLUMNS "), "{whole:#?}");
        assert_eq!(whole.len(), 2 + 6, "{whole:#?}");
        assert!(whole[2].contains("col0") && whole[2].contains("Note 0 (USD)"));
        assert!(!whole.iter().any(|l| l.contains("^E")), "{whole:#?}");

        let cut = texts(&column_notes_block(&columns, 50, 6, &ctx));
        assert_eq!(cut.len(), 6, "{cut:#?}");
        let more = format!("{} 3 more", glyphs::get().ellipsis);
        assert_eq!(cut.last(), Some(&more), "{cut:#?}");
        assert!(!cut.iter().any(|l| l.contains("^E")), "{cut:#?}");
    }
}