repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! The help overlay [keybindings.md](../../../../docs/spec/keybindings.md#the-help-overlay)
//! describes: generated from the same table as the footer, current context first then
//! `global`, then a glyph legend, scrolling, and closing on `Esc` or `q`. Content comes
//! straight from [`BindingTable::describe_own`], [`BindingTable::describe_global`] and
//! [`GlyphSet::row_interior`]; nothing here is transcribed.
//!
//! Two modes, both dispatched through `Context::Overlay`
//! ([keybindings.md](../../../../docs/spec/keybindings.md#the-help-overlay)): reading, the
//! overlay's own original shape (`q`/`Esc` close it, `j`/`k`/`g`/`G`/`Ctrl+D`/`Ctrl+U`
//! scroll, nothing filtered unless a prior search left a query committed), and searching,
//! entered with `/` (`Action::Search`), where a query line renders and narrows both the
//! binding list and the legend as it is typed. `Esc` in search mode leaves it and clears
//! the query; `Enter` leaves it and keeps the query applied. [`crate::app::App`] is what
//! tells the two apart on a keystroke; this module only holds [`HelpOverlay`]'s own state
//! and renders whichever mode it is in.
//!
//! The overlay's own chrome (border, title, the fixed key gutter, the degrade threshold, the
//! three sections' own headings, the query line's own edge, the version on the bottom
//! border) is a presentation decision this crate makes rather than one
//! [keybindings.md](../../../../docs/spec/keybindings.md#the-help-overlay) fixes; the choice
//! is recorded there under "The help overlay's own chrome". Help stays full-frame: it is a
//! reading surface, not a chooser, so the popup treatment [0008](../../../../docs/adr/0008-two-palettes-not-one.md)
//! reserves for the palettes does not apply here.

use ratatui::{
    Frame,
    buffer::Buffer,
    layout::Rect,
    style::{Modifier, Style},
    text::Line,
};

use crate::edit_buffer::EditBuffer;
use crate::glyphs::{BorderScratch, GlyphSet, Meaning, bordered_interior};
use crate::keys::{Action, BindingTable, Context};
use crate::scroll::scroll_after;
use crate::theme::{Role, Theme};

/// Columns/rows the bordered box's own border consumes, matching `components/detail.rs`'s
/// own `BORDER_WIDTH`: one column of `│`/row of `─` on each side.
const BORDER_WIDTH: u16 = 2;
const BORDER_HEIGHT: u16 = 2;

/// The frame must hold the border plus at least one row/column of content, or a bordered box
/// would draw a border with nothing inside it (or clip the border itself). One row/column is
/// the least "any content" can mean; below it there is nothing to inset a border around.
const MIN_CONTENT_WIDTH: u16 = 1;
const MIN_CONTENT_HEIGHT: u16 = 1;
const MIN_BORDERED_WIDTH: u16 = BORDER_WIDTH + MIN_CONTENT_WIDTH;
const MIN_BORDERED_HEIGHT: u16 = BORDER_HEIGHT + MIN_CONTENT_HEIGHT;

/// The gap between the two columns when [`ColumnMetrics::two_columns`] holds: wider than the
/// two-space key/description gutter every line already carries, so a column boundary reads
/// as its own break rather than blending into another wrapped line.
const COLUMN_GUTTER: u16 = 4;

/// The title the overlay draws into its own top border, recorded in keybindings.md's "The
/// help overlay's own chrome" and named once here so no reader of it holds a second copy.
pub(crate) const BORDER_TITLE: &str = " help (esc or q closes) ";

/// `repon <version>`, right-aligned on the panel's own bottom border: the one place this
/// crate's own build version reaches the screen, since `--version` (`cli.rs`) exits before
/// the terminal is claimed. Not the status row, which [0026](../../../../docs/adr/0026-the-status-row-is-one-list-not-a-stack-of-surfaces.md)
/// and [0027](../../../../docs/adr/0027-the-active-set-names-the-status-row-and-the-picker-is-the-strip.md)
/// close to this, nor the footer, which [0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md)
/// fixes as derived from the binding table alone.
fn version_title() -> String {
    format!("repon {}", env!("CARGO_PKG_VERSION"))
}

/// The interior's list rows when the query matches nothing, the same convention
/// [`crate::launcher_palette::NO_MATCHES_MESSAGE`] uses for the same fact on a different
/// surface: shown once in place of the list rather than an empty area, so a query that
/// matches nothing is told apart from a query nobody has typed anything into yet.
pub(crate) const NO_MATCHES_MESSAGE: &str = "no matches";

/// The `global` section's own heading text.
pub(crate) const GLOBAL_HEADING: &str = "Global";

/// The legend section's own heading text.
pub(crate) const LEGEND_HEADING: &str = "Glyphs";

/// One line the overlay can render: a section heading, a blank row separating two sections, a
/// keybinding row from [`BindingTable::describe_own`]/[`BindingTable::describe_global`], or a
/// legend row naming what one row-interior glyph means. Kept as its own line kind rather than
/// squeezing a legend row into a binding row's shape, because a legend row's two columns
/// (glyph, meaning) are not a key and a description, and filtering must not conflate the two.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum HelpLine {
    /// One of the overlay's three section headings: the current context's own name, `global`,
    /// or the glyph legend's ([`HelpOverlay::assemble_sections`]'s own blank-row rule puts one
    /// above every heading but the first that survives a query).
    Heading(&'static str),
    /// The one blank row [`HelpOverlay::assemble_sections`] inserts above every heading but
    /// the first, so the groups it separates read apart by whitespace rather than sitting
    /// flush.
    Blank,
    Binding {
        keys: String,
        description: &'static str,
    },
    Legend {
        glyph: String,
        meaning: &'static str,
    },
}

/// The prose for one row-interior [`Meaning`], pinned to
/// [theming.md](../../../../docs/spec/theming.md)'s "The two sets" table:
/// `glyph_legend_prose_matches_theming_mds_own_two_sets_table` reads that table at test time
/// and checks every arm against it rather than restating the wording a second time. No `_`
/// arm: a `Meaning` variant added in `crate::glyphs` without a line here fails to compile,
/// which is the whole point of driving the legend from the enum instead of a hand-kept list.
fn meaning_text(meaning: Meaning) -> &'static str {
    match meaning {
        Meaning::Fresh => "Fresh (gutter)",
        Meaning::Stale => "Stale (gutter)",
        Meaning::Unknown => "Unknown (gutter)",
        Meaning::Failed => "Failed (gutter)",
        Meaning::Loading => "Loading (gutter, and a cell)",
        Meaning::InSync => "in sync",
        Meaning::Clean => "clean, a known zero",
        Meaning::NoUpstream => "no upstream, or no branch at all",
        Meaning::NoRemote => "no remote at all",
        Meaning::Ahead => "ahead by n",
        Meaning::Behind => "behind by n",
        Meaning::Changed => "n changed files",
        Meaning::ChildRow => "child row",
        Meaning::OrphanChildRow => "child with no visible parent",
        Meaning::Checked => "checked (the Selection's own marker)",
        Meaning::Ignored => "ignored",
        Meaning::Truncated => "truncated name",
    }
}

/// The current-context section's own heading text
/// ([keybindings.md](../../../../docs/spec/keybindings.md#the-contexts) names the seven
/// contexts this matches). No `_` arm: a context added to [`Context`] fails to compile here
/// until this overlay says what its own section is called, rather than falling back to
/// something generic no reader asked for.
fn context_heading(context: Context) -> &'static str {
    match context {
        Context::Global => GLOBAL_HEADING,
        Context::List => "List",
        Context::Detail => "Detail",
        Context::Input => "Input",
        Context::Overlay => "Overlay",
        Context::Confirm => "Confirm",
        Context::Sort => "Sort",
    }
}

/// One [`HelpLine::Binding`] per `(keys, description)` pair, kept apart rather than joined
/// into one string: [theming.md](../../../../docs/spec/theming.md) fixes the keys' own role
/// as `accent` and the description's as `dim`, and that split only survives if nothing here
/// bakes it together before [`HelpOverlay::draw`] paints it.
fn bindings_to_lines(rows: Vec<(String, &'static str)>) -> Vec<HelpLine> {
    rows.into_iter()
        .map(|(keys, description)| HelpLine::Binding { keys, description })
        .collect()
}

/// One [`HelpLine::Legend`] per `(glyph, meaning)` pair, [`HelpOverlay::legend_rows`]'s own
/// output kept apart the same way [`bindings_to_lines`] keeps a binding's two columns apart.
fn legend_to_lines(rows: Vec<(String, &'static str)>) -> Vec<HelpLine> {
    rows.into_iter()
        .map(|(glyph, meaning)| HelpLine::Legend { glyph, meaning })
        .collect()
}

/// Whether `frame_area` is drawn as a bordered panel or, below the size that needs, degraded
/// to flush content with no border: [`HelpOverlay::draw`] and [`HelpOverlay::viewport_height`]
/// both read this so neither can disagree with the other about which shape is on screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HelpLayout {
    /// The house-style bordered panel, filling the whole frame: help is a reading surface,
    /// not a chooser, so unlike a palette it never shrinks to leave anything visible around
    /// it ([0008](../../../../docs/adr/0008-two-palettes-not-one.md)).
    Bordered,
    /// `frame_area` is too small to hold a border and any content without clipping the
    /// border itself; content draws flush against the frame with no border at all, the same
    /// way this overlay drew before this ticket.
    Degraded,
}

impl HelpLayout {
    /// Decides between the two shapes from `frame_area` alone: content length plays no part,
    /// since a bordered panel spans the whole frame here regardless of how much it holds.
    pub(crate) fn compute(frame_area: Rect) -> HelpLayout {
        if frame_area.width < MIN_BORDERED_WIDTH || frame_area.height < MIN_BORDERED_HEIGHT {
            HelpLayout::Degraded
        } else {
            HelpLayout::Bordered
        }
    }

    /// The area content lines draw into: `frame_area`'s own interior, one cell inset from the
    /// border on every side, for `Bordered`; `frame_area` itself, flush, for `Degraded`,
    /// which draws no border to be inset from.
    pub(crate) fn content_area(self, frame_area: Rect) -> Rect {
        match self {
            HelpLayout::Bordered => bordered_interior(frame_area),
            HelpLayout::Degraded => frame_area,
        }
    }
}

/// One line's own rendered width at `key_width`: a heading's own text, or the padded
/// key/glyph column plus the two-space inner gutter plus the description/meaning, matching
/// exactly what [`HelpOverlay::draw_line`] paints. A blank separator has no width of its own.
fn line_display_width(line: &HelpLine, key_width: usize) -> usize {
    match line {
        HelpLine::Heading(text) => text.chars().count(),
        HelpLine::Binding { description, .. } => description.chars().count() + key_width + 2,
        HelpLine::Legend { meaning, .. } => meaning.chars().count() + key_width + 2,
        HelpLine::Blank => 0,
    }
}

/// The widest key or glyph column any line in `lines` needs, 0 for a column with no such line
/// (a slice of nothing but headings and blanks). Shared by [`ColumnMetrics::compute`] to size a
/// column's own key/glyph gutter from that column's own lines alone, rather than the whole
/// table.
fn max_key_width(lines: &[HelpLine]) -> usize {
    lines
        .iter()
        .map(|line| match line {
            HelpLine::Binding { keys, .. } => keys.chars().count(),
            HelpLine::Legend { glyph, .. } => glyph.chars().count(),
            HelpLine::Heading(_) | HelpLine::Blank => 0,
        })
        .max()
        .unwrap_or(0)
}

/// `lines`' own rendered width at `key_width`: the widest [`line_display_width`] among them, 0
/// for an empty column.
fn column_width(lines: &[HelpLine], key_width: usize) -> u16 {
    lines
        .iter()
        .map(|line| line_display_width(line, key_width) as u16)
        .max()
        .unwrap_or(0)
}

/// The overlay's column geometry for one frame width, computed once so [`HelpOverlay::draw`]'s
/// render loop and [`HelpOverlay::visible_len`]'s own row count can never disagree about what
/// is on screen. The key/glyph gutter is one fixed width *per column*, not one figure shared
/// across both: [`HelpOverlay::split_into_columns`] decides which sections land in which column
/// first, from the whole unfiltered content ([`HelpOverlay::built_sections`] with an empty
/// query), and each column is then measured only against its own lines
/// ([`max_key_width`], [`column_width`]). `two_columns` holds once the two columns' own widths
/// plus [`COLUMN_GUTTER`] fit `content_width`; reading from the unfiltered split rather than
/// whatever a query currently narrows to is what keeps a column's own gutter, and the column
/// count itself, from shifting mid-search.
struct ColumnMetrics {
    left_key_width: usize,
    right_key_width: usize,
    two_columns: bool,
    /// How far right of the left column's own origin the right one starts, when
    /// `two_columns` holds. Unused otherwise.
    column_offset: u16,
}

impl ColumnMetrics {
    /// `left` and `right`, already split, into `(left_key_width, right_key_width, left_width,
    /// right_width)`: the shared arithmetic [`Self::compute`] and the test module's own
    /// `two_column_threshold` both need, so the test pins the exact threshold without a
    /// second copy of this sum drifting from the real one.
    fn column_metrics(left: &[HelpLine], right: &[HelpLine]) -> (usize, usize, u16, u16) {
        let left_key_width = max_key_width(left);
        let right_key_width = max_key_width(right);
        let left_width = column_width(left, left_key_width);
        let right_width = column_width(right, right_key_width);
        (left_key_width, right_key_width, left_width, right_width)
    }

    fn compute(
        table: &BindingTable,
        context: Context,
        glyphs: &GlyphSet,
        content_width: u16,
    ) -> ColumnMetrics {
        let unfiltered = HelpOverlay::built_sections(table, context, glyphs, "");
        let (left, right) = HelpOverlay::split_into_columns(unfiltered);
        let (left_key_width, right_key_width, left_width, right_width) =
            Self::column_metrics(&left, &right);
        let two_column_min_width = left_width
            .saturating_add(COLUMN_GUTTER)
            .saturating_add(right_width);
        ColumnMetrics {
            left_key_width,
            right_key_width,
            two_columns: content_width >= two_column_min_width,
            column_offset: left_width.saturating_add(COLUMN_GUTTER),
        }
    }
}

/// The overlay's own two modes, [`crate::app::App`]'s own key handling decides between on
/// every keystroke: reading is the overlay's original shape, searching is `/`'s own, and
/// [`HelpOverlay::draw`] and [`HelpOverlay::viewport_height`] both read this to decide
/// whether the query line has a row to draw into at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Mode {
    #[default]
    Reading,
    Searching,
}

/// The overlay's own scroll position, mode and query: [`HelpOverlay::built_sections`] derives
/// everything else fresh from the binding table and the live glyph set on every call, which
/// is what lets a config reload or a `glyphs` switch change what this screen shows with no
/// code change here. Dropped and rebuilt with [`Self::default`] on every open
/// ([`crate::app::App`]'s own `Action::OpenHelp` arm), which is what makes reopening start
/// in reading mode with an empty query.
#[derive(Default)]
pub(crate) struct HelpOverlay {
    scroll: u16,
    /// The same buffer every `input`-context field edits through, so the query's `Backspace`
    /// and `Ctrl+W` are one implementation rather than a second copy. Its cursor stays at the
    /// end: `overlay` binds no motion, since `Up` and `Down` scroll the list here.
    query: EditBuffer,
    mode: Mode,
}

impl HelpOverlay {
    /// One line per action live in `context`, as `(keys, description)`, current context first
    /// then `global`: [`BindingTable::describe`]'s own flat shape, kept for whatever wants the
    /// overlay's content with no section boundary. [`Self::lines`] reads
    /// [`BindingTable::describe_own`] and [`BindingTable::describe_global`] instead, since it
    /// is the boundary between them that carries a heading. Test-only: nothing in the render
    /// path needs the two merged back together once they draw as separate sections.
    #[cfg(test)]
    pub(crate) fn content(table: &BindingTable, context: Context) -> Vec<(String, &'static str)> {
        table.describe(context)
    }

    /// One row per row-interior [`Meaning`], `Meaning::ALL` driving the loop rather than a
    /// hand-kept list so a variant `meaning_text` cannot yet describe fails to compile
    /// before it could reach here silently. `glyph` is read live from `glyphs.row_interior()`
    /// rather than typed in: every occurrence of a meaning joins into one string, which is
    /// one character for every meaning but `Loading`, where every spinner frame joins into
    /// the one row the same way [theming.md](../../../../docs/spec/theming.md)'s "The two
    /// sets" shows the whole frame set in one cell.
    fn legend_rows(glyphs: &GlyphSet) -> Vec<(String, &'static str)> {
        let interior = glyphs.row_interior();
        Meaning::ALL
            .into_iter()
            .map(|meaning| {
                let glyph: String = interior
                    .iter()
                    .filter(|(m, _)| *m == meaning)
                    .map(|(_, c)| *c)
                    .collect();
                (glyph, meaning_text(meaning))
            })
            .collect()
    }

    /// Folds `sections` into one line list: each section's own heading immediately followed
    /// by its content, a [`HelpLine::Blank`] above every heading but the first that survives.
    /// A section whose content is empty is dropped entirely, heading included, so a query that
    /// empties one never leaves its heading standing over nothing; that rule is what already
    /// held for the legend heading alone and now covers all three. Takes a `Vec` rather than
    /// the fixed three-element array it once did: [`Self::split_into_columns`] calls this on
    /// whatever subset of sections a column holds, not always all three at once.
    fn assemble_sections(sections: Vec<(&'static str, Vec<HelpLine>)>) -> Vec<HelpLine> {
        let mut lines = Vec::new();
        for (heading, content) in sections
            .into_iter()
            .filter(|(_, content)| !content.is_empty())
        {
            if !lines.is_empty() {
                lines.push(HelpLine::Blank);
            }
            lines.push(HelpLine::Heading(heading));
            lines.extend(content);
        }
        lines
    }

    /// The overlay's three sections narrowed to `query` (empty matches everything, the same
    /// case-insensitive substring convention [`crate::launcher_palette::matching`] and
    /// [`crate::action_palette::ActionPalette::matches`] already match their own lists with),
    /// heading paired with its own content, a section left with no surviving content dropped
    /// entirely rather than standing over nothing: `context`'s own bindings
    /// ([`BindingTable::describe_own`]), the `global` bindings live alongside it
    /// ([`BindingTable::describe_global`]), and one legend row per row-interior [`Meaning`]
    /// ([`Self::legend_rows`]). The one source `Self::lines`, `Self::filtered_lines` (both
    /// assembled flat, one column) and [`Self::draw`] (assembled into one or two columns,
    /// [`Self::split_into_columns`]) all build from, so the shapes can never disagree about
    /// which sections and rows exist.
    fn built_sections(
        table: &BindingTable,
        context: Context,
        glyphs: &GlyphSet,
        query: &str,
    ) -> Vec<(&'static str, Vec<HelpLine>)> {
        let query = query.to_lowercase();
        let binding_matches = |(keys, description): &(String, &'static str)| {
            keys.to_lowercase().contains(&query) || description.to_lowercase().contains(&query)
        };
        let legend_matches = |(glyph, meaning): &(String, &'static str)| {
            glyph.to_lowercase().contains(&query) || meaning.to_lowercase().contains(&query)
        };
        [
            (
                context_heading(context),
                bindings_to_lines(
                    table
                        .describe_own(context)
                        .into_iter()
                        .filter(binding_matches)
                        .collect(),
                ),
            ),
            (
                GLOBAL_HEADING,
                bindings_to_lines(
                    table
                        .describe_global(context)
                        .into_iter()
                        .filter(binding_matches)
                        .collect(),
                ),
            ),
            (
                LEGEND_HEADING,
                legend_to_lines(
                    Self::legend_rows(glyphs)
                        .into_iter()
                        .filter(legend_matches)
                        .collect(),
                ),
            ),
        ]
        .into_iter()
        .filter(|(_, content)| !content.is_empty())
        .collect()
    }

    /// The overlay's full content with no query typed, assembled into one column
    /// ([`Self::assemble_sections`] over [`Self::built_sections`]). Test-only: production
    /// measures column widths from [`Self::built_sections`] split into two, never from this
    /// flat one-column shape.
    #[cfg(test)]
    fn lines(table: &BindingTable, context: Context, glyphs: &GlyphSet) -> Vec<HelpLine> {
        Self::assemble_sections(Self::built_sections(table, context, glyphs, ""))
    }

    /// [`Self::lines`] narrowed to `query` ([`Self::built_sections`]), assembled into one
    /// column: the flat shape [`Self::visible_len`] and [`Self::draw`] no longer render
    /// directly (both lay `query`'s own sections out through [`Self::laid_out`] instead, one
    /// or two columns depending on the frame), kept as the one-column reference a test can
    /// still assert content and ordering against. An empty query matches everything.
    #[cfg(test)]
    pub(crate) fn filtered_lines(
        table: &BindingTable,
        context: Context,
        glyphs: &GlyphSet,
        query: &str,
    ) -> Vec<HelpLine> {
        Self::assemble_sections(Self::built_sections(table, context, glyphs, query))
    }

    /// The row count [`Self::draw`] actually puts on screen for `query` at `frame_area`'s own
    /// width ([`Self::laid_out`]): one column's worth below the two-column threshold
    /// ([`ColumnMetrics::two_columns`]), the taller of the two column line lists at or above
    /// it. What the scroll clamp ([`Self::apply`]) must fold every action against, since a
    /// frame wide enough to split the list into two columns side by side has fewer rows to
    /// scroll through than the flat line count (`Self::filtered_lines`) would suggest.
    pub(crate) fn visible_len(
        table: &BindingTable,
        context: Context,
        glyphs: &GlyphSet,
        query: &str,
        frame_area: Rect,
    ) -> usize {
        let sections = Self::built_sections(table, context, glyphs, query);
        if sections.is_empty() {
            return 0;
        }
        let content_width = HelpLayout::compute(frame_area)
            .content_area(frame_area)
            .width;
        let metrics = ColumnMetrics::compute(table, context, glyphs, content_width);
        let (left, right) = Self::laid_out(sections, &metrics);
        left.len().max(right.len())
    }

    /// `sections` assembled into the shape [`Self::draw`] renders: one column (`right` empty)
    /// below [`ColumnMetrics::two_columns`], split at a section boundary
    /// ([`Self::split_into_columns`]) at or above it.
    fn laid_out(
        sections: Vec<(&'static str, Vec<HelpLine>)>,
        metrics: &ColumnMetrics,
    ) -> (Vec<HelpLine>, Vec<HelpLine>) {
        if metrics.two_columns {
            Self::split_into_columns(sections)
        } else {
            (Self::assemble_sections(sections), Vec::new())
        }
    }

    /// The row count [`Self::assemble_sections`] would produce for `sections`, without paying
    /// to assemble them: each section costs its own heading plus its content, and every
    /// section after the first in the slice costs one more for the [`HelpLine::Blank`] above
    /// it. [`Self::split_into_columns`] calls this on candidate prefixes and suffixes to find
    /// the boundary that balances the two without assembling every candidate to measure it.
    fn assembled_len(sections: &[(&'static str, Vec<HelpLine>)]) -> usize {
        if sections.is_empty() {
            return 0;
        }
        sections
            .iter()
            .map(|(_, content)| 1 + content.len())
            .sum::<usize>()
            + sections.len()
            - 1
    }

    /// Splits `sections` (already narrowed to a query and dropped of any left empty by
    /// [`Self::built_sections`]) into two column-ordered line lists. A section is never split
    /// across the boundary: every whole section in `sections`' own order goes to the left
    /// column up to some index, the rest to the right, at whichever boundary leaves the two
    /// assembled lengths ([`Self::assembled_len`]) closest. Reading order is preserved, top to
    /// bottom in the left column, then continuing top to bottom in the right one, exactly the
    /// order [`Self::assemble_sections`] would use for all of `sections` in one column.
    ///
    /// One section that is simply too tall for any boundary to balance well (its own line
    /// count alone dwarfs the rest) still lands whole in one column; the choice below still
    /// picks the least-lopsided boundary available, it just cannot make that section's own
    /// bulk disappear. A single surviving section (a query narrow enough that only one of the
    /// three matches anything) cannot be split at all: putting it whole on the left and
    /// leaving the right empty ties with the reverse, and the left is what a reader's eye
    /// already rests on, so ties favour it (`.rev()` below, so the largest tied boundary is
    /// the first `min_by_key` sees) rather than leaving the left column blank with everything
    /// pushed past an empty gutter. Either way the overlay stays one column in every way that
    /// matters even though [`ColumnMetrics::two_columns`] held.
    fn split_into_columns(
        mut sections: Vec<(&'static str, Vec<HelpLine>)>,
    ) -> (Vec<HelpLine>, Vec<HelpLine>) {
        let split = (0..=sections.len())
            .rev()
            .min_by_key(|&s| {
                Self::assembled_len(&sections[..s]).abs_diff(Self::assembled_len(&sections[s..]))
            })
            .unwrap_or(0);
        let right = sections.split_off(split);
        (
            Self::assemble_sections(sections),
            Self::assemble_sections(right),
        )
    }

    /// Whether the query line has a row to draw into at all: while actively searching, so
    /// the `/` prompt is visible even before anything is typed, or in reading mode with a
    /// filter still committed from an earlier search ([`Self::commit_search`]) so the user
    /// can see what is narrowing the list underneath them. A fresh, never-searched overlay
    /// shows neither, which is what makes reading mode's layout identical to the overlay's
    /// pre-search shape rather than always costing it a row.
    fn shows_query_line(&self) -> bool {
        self.mode == Mode::Searching || !self.query.is_empty()
    }

    /// The overlay's real interior height for `frame_area`: the bordered panel's own
    /// interior, one row shorter only while [`Self::shows_query_line`] has something to put on
    /// the interior's own last row. The caller's scroll clamp must use this, since the border
    /// and (conditionally) the query row both cost it.
    pub(crate) fn viewport_height(&self, frame_area: Rect) -> u16 {
        let interior = HelpLayout::compute(frame_area)
            .content_area(frame_area)
            .height;
        if self.shows_query_line() {
            interior.saturating_sub(1)
        } else {
            interior
        }
    }

    /// The query typed so far, empty until the first keystroke of a search.
    pub(crate) fn query(&self) -> &str {
        self.query.as_str()
    }

    /// Whether `/` has been pressed and `Esc` or `Enter` has not yet left search mode again:
    /// what [`crate::app::App`]'s own key handling reads to decide whether a printable key
    /// is query text or one of `Context::Overlay`'s own scroll/close bindings.
    pub(crate) fn is_searching(&self) -> bool {
        self.mode == Mode::Searching
    }

    /// `/` (`Action::Search`), from reading mode: enters search mode without disturbing
    /// whatever query already exists, so refining a committed search
    /// ([`Self::commit_search`]) is the common case, the same way
    /// [`crate::filter_line::FilterLine::new`] reopens prefilled with the committed Filter's
    /// own text rather than empty.
    pub(crate) fn enter_search(&mut self) {
        self.mode = Mode::Searching;
    }

    /// `Esc` from search mode: one rung of help's own unwind ladder, the same
    /// one-level-at-a-time philosophy [`crate::unwind::unwind_one`] already gives Global's
    /// own `Esc` elsewhere. Leaves search mode and clears the query, one level short of
    /// closing help entirely, which is the next press's job once back in reading mode.
    pub(crate) fn cancel_search(&mut self) {
        self.mode = Mode::Reading;
        self.query.clear();
        self.scroll = 0;
    }

    /// `Enter` from search mode: leaves search mode but keeps the query applied, so `j`/`k`
    /// then scroll the list it narrowed rather than the reader losing their place to a
    /// query that vanishes the moment they stop typing it.
    pub(crate) fn commit_search(&mut self) {
        self.mode = Mode::Reading;
    }

    /// Appends one typed character to the query and snaps the scroll back to the top: a
    /// keystroke that narrows or widens the list underneath a standing offset would otherwise
    /// leave the viewport looking at whatever used to be there.
    pub(crate) fn push_query_char(&mut self, c: char) {
        self.query.insert_char(c);
        self.scroll = 0;
    }

    /// `Backspace`: drops the last character of the query, the same
    /// `Context::Input`/`DeletePreviousChar` row every other text surface reads. Inert on an
    /// empty query, which keeps it from being a second way to leave search mode.
    pub(crate) fn pop_query_char(&mut self) {
        self.query.delete_previous_char();
        self.scroll = 0;
    }

    /// `Ctrl+W`: deletes one trailing whitespace-delimited word from the query, the same
    /// `Context::Input`/`DeletePreviousWord` row every other text surface reads.
    pub(crate) fn delete_previous_word(&mut self) {
        self.query.delete_previous_word();
        self.scroll = 0;
    }

    /// Folds one of the overlay's own scroll actions into the current offset, clamped so it
    /// can never scroll past the last line reaching `viewport_height`. Every other action
    /// (`Choose`, `Close`) is the caller's concern: `Close` unmounts this overlay entirely,
    /// which is not a state this struct can represent about itself.
    pub(crate) fn apply(&mut self, action: Action, content_len: usize, viewport_height: u16) {
        self.scroll = scroll_after(self.scroll, action, content_len, viewport_height);
    }

    /// Paints one `line` at `(x, y)`: a binding's or legend's own key/glyph column padded to
    /// `key_width` in `accent`, two spaces, then the description or meaning in `dim`
    /// ([theming.md](../../../../docs/spec/theming.md)); a heading in bold `accent`; a blank
    /// row paints nothing. The one line-painting path both of [`Self::draw`]'s columns share,
    /// so a binding's two-tone split ([`bindings_to_lines`]'s own doc) stays one
    /// implementation rather than two copies a second column could drift out of step with.
    fn draw_line(
        buf: &mut Buffer,
        x: u16,
        y: u16,
        end: u16,
        line: &HelpLine,
        key_width: usize,
        theme: &Theme,
    ) {
        let mut x = x;
        match line {
            HelpLine::Binding { keys, description } => {
                let padded_keys = format!("{keys:<key_width$}");
                paint_run(
                    buf,
                    &mut x,
                    y,
                    end,
                    &padded_keys,
                    theme.style_for(Role::Accent),
                );
                paint_run(buf, &mut x, y, end, "  ", theme.style_for(Role::Dim));
                paint_run(buf, &mut x, y, end, description, theme.style_for(Role::Dim));
            }
            HelpLine::Legend { glyph, meaning } => {
                let padded_glyph = format!("{glyph:<key_width$}");
                paint_run(
                    buf,
                    &mut x,
                    y,
                    end,
                    &padded_glyph,
                    theme.style_for(Role::Accent),
                );
                paint_run(buf, &mut x, y, end, "  ", theme.style_for(Role::Dim));
                paint_run(buf, &mut x, y, end, meaning, theme.style_for(Role::Dim));
            }
            HelpLine::Heading(text) => {
                let heading_style = theme.style_for(Role::Accent).add_modifier(Modifier::BOLD);
                paint_run(buf, &mut x, y, end, text, heading_style);
            }
            HelpLine::Blank => {}
        }
    }

    /// Draws the overlay into `frame_area`: the house-style bordered panel (its own bottom
    /// border carrying this crate's version, right-aligned) or, below
    /// [`HelpLayout::compute`]'s threshold, flush content with no border; the section headings
    /// and binding/legend rows above the query line, which takes the interior's own last row
    /// while [`Self::shows_query_line`] holds. Below [`ColumnMetrics::two_columns`]'s own
    /// threshold this is one scrolling list, exactly as it always was; at or above it, the
    /// content is split at a section boundary ([`Self::split_into_columns`]) into two columns
    /// side by side sharing one scroll position, the row count the taller of the two
    /// ([`Self::visible_len`], which the caller's scroll clamp must use instead of the flat
    /// line count once a frame is wide enough for this).
    pub(crate) fn draw(
        &self,
        frame: &mut Frame,
        frame_area: Rect,
        context: Context,
        table: &BindingTable,
        theme: &Theme,
        glyphs: &'static GlyphSet,
    ) {
        let layout = HelpLayout::compute(frame_area);
        if layout == HelpLayout::Bordered {
            // Like `List`'s own border, always painted focused: help is the only thing on
            // screen while it is open, so there is no second, dimmer panel to contrast it
            // against.
            let mut scratch = BorderScratch::new();
            let block = glyphs
                .bordered_block(&mut scratch)
                .border_style(theme.style_for(Role::BorderFocused))
                .title(BORDER_TITLE)
                .title_bottom(Line::from(version_title()).right_aligned());
            frame.render_widget(block, frame_area);
        }
        let content_area = layout.content_area(frame_area);
        let buf = frame.buffer_mut();
        let end = content_area.right();

        // The list gets the whole interior except the one row the query line costs while
        // `Self::shows_query_line` holds; that row sits at the interior's own bottom edge,
        // never at the top where the query used to sit, so it lines up with where the main
        // screen puts its own Filter line, directly above the footer.
        let list_height = if self.shows_query_line() {
            content_area.height.saturating_sub(1)
        } else {
            content_area.height
        };
        let list_area = Rect::new(
            content_area.x,
            content_area.y,
            content_area.width,
            list_height,
        );

        let sections = Self::built_sections(table, context, glyphs, self.query.as_str());
        if sections.is_empty() {
            let mut x = list_area.x;
            paint_run(
                buf,
                &mut x,
                list_area.y,
                list_area.right(),
                NO_MATCHES_MESSAGE,
                theme.style_for(Role::Dim),
            );
        } else {
            let metrics = ColumnMetrics::compute(table, context, glyphs, content_area.width);
            let (left, right) = Self::laid_out(sections, &metrics);
            let row_count = left.len().max(right.len());

            for row in 0..(list_area.height as usize) {
                let index = row + self.scroll as usize;
                if index >= row_count {
                    break;
                }
                let y = list_area.y + row as u16;
                if let Some(line) = left.get(index) {
                    Self::draw_line(
                        buf,
                        list_area.x,
                        y,
                        end,
                        line,
                        metrics.left_key_width,
                        theme,
                    );
                }
                if let Some(line) = right.get(index) {
                    Self::draw_line(
                        buf,
                        list_area.x + metrics.column_offset,
                        y,
                        end,
                        line,
                        metrics.right_key_width,
                        theme,
                    );
                }
            }
        }

        if self.shows_query_line() {
            let mut qx = content_area.x;
            let query_line = format!("/ {}", self.query.as_str());
            let query_y = content_area.y + list_height;
            paint_run(
                buf,
                &mut qx,
                query_y,
                end,
                &query_line,
                theme.style_for(Role::Text),
            );
        }
    }
}

/// Writes `text` at `(*x, y)` in `style`, clipped to the buffer's own right edge at `end`,
/// and advances `*x` past what was actually written: `footer.rs`'s own `paint_run` has the
/// same shape, reimplemented here since that copy is private to its module.
fn paint_run(buf: &mut Buffer, x: &mut u16, y: u16, end: u16, text: &str, style: Style) {
    let (next_x, _) = buf.set_stringn(*x, y, text, end.saturating_sub(*x) as usize, style);
    *x = next_x;
}

#[cfg(test)]
mod tests {
    use ratatui::{Terminal, backend::TestBackend};

    use super::*;

    /// The compiled default table: none of these tests exercises a config rebind, only the
    /// derivation, ordering and scrolling.
    fn default_table() -> BindingTable {
        BindingTable::compiled_default()
    }

    /// The full glyph table, for every test that draws a border and does not care which one
    /// is in force.
    fn full_glyphs() -> &'static GlyphSet {
        GlyphSet::for_config(crate::config::document::Glyphs::default())
    }

    fn ascii_glyphs() -> &'static GlyphSet {
        GlyphSet::for_config(crate::config::document::Glyphs::Ascii)
    }

    /// A frame comfortably larger than the border/content minimum, for every test that is not
    /// itself exercising the degrade threshold. Tall enough to hold every `List`-context line
    /// (its own bindings, `global`'s, and the glyph legend) with room to spare, so a binding
    /// added to the default map does not silently scroll the legend heading out of view here.
    const ROOMY_FRAME: Rect = Rect::new(0, 0, 100, 70);

    /// Renders `overlay` at `width`x`height` for `context` and hands back the terminal so a
    /// test can read its buffer: the one render path every rendering test below shares.
    fn render(
        overlay: &HelpOverlay,
        width: u16,
        height: u16,
        context: Context,
        table: &BindingTable,
    ) -> Terminal<TestBackend> {
        render_with_glyphs(overlay, width, height, context, table, full_glyphs())
    }

    fn render_with_glyphs(
        overlay: &HelpOverlay,
        width: u16,
        height: u16,
        context: Context,
        table: &BindingTable,
        glyphs: &'static GlyphSet,
    ) -> Terminal<TestBackend> {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        terminal
            .draw(|frame| {
                overlay.draw(
                    frame,
                    frame.area(),
                    context,
                    table,
                    &crate::theme::DEFAULT,
                    glyphs,
                );
            })
            .expect("draw the frame");
        terminal
    }

    /// The leftmost `x` on row `y`, within `[area.x, area.right())`, where `text` starts
    /// reading forward: how a test locates a line's own description without recomputing the
    /// gutter width the production code used to place it there.
    fn find_text_start_x(buf: &ratatui::buffer::Buffer, area: Rect, y: u16, text: &str) -> u16 {
        let want: Vec<char> = text.chars().collect();
        for x in area.x..area.right() {
            let got: Vec<char> = (x..area.right())
                .take(want.len())
                .map(|cx| buf[(cx, y)].symbol().chars().next().unwrap_or(' '))
                .collect();
            if got == want {
                return x;
            }
        }
        panic!("text {text:?} not found on row {y} within {area:?}");
    }

    /// The content area's list portion, mode-aware: one row shorter than the interior while
    /// `overlay` shows a query line ([`HelpOverlay::shows_query_line`]), which now takes the
    /// interior's own last row rather than its first, so the list still starts flush at the
    /// origin either way and only its height changes. Reading a fresh, never-searched
    /// `overlay`'s own state here rather than assuming a fixed offset is what keeps this
    /// helper honest about the one thing the heading rework is about: reading mode costs no
    /// row at all.
    fn list_area(overlay: &HelpOverlay, frame: Rect) -> Rect {
        let content_area = HelpLayout::compute(frame).content_area(frame);
        let height = if overlay.shows_query_line() {
            content_area.height - 1
        } else {
            content_area.height
        };
        Rect::new(content_area.x, content_area.y, content_area.width, height)
    }

    /// `line`'s own leading character, whichever variant it is: a heading's own text, a
    /// binding's keys or a legend's glyph. What a test reads to check the very first rendered
    /// line lands where it should, without assuming that line is a binding.
    fn leading_char(line: &HelpLine) -> char {
        let text = match line {
            HelpLine::Heading(text) => text,
            HelpLine::Binding { keys, .. } => keys.as_str(),
            HelpLine::Legend { glyph, .. } => glyph.as_str(),
            HelpLine::Blank => panic!("expected a real line, not the blank separator"),
        };
        text.chars().next().expect("expected a non-empty line")
    }

    /// The symbol [`HelpOverlay::draw_line`] actually paints at `line`'s own row, first
    /// column: [`leading_char`] for a real line, or a bare space for [`HelpLine::Blank`],
    /// which paints nothing and so reads back as the buffer's own untouched cell. Unlike
    /// `leading_char`, this never panics: a test asserting "the left column keeps going" past
    /// where a shorter right column ran out must hold whichever line lands there, blank
    /// separator included, rather than assuming row counts always dodge one.
    fn rendered_symbol(line: &HelpLine) -> String {
        match line {
            HelpLine::Blank => " ".to_string(),
            other => leading_char(other).to_string(),
        }
    }

    // --- content is derived, not transcribed, and stays unjoined ---

    #[test]
    fn content_is_exactly_the_tables_own_describe_with_no_reformatting() {
        let table = default_table();
        assert_eq!(
            HelpOverlay::content(&table, Context::List),
            table.describe(Context::List)
        );
    }

    #[test]
    fn content_shows_the_current_contexts_own_actions_before_global() {
        let lines = HelpOverlay::content(&default_table(), Context::List);
        let own = lines
            .iter()
            .position(|(_, description)| *description == "Move down")
            .expect("List's own Move down must appear");
        let global = lines
            .iter()
            .position(|(_, description)| *description == "Quit")
            .expect("Global's Quit must appear alongside List");
        assert!(own < global, "expected List before global, got {lines:?}");
    }

    #[test]
    fn content_omits_bindings_not_live_in_the_given_context() {
        // Confirm never dispatches Global, so a leaked "Move down" or "Quit" line would be
        // a context-scoping bug, not merely an ordering one.
        let lines = HelpOverlay::content(&default_table(), Context::Confirm);
        assert!(
            !lines
                .iter()
                .any(|(_, description)| *description == "Move down")
        );
        assert!(!lines.iter().any(|(_, description)| *description == "Quit"));
        assert!(lines.iter().any(|(_, description)| *description == "Run"));
    }

    /// [ADR 0023](../../../../docs/adr/0023-an-unbuilt-binding-is-not-advertised-and-an-unavailable-one-answers-on-press.md):
    /// the help overlay carries only Built bindings. Built against
    /// [`keys::single_unbuilt_binding_table`]'s synthetic table rather than off
    /// [`keys::unbuilt_bindings`]: with `d` built,
    /// `BINDINGS` carries no unbuilt row today, and `content`'s own filter is what this test
    /// proves, not which production row happens to be in that state this week.
    #[test]
    fn content_excludes_a_currently_unbuilt_binding() {
        let unbuilt_context = Context::List;
        let unbuilt_action = Action::DismissVanished;
        let table = crate::keys::single_unbuilt_binding_table(
            unbuilt_context,
            crossterm::event::KeyCode::Char('x'),
            crossterm::event::KeyModifiers::NONE,
            unbuilt_action,
        );
        let unbuilt_description = crate::keys::description(unbuilt_action);
        let lines = HelpOverlay::content(&table, unbuilt_context);
        assert!(
            !lines
                .iter()
                .any(|(_, description)| *description == unbuilt_description),
            "expected {unbuilt_description:?}, unbuilt in this synthetic table, to be \
             absent from the help overlay, got: {lines:?}"
        );
    }

    #[test]
    fn visible_len_matches_filtered_lines_own_length_for_every_query_below_the_two_column_threshold()
     {
        let table = default_table();
        for query in ["", "move", "zzz-nothing-matches-this-zzz"] {
            assert_eq!(
                HelpOverlay::visible_len(&table, Context::List, full_glyphs(), query, ROOMY_FRAME),
                HelpOverlay::filtered_lines(&table, Context::List, full_glyphs(), query).len()
            );
        }
    }

    #[test]
    fn content_reflects_whatever_table_it_is_handed_rather_than_a_fixed_default() {
        // Not a config-parsing test: `keys::merge`'s own tests own that. This only proves
        // `content` is a pure function of the table it is given, which is what lets a config
        // reload change the overlay by handing it a new table, with no code change here.
        let mut context_table = toml::Table::new();
        context_table.insert(
            "anchor_range".to_string(),
            toml::Value::String("x".to_string()),
        );
        let mut document_keys = toml::Table::new();
        document_keys.insert("list".to_string(), toml::Value::Table(context_table));
        let (rebound, _) =
            crate::keys::merge(&document_keys).expect("expected the merge to succeed");

        let rows = HelpOverlay::content(&rebound, Context::List);
        assert!(
            rows.iter().any(|(keys, description)| keys == "x"
                && *description == "Anchor a range at the cursor, extended with `j` and `k`"),
            "expected the rebound key to appear in the overlay's own content, got: {rows:?}"
        );
        assert!(
            !rows.iter().any(|(keys, _)| keys == "v"),
            "the old default key must not still appear once it has been rebound, got: {rows:?}"
        );
    }

    // --- Criterion (180): every glyph the row interior draws is covered, exhaustively ---

    /// [`Meaning::ALL`] is generated from the same list `crate::glyphs`'s own macro declares
    /// the enum from, so this only proves [`HelpOverlay::legend_rows`] visits every element
    /// of it; `meaning_text`'s own exhaustive match (no `_` arm) is what makes a variant it
    /// cannot describe a compile error rather than a silently missing row.
    #[test]
    fn legend_rows_has_exactly_one_row_per_meaning_variant() {
        let rows = HelpOverlay::legend_rows(full_glyphs());
        assert_eq!(rows.len(), Meaning::ALL.len());
    }

    /// Pinned to [theming.md](../../../../docs/spec/theming.md)'s own "The two sets" table,
    /// read at test time rather than restated: every meaning that table names must appear in
    /// the legend with exactly its own wording, and the legend must name nothing the table
    /// does not. `panel border`, `capture elision`, the header's own `sort arrow` and a
    /// scrollable pane's own `scrollbar` are the table's rows outside the row interior ([`crate::glyphs`]'s own module doc: they are
    /// declared outside the `glyph_set!` macro and carry no `Meaning`), excluded here on the
    /// same terms.
    #[test]
    fn glyph_legend_prose_matches_theming_mds_own_two_sets_table() {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let spec = std::fs::read_to_string(manifest_dir.join("../../docs/spec/theming.md"))
            .expect("read docs/spec/theming.md");

        const HEADING: &str = "### The two sets";
        let after_heading = &spec[spec
            .find(HEADING)
            .expect("theming.md must contain \"### The two sets\"")
            + HEADING.len()..];
        let table_lines: Vec<&str> = after_heading
            .lines()
            .skip_while(|line| !line.trim_start().starts_with('|'))
            .take_while(|line| line.trim_start().starts_with('|'))
            .map(str::trim)
            .collect();
        assert!(
            table_lines.len() > 2,
            "theming.md's \"The two sets\" table has no data rows"
        );

        let spec_meanings: Vec<String> = table_lines[2..]
            .iter()
            .map(|line| {
                let cells: Vec<&str> = line.trim_matches('|').split('|').map(str::trim).collect();
                cells
                    .first()
                    .unwrap_or_else(|| panic!("malformed table row: {line:?}"))
                    .trim_matches('`')
                    .to_string()
            })
            .filter(|meaning| {
                !matches!(
                    meaning.as_str(),
                    "panel border"
                        | "capture elision"
                        | "sort arrow (ascending, descending)"
                        | "scrollbar (track, thumb)"
                )
            })
            .collect();

        let legend_meanings: Vec<&'static str> =
            Meaning::ALL.iter().map(|&m| meaning_text(m)).collect();

        assert_eq!(
            legend_meanings.len(),
            spec_meanings.len(),
            "the legend and theming.md's own table name a different number of meanings: \
             legend {legend_meanings:?}, spec {spec_meanings:?}"
        );
        for spec_meaning in &spec_meanings {
            assert!(
                legend_meanings.contains(&spec_meaning.as_str()),
                "theming.md's \"The two sets\" table names {spec_meaning:?}, which the help \
                 legend does not: {legend_meanings:?}"
            );
        }
    }

    /// Ascii users see ascii glyphs: the legend's own glyph column, read from
    /// [`GlyphSet::row_interior`], differs between the two tables for a meaning the two
    /// tables render differently, and matches each table's own field for that meaning,
    /// read from the table rather than typed in here.
    #[test]
    fn legend_glyphs_are_read_from_the_live_glyph_set_and_differ_between_full_and_ascii() {
        let full_rows = HelpOverlay::legend_rows(full_glyphs());
        let ascii_rows = HelpOverlay::legend_rows(ascii_glyphs());

        let full_in_sync = full_rows
            .iter()
            .find(|(_, meaning)| *meaning == meaning_text(Meaning::InSync))
            .expect("full legend must carry InSync")
            .0
            .clone();
        let ascii_in_sync = ascii_rows
            .iter()
            .find(|(_, meaning)| *meaning == meaning_text(Meaning::InSync))
            .expect("ascii legend must carry InSync")
            .0
            .clone();

        assert_eq!(full_in_sync, full_glyphs().in_sync.to_string());
        assert_eq!(ascii_in_sync, ascii_glyphs().in_sync.to_string());
        assert_ne!(
            full_in_sync, ascii_in_sync,
            "expected the full and ascii legends to render InSync differently, got the same \
             glyph {full_in_sync:?} for both"
        );
    }

    /// The full spinner's ten frames join into one legend row's own glyph text, read from
    /// `glyphs.loading` rather than one frame picked out of it.
    #[test]
    fn the_loading_legend_row_joins_every_spinner_frame_the_live_table_carries() {
        let full_rows = HelpOverlay::legend_rows(full_glyphs());
        let (glyph, _) = full_rows
            .iter()
            .find(|(_, meaning)| *meaning == meaning_text(Meaning::Loading))
            .expect("full legend must carry Loading");
        let expected: String = full_glyphs().loading.iter().collect();
        assert_eq!(*glyph, expected);

        let ascii_rows = HelpOverlay::legend_rows(ascii_glyphs());
        let (ascii_glyph, _) = ascii_rows
            .iter()
            .find(|(_, meaning)| *meaning == meaning_text(Meaning::Loading))
            .expect("ascii legend must carry Loading");
        let ascii_expected: String = ascii_glyphs().loading.iter().collect();
        assert_eq!(*ascii_glyph, ascii_expected);
    }

    // --- Criterion (179): typing filters both the binding list and the legend ---

    #[test]
    fn a_query_matching_a_binding_keeps_it_and_drops_bindings_that_do_not_match() {
        let table = default_table();
        let lines = HelpOverlay::filtered_lines(&table, Context::List, full_glyphs(), "move");
        assert!(lines.iter().any(|line| matches!(
            line,
            HelpLine::Binding { description, .. } if *description == "Move down"
        )));
        assert!(!lines.iter().any(|line| matches!(
            line,
            HelpLine::Binding { description, .. } if *description == "Toggle this row's Selection"
        )));
    }

    #[test]
    fn a_query_matches_the_key_column_as_well_as_the_description() {
        let table = default_table();
        // `g` is List's own "First row" key and matches no other List description, so a hit
        // here can only be the key column, not the description falling through.
        let lines = HelpOverlay::filtered_lines(&table, Context::List, full_glyphs(), "g");
        assert!(lines.iter().any(|line| matches!(
            line,
            HelpLine::Binding { description, .. } if *description == "First row"
        )));
    }

    #[test]
    fn a_query_also_narrows_the_legend_to_glyph_or_meaning_matches() {
        let table = default_table();
        let lines = HelpOverlay::filtered_lines(&table, Context::List, full_glyphs(), "child row");
        let legend_rows: Vec<&HelpLine> = lines
            .iter()
            .filter(|line| matches!(line, HelpLine::Legend { .. }))
            .collect();
        assert_eq!(
            legend_rows.len(),
            1,
            "expected exactly ChildRow to survive: {lines:?}"
        );
        assert!(matches!(
            legend_rows[0],
            HelpLine::Legend { meaning, .. } if *meaning == "child row"
        ));
        assert!(
            lines
                .iter()
                .any(|line| matches!(line, HelpLine::Heading(text) if *text == LEGEND_HEADING)),
            "the legend heading must survive alongside its one surviving row"
        );
    }

    #[test]
    fn an_empty_query_matches_every_binding_and_every_legend_row() {
        let table = default_table();
        let unfiltered = HelpOverlay::lines(&table, Context::List, full_glyphs());
        let filtered = HelpOverlay::filtered_lines(&table, Context::List, full_glyphs(), "");
        assert_eq!(unfiltered, filtered);
    }

    #[test]
    fn a_query_matching_no_binding_and_no_legend_row_leaves_the_legend_heading_out_too() {
        let table = default_table();
        let lines = HelpOverlay::filtered_lines(
            &table,
            Context::List,
            full_glyphs(),
            "zzz-nothing-matches-this-zzz",
        );
        assert!(lines.is_empty(), "expected nothing to match, got {lines:?}");
    }

    // --- Criterion: an empty result set says so rather than rendering blank ---

    #[test]
    fn a_query_matching_nothing_renders_the_no_matches_message() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        for c in "zzz-z".chars() {
            overlay.push_query_char(c);
        }
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &default_table(),
        );
        let buf = terminal.backend().buffer();
        let area = list_area(&overlay, ROOMY_FRAME);
        let row_text: String = (area.x..area.right())
            .map(|x| buf[(x, area.y)].symbol())
            .collect();
        assert!(
            row_text.contains(NO_MATCHES_MESSAGE),
            "expected {NO_MATCHES_MESSAGE:?} on the first list row, got {row_text:?}"
        );
    }

    #[test]
    fn an_unfiltered_overlay_never_renders_the_no_matches_message() {
        let overlay = HelpOverlay::default();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &default_table(),
        );
        let buf = terminal.backend().buffer();
        let area = list_area(&overlay, ROOMY_FRAME);
        let row_text: String = (area.x..area.right())
            .map(|x| buf[(x, area.y)].symbol())
            .collect();
        assert!(!row_text.contains(NO_MATCHES_MESSAGE));
    }

    // --- Criterion: the query is visible on screen, only while it means something ---

    #[test]
    fn the_typed_query_renders_on_the_overlays_own_last_row_while_searching() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        for c in "move".chars() {
            overlay.push_query_char(c);
        }
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &default_table(),
        );
        let buf = terminal.backend().buffer();
        let content_area = HelpLayout::compute(ROOMY_FRAME).content_area(ROOMY_FRAME);
        let last_row = content_area.bottom() - 1;
        let row_text: String = (content_area.x..content_area.right())
            .map(|x| buf[(x, last_row)].symbol())
            .collect();
        assert!(
            row_text.contains("/ move"),
            "expected the query line to show what was typed on the interior's last row, got \
             {row_text:?}"
        );
    }

    /// A fresh, never-searched overlay draws no query line at all: reading mode is the
    /// overlay's original shape, not one that always spends a row on a prompt nobody has
    /// asked for.
    #[test]
    fn a_fresh_overlay_in_reading_mode_draws_no_query_line() {
        let overlay = HelpOverlay::default();
        assert!(!overlay.shows_query_line());
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &default_table(),
        );
        let buf = terminal.backend().buffer();
        let content_area = HelpLayout::compute(ROOMY_FRAME).content_area(ROOMY_FRAME);
        let first_row: String = (content_area.x..content_area.right())
            .map(|x| buf[(x, content_area.y)].symbol())
            .collect();
        assert!(
            !first_row.trim_start().starts_with('/'),
            "expected no query prompt on a fresh overlay's own first row, got {first_row:?}"
        );
    }

    // --- Criterion: search mode transitions ---

    #[test]
    fn a_fresh_overlay_opens_in_reading_mode() {
        let overlay = HelpOverlay::default();
        assert!(!overlay.is_searching());
        assert_eq!(overlay.query(), "");
    }

    #[test]
    fn enter_search_switches_to_searching_without_disturbing_an_existing_query() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        overlay.push_query_char('m');
        overlay.commit_search();
        assert!(!overlay.is_searching());
        assert_eq!(overlay.query(), "m");

        // Re-entering search mode (refining a committed search) keeps the query rather than
        // starting over, the same way `FilterLine::new` reopens prefilled.
        overlay.enter_search();
        assert!(overlay.is_searching());
        assert_eq!(overlay.query(), "m");
    }

    #[test]
    fn cancel_search_returns_to_reading_mode_and_clears_the_query() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        overlay.push_query_char('m');
        overlay.cancel_search();
        assert!(!overlay.is_searching());
        assert_eq!(overlay.query(), "");
    }

    #[test]
    fn commit_search_returns_to_reading_mode_and_keeps_the_query() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        overlay.push_query_char('m');
        overlay.push_query_char('v');
        overlay.commit_search();
        assert!(!overlay.is_searching());
        assert_eq!(overlay.query(), "mv");
    }

    #[test]
    fn typing_snaps_the_scroll_back_to_the_top() {
        let mut overlay = HelpOverlay::default();
        overlay.apply(Action::ScrollDown, 20, 5);
        assert_eq!(overlay.scroll, 1);
        overlay.enter_search();
        overlay.push_query_char('m');
        assert_eq!(overlay.scroll, 0);
    }

    // --- Criterion: `Ctrl+W` removes one trailing whitespace-delimited word from the query,
    // the same pair `filter_line.rs` proves its own `delete_previous_word` with ---

    #[test]
    fn delete_previous_word_removes_one_trailing_whitespace_delimited_word() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        for c in "kind:worktree is:dirty".chars() {
            overlay.push_query_char(c);
        }

        overlay.delete_previous_word();

        assert_eq!(overlay.query(), "kind:worktree ");
    }

    /// macOS Option+Space types U+00A0 NO-BREAK SPACE (two bytes) and U+2003 EM SPACE is
    /// three, so a cut derived by adding one byte to the separator's start lands inside a
    /// character; the accented letters pin that a multi-byte *non*-whitespace character
    /// before the cut survives it.
    #[test]
    fn delete_previous_word_cuts_on_a_character_boundary_after_a_multi_byte_whitespace() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        for c in "café\u{00A0}naïve".chars() {
            overlay.push_query_char(c);
        }

        overlay.delete_previous_word();

        assert_eq!(overlay.query(), "café\u{00A0}");

        for c in "naïve\u{2003}encore".chars() {
            overlay.push_query_char(c);
        }

        overlay.delete_previous_word();

        assert_eq!(overlay.query(), "café\u{00A0}naïve\u{2003}");
    }

    #[test]
    fn delete_previous_word_on_an_empty_query_leaves_it_empty_and_does_not_panic() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();

        overlay.delete_previous_word();

        assert_eq!(overlay.query(), "");
        assert!(overlay.is_searching());
    }

    #[test]
    fn delete_previous_word_snaps_the_scroll_back_to_the_top() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        for c in "move extra".chars() {
            overlay.push_query_char(c);
        }
        overlay.apply(Action::ScrollDown, 20, 5);
        assert_eq!(overlay.scroll, 1);

        overlay.delete_previous_word();

        assert_eq!(overlay.scroll, 0);
    }

    // --- scrolling: the state-transition half, at fixed synthetic viewport heights ---

    #[test]
    fn scroll_down_then_up_returns_to_the_top() {
        let mut overlay = HelpOverlay::default();
        overlay.apply(Action::ScrollDown, 20, 5);
        overlay.apply(Action::ScrollDown, 20, 5);
        assert_eq!(overlay.scroll, 2);
        overlay.apply(Action::ScrollUp, 20, 5);
        assert_eq!(overlay.scroll, 1);
    }

    #[test]
    fn scroll_up_from_the_top_stays_at_the_top() {
        let mut overlay = HelpOverlay::default();
        overlay.apply(Action::ScrollUp, 20, 5);
        assert_eq!(overlay.scroll, 0);
    }

    #[test]
    fn scroll_down_never_passes_the_last_line_reaching_the_viewport() {
        let mut overlay = HelpOverlay::default();
        for _ in 0..50 {
            overlay.apply(Action::ScrollDown, 20, 5);
        }
        assert_eq!(
            overlay.scroll, 15,
            "20 lines in a 5-row viewport clamps at 15"
        );
    }

    #[test]
    fn top_and_bottom_jump_to_the_clamped_ends() {
        let mut overlay = HelpOverlay::default();
        overlay.apply(Action::Bottom, 20, 5);
        assert_eq!(overlay.scroll, 15);
        overlay.apply(Action::Top, 20, 5);
        assert_eq!(overlay.scroll, 0);
    }

    #[test]
    fn an_action_this_overlay_does_not_own_leaves_the_scroll_untouched() {
        let mut overlay = HelpOverlay::default();
        overlay.apply(Action::ScrollDown, 20, 5);
        let scroll_before = overlay.scroll;
        overlay.apply(Action::Close, 20, 5);
        assert_eq!(overlay.scroll, scroll_before);
    }

    // --- viewport height: the border always costs it, the query row only while shown ---

    #[test]
    fn viewport_height_in_reading_mode_with_no_query_only_pays_for_the_border() {
        let overlay = HelpOverlay::default();
        let frame = Rect::new(0, 0, 100, 15);
        let interior = HelpLayout::compute(frame).content_area(frame).height;
        assert_eq!(overlay.viewport_height(frame), interior);
    }

    #[test]
    fn viewport_height_while_searching_pays_for_the_query_row_too() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        let frame = Rect::new(0, 0, 100, 15);
        let interior = HelpLayout::compute(frame).content_area(frame).height;
        assert_eq!(overlay.viewport_height(frame), interior - 1);
    }

    // --- scrolling: rendered, against the overlay's own viewport ---

    /// Scrolls past the end and checks the last line lands on the panel's own last visible
    /// row, not merely that the offset moved. Reading mode, no query, so the viewport is the
    /// panel's own full interior.
    #[test]
    fn scrolling_past_the_end_still_shows_the_last_line_inside_the_border() {
        let table = default_table();
        let context = Context::List;
        let lines = HelpOverlay::lines(&table, context, full_glyphs());
        let content_len = lines.len();
        let frame = Rect::new(0, 0, 100, 15);

        let mut overlay = HelpOverlay::default();
        let viewport_height = overlay.viewport_height(frame);
        assert!(
            (viewport_height as usize) < content_len,
            "fixture sanity: List's real content must exceed a 15-row frame's own interior"
        );
        for _ in 0..content_len {
            overlay.apply(Action::ScrollDown, content_len, viewport_height);
        }

        let terminal = render(&overlay, frame.width, frame.height, context, &table);
        let buf = terminal.backend().buffer();
        let last_line = lines.last().expect("expected at least one content line");
        let last_text = match last_line {
            HelpLine::Binding { description, .. } => description,
            HelpLine::Legend { meaning, .. } => meaning,
            HelpLine::Heading(text) => text,
            HelpLine::Blank => panic!(
                "fixture sanity: the legend always has at least one row, so the last line is \
                 never the blank separator above a heading"
            ),
        };
        let area = list_area(&overlay, frame);
        let last_row_y = area.bottom() - 1;
        let row_text: String = (area.x..area.right())
            .map(|x| buf[(x, last_row_y)].symbol())
            .collect();
        assert!(
            row_text.contains(last_text),
            "expected the last content line {last_text:?} on the panel's own last visible \
             row, got {row_text:?}"
        );
    }

    // --- Criterion: the overlay's keys/description split takes its colour
    // from the theme's own accent/dim roles, theming.md's per-surface assignment ---

    #[test]
    fn draw_paints_a_lines_keys_in_accent_and_its_description_in_dim() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let theme = crate::theme::DEFAULT;
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let lines = HelpOverlay::lines(&table, Context::List, full_glyphs());
        let (row, first_keys, first_description) = lines
            .iter()
            .enumerate()
            .find_map(|(row, line)| match line {
                HelpLine::Binding { keys, description } => Some((row, keys, *description)),
                _ => None,
            })
            .expect("expected at least one binding row");
        let area = list_area(&overlay, ROOMY_FRAME);
        let y = area.y + row as u16;
        assert!(!first_keys.is_empty(), "expected a non-empty first key");
        assert_eq!(
            buf[(area.x, y)].fg,
            theme.role_color(Role::Accent),
            "expected the first binding row's keys painted in the theme's accent role"
        );

        let value_x = find_text_start_x(buf, area, y, first_description);
        assert!(!first_description.is_empty());
        assert_eq!(
            buf[(value_x, y)].fg,
            theme.role_color(Role::Dim),
            "expected the first binding row's description painted in the theme's dim role"
        );
    }

    // --- Criterion (180): the legend section is distinguishable from the binding list ---

    #[test]
    fn the_legend_heading_paints_one_solid_colour_unlike_a_binding_rows_own_two_tone_line() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );
        let buf = terminal.backend().buffer();
        let area = list_area(&overlay, ROOMY_FRAME);

        let lines = HelpOverlay::lines(&table, Context::List, full_glyphs());
        let heading_index = lines
            .iter()
            .position(|line| matches!(line, HelpLine::Heading(text) if *text == LEGEND_HEADING))
            .expect("expected a legend heading line");
        let heading_y = area.y + heading_index as u16;
        let heading_row: String = (area.x..area.right())
            .map(|x| buf[(x, heading_y)].symbol())
            .collect();
        assert!(heading_row.contains(LEGEND_HEADING));

        let heading_start_x = find_text_start_x(buf, area, heading_y, LEGEND_HEADING);
        assert!(
            buf[(heading_start_x, heading_y)]
                .modifier
                .contains(ratatui::style::Modifier::BOLD),
            "expected the legend heading painted bold, unlike any binding or legend row"
        );

        // A binding row's own key cell must not carry that same bold modifier: the heading
        // is what stands apart, not every row on screen.
        let binding_index = lines
            .iter()
            .position(|line| matches!(line, HelpLine::Binding { .. }))
            .expect("expected at least one binding row");
        let binding_y = area.y + binding_index as u16;
        assert!(
            !buf[(area.x, binding_y)]
                .modifier
                .contains(ratatui::style::Modifier::BOLD),
            "expected an ordinary binding row's key cell to carry no bold modifier"
        );
    }

    /// The three sections in the order [keybindings.md](../../../../docs/spec/keybindings.md#the-help-overlay)
    /// fixes: `context`'s own bindings, then `global`'s, then the glyph legend, each under its
    /// own heading with a blank row above every heading but the first. `Context::List` gets a
    /// `global` section ([keybindings.md](../../../../docs/spec/keybindings.md#the-contexts)),
    /// so all three sections are exercised at once.
    #[test]
    fn the_three_sections_appear_in_order_each_under_its_own_heading_with_a_blank_row_between() {
        let table = default_table();
        let context = Context::List;
        let lines = HelpOverlay::lines(&table, context, full_glyphs());

        let own_heading = lines
            .iter()
            .position(
                |line| matches!(line, HelpLine::Heading(text) if *text == context_heading(context)),
            )
            .expect("expected the current context's own heading");
        let global_heading = lines
            .iter()
            .position(|line| matches!(line, HelpLine::Heading(text) if *text == GLOBAL_HEADING))
            .expect("expected List's own `global` section, live alongside it per keybindings.md");
        let legend_heading = lines
            .iter()
            .position(|line| matches!(line, HelpLine::Heading(text) if *text == LEGEND_HEADING))
            .expect("expected a legend heading");
        assert!(
            own_heading < global_heading && global_heading < legend_heading,
            "expected {}, then {GLOBAL_HEADING}, then {LEGEND_HEADING}, got {lines:?}",
            context_heading(context)
        );

        assert_eq!(
            own_heading, 0,
            "expected no blank row above the very first heading"
        );
        assert!(
            matches!(lines[global_heading - 1], HelpLine::Blank),
            "expected a blank row between the own-context section and {GLOBAL_HEADING}'s own \
             heading, got {:?}",
            lines[global_heading - 1]
        );
        assert!(
            matches!(lines[legend_heading - 1], HelpLine::Blank),
            "expected a blank row between the `global` section and {LEGEND_HEADING}'s own \
             heading, got {:?}",
            lines[legend_heading - 1]
        );

        assert!(
            lines[own_heading + 1..global_heading - 1]
                .iter()
                .all(|line| matches!(line, HelpLine::Binding { .. })),
            "expected only binding rows between the own-context heading and the blank row \
             above {GLOBAL_HEADING}, got {lines:?}"
        );
        assert!(
            !lines[own_heading + 1..global_heading - 1].is_empty(),
            "expected at least one of List's own bindings"
        );
        assert!(
            lines[global_heading + 1..legend_heading - 1]
                .iter()
                .all(|line| matches!(line, HelpLine::Binding { .. })),
            "expected only binding rows between {GLOBAL_HEADING}'s own heading and the blank \
             row above {LEGEND_HEADING}, got {lines:?}"
        );
        assert!(
            !lines[global_heading + 1..legend_heading - 1].is_empty(),
            "expected at least one `global` binding"
        );
        assert!(
            lines[legend_heading + 1..]
                .iter()
                .all(|line| matches!(line, HelpLine::Legend { .. })),
            "expected only legend rows after the legend heading"
        );
        assert!(
            !lines[legend_heading + 1..].is_empty(),
            "expected at least one legend row"
        );
    }

    /// A context `global` is suspended in
    /// ([keybindings.md](../../../../docs/spec/keybindings.md#the-contexts)) shows no
    /// `global` section at all, not an empty heading standing over nothing.
    #[test]
    fn a_context_with_no_global_section_shows_no_global_heading() {
        let table = default_table();
        let lines = HelpOverlay::lines(&table, Context::Confirm, full_glyphs());
        assert!(
            !lines
                .iter()
                .any(|line| matches!(line, HelpLine::Heading(text) if *text == GLOBAL_HEADING)),
            "expected Confirm, where global is suspended, to carry no {GLOBAL_HEADING} \
             heading, got {lines:?}"
        );
    }

    // --- Criterion: house-style border and title, at the position the house style puts them ---

    /// The bottom border no longer draws as a plain run once it carries the version
    /// ([`the_bottom_border_carries_the_crates_own_version_right_aligned`]), so this reads
    /// [`crate::test_support::assert_bordered_frame_and_top_title_drawn_with`] rather than
    /// [`crate::test_support::assert_frame_drawn_with`], which every other bordered surface's
    /// own bottom-border-has-nothing-on-it assumption still holds for.
    #[test]
    fn draws_the_house_styles_border_and_a_title_naming_the_overlay_and_its_close_keys() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let glyphs = full_glyphs();

        crate::test_support::assert_bordered_frame_and_top_title_drawn_with(
            buf,
            ROOMY_FRAME,
            glyphs.border,
            BORDER_TITLE,
            "the help overlay's frame",
        );
    }

    /// `keybindings.md`'s own "The help overlay's own chrome" fixes the border and title;
    /// this ticket adds the version to the bottom one, right-aligned.
    #[test]
    fn the_bottom_border_carries_the_crates_own_version_right_aligned() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let outer = ROOMY_FRAME;
        let bottom_y = outer.bottom() - 1;
        let expected = version_title();
        let expected_len = expected.chars().count() as u16;
        let start_x = outer.right() - 1 - expected_len;
        let got: String = (start_x..outer.right() - 1)
            .map(|x| buf[(x, bottom_y)].symbol())
            .collect();
        assert_eq!(
            got, expected,
            "expected the version right-aligned on the bottom border, ending one cell before \
             the right corner"
        );
    }

    // --- Criterion: content draws at the block's own interior origin, not over the border ---

    /// A fresh, reading-mode overlay's first rendered line (a section heading) draws at the
    /// block's own `inner()` origin, not over the border, and not shifted down for a query
    /// line it is not showing.
    #[test]
    fn content_draws_at_the_blocks_own_interior_origin_not_over_the_border_in_reading_mode() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let glyphs = full_glyphs();
        assert_eq!(
            buf[(ROOMY_FRAME.x, ROOMY_FRAME.y)].symbol(),
            glyphs.border.top_left.to_string(),
            "expected the border's own corner untouched by content"
        );

        let lines = HelpOverlay::lines(&table, Context::List, full_glyphs());
        let first_char = leading_char(&lines[0]);
        assert_eq!(
            buf[(ROOMY_FRAME.x + 1, ROOMY_FRAME.y + 1)].symbol(),
            first_char.to_string(),
            "expected the first line's first character at the block's own interior origin"
        );
    }

    /// While searching, the interior's own origin still holds the first content line (a
    /// section heading, here): the query line takes the interior's own *last* row instead,
    /// the same edge the main screen's Filter line sits above its own footer
    /// ([filter.md](../../../../docs/spec/filter.md)), and the list above it just loses that
    /// one row rather than being pushed down from the top.
    #[test]
    fn the_query_line_takes_the_interiors_own_last_row_while_content_keeps_the_origin() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        let table = default_table();
        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let lines = HelpOverlay::lines(&table, Context::List, full_glyphs());
        let first_char = leading_char(&lines[0]);
        assert_eq!(
            buf[(ROOMY_FRAME.x + 1, ROOMY_FRAME.y + 1)].symbol(),
            first_char.to_string(),
            "expected the first content line's own leading character still at the block's own \
             interior origin while searching"
        );

        let content_area = HelpLayout::compute(ROOMY_FRAME).content_area(ROOMY_FRAME);
        let last_row = content_area.bottom() - 1;
        assert_eq!(
            buf[(content_area.x, last_row)].symbol(),
            "/",
            "expected the query line's own leading mark on the interior's own last row"
        );
    }

    // --- Criterion: a fixed gutter, not each line finding its own spacing ---

    /// Finds two real lines of different key length and checks both descriptions land at the
    /// same column.
    #[test]
    fn every_lines_description_starts_at_the_same_column_regardless_of_its_own_keys_length() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let context = Context::List;
        let lines = HelpOverlay::lines(&table, context, full_glyphs());
        let bindings: Vec<(usize, &str, &str)> = lines
            .iter()
            .enumerate()
            .filter_map(|(row, line)| match line {
                HelpLine::Binding { keys, description } => Some((row, keys.as_str(), *description)),
                _ => None,
            })
            .collect();
        let (shortest_row, _, shortest_description) = *bindings
            .iter()
            .min_by_key(|(_, keys, _)| keys.chars().count())
            .expect("expected at least one binding row");
        let (longest_row, longest_keys, longest_description) = *bindings
            .iter()
            .max_by_key(|(_, keys, _)| keys.chars().count())
            .expect("expected at least one binding row");
        assert!(
            bindings
                .iter()
                .any(|(_, keys, _)| keys.chars().count() < longest_keys.chars().count()),
            "fixture sanity: List's own content must have two lines of different key length"
        );

        let terminal = render(
            &overlay,
            ROOMY_FRAME.width,
            ROOMY_FRAME.height,
            context,
            &table,
        );
        let buf = terminal.backend().buffer();
        let area = list_area(&overlay, ROOMY_FRAME);

        let shortest_y = area.y + shortest_row as u16;
        let longest_y = area.y + longest_row as u16;
        let shortest_x = find_text_start_x(buf, area, shortest_y, shortest_description);
        let longest_x = find_text_start_x(buf, area, longest_y, longest_description);
        assert_eq!(
            shortest_x, longest_x,
            "expected both descriptions to start at the same column regardless of their own \
             line's key length"
        );
    }

    // --- Criterion: the gutter is fixed by content, not stretched to fill a wide frame ---

    #[test]
    fn the_gutter_stays_the_same_width_in_a_much_wider_frame_rather_than_stretching_to_fill_it() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let context = Context::List;
        let lines = HelpOverlay::lines(&table, context, full_glyphs());
        let (first_row, first_description) = lines
            .iter()
            .enumerate()
            .find_map(|(row, line)| match line {
                HelpLine::Binding { description, .. } => Some((row, *description)),
                _ => None,
            })
            .expect("expected at least one binding row");

        let narrower = render(&overlay, 100, 40, context, &table);
        let narrower_area = list_area(&overlay, Rect::new(0, 0, 100, 40));
        let narrower_x = find_text_start_x(
            narrower.backend().buffer(),
            narrower_area,
            narrower_area.y + first_row as u16,
            first_description,
        );

        let wider = render(&overlay, 200, 40, context, &table);
        let wider_area = list_area(&overlay, Rect::new(0, 0, 200, 40));
        let wider_x = find_text_start_x(
            wider.backend().buffer(),
            wider_area,
            wider_area.y + first_row as u16,
            first_description,
        );

        assert_eq!(
            narrower_x, wider_x,
            "expected the gutter width to stay fixed rather than stretch with a wider frame"
        );
    }

    // --- Criterion: degrades below a frame too small for a border and any content, both sides ---

    #[test]
    fn degrades_below_the_height_a_border_and_one_content_row_need_both_sides_of_the_boundary() {
        let ample_width = 40;

        let just_tall_enough = Rect::new(0, 0, ample_width, MIN_BORDERED_HEIGHT);
        assert_eq!(HelpLayout::compute(just_tall_enough), HelpLayout::Bordered);

        let one_row_short = Rect::new(0, 0, ample_width, MIN_BORDERED_HEIGHT - 1);
        assert_eq!(HelpLayout::compute(one_row_short), HelpLayout::Degraded);
    }

    #[test]
    fn degrades_below_the_width_a_border_and_one_content_column_need_both_sides_of_the_boundary() {
        let ample_height = 20;

        let just_wide_enough = Rect::new(0, 0, MIN_BORDERED_WIDTH, ample_height);
        assert_eq!(HelpLayout::compute(just_wide_enough), HelpLayout::Bordered);

        let one_column_short = Rect::new(0, 0, MIN_BORDERED_WIDTH - 1, ample_height);
        assert_eq!(HelpLayout::compute(one_column_short), HelpLayout::Degraded);
    }

    #[test]
    fn a_too_small_frame_degrades_to_flush_content_with_no_border_in_reading_mode() {
        let overlay = HelpOverlay::default();
        let table = default_table();
        let tiny_frame = Rect::new(0, 0, 20, MIN_BORDERED_HEIGHT - 1);
        let terminal = render(
            &overlay,
            tiny_frame.width,
            tiny_frame.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let lines = HelpOverlay::lines(&table, Context::List, full_glyphs());
        // With no border and no query line, the first line starts at the frame's own
        // top-left corner, exactly where a border's top-left glyph would otherwise sit.
        let first_char = leading_char(&lines[0]);
        assert_eq!(buf[(0, 0)].symbol(), first_char.to_string());
    }

    /// Degraded and searching, the query line still claims the interior's own last row
    /// (here, `frame_area` itself, one row shorter than reading mode): the list occupies row
    /// `0`, the query row `1`.
    #[test]
    fn a_too_small_frame_degrades_to_flush_query_line_with_no_border_while_searching() {
        let mut overlay = HelpOverlay::default();
        overlay.enter_search();
        let table = default_table();
        let tiny_frame = Rect::new(0, 0, 20, MIN_BORDERED_HEIGHT - 1);
        let terminal = render(
            &overlay,
            tiny_frame.width,
            tiny_frame.height,
            Context::List,
            &table,
        );

        let buf = terminal.backend().buffer();
        let query_y = tiny_frame.bottom() - 1;
        assert_eq!(buf[(0, query_y)].symbol(), "/");
    }

    // --- Criterion: a wide enough frame lays the content out in two columns ---

    /// A section with `row_count` synthetic binding rows under `heading`, for the splitting
    /// tests below: their own content does not matter, only how many lines each section
    /// costs.
    fn synthetic_section(heading: &'static str, row_count: usize) -> (&'static str, Vec<HelpLine>) {
        (
            heading,
            (0..row_count)
                .map(|i| HelpLine::Binding {
                    keys: i.to_string(),
                    description: "row",
                })
                .collect(),
        )
    }

    /// [`ColumnMetrics::compute`]'s own two-column threshold for `context`'s content: the
    /// content_width right at which `two_columns` first turns on, from the same split and
    /// per-column widths ([`ColumnMetrics::column_metrics`]) `compute` itself uses, rather
    /// than hard-coded, so this stays correct if `context`'s own bindings or descriptions
    /// ever change length.
    fn two_column_threshold(table: &BindingTable, context: Context, glyphs: &GlyphSet) -> u16 {
        let unfiltered = HelpOverlay::built_sections(table, context, glyphs, "");
        let (left, right) = HelpOverlay::split_into_columns(unfiltered);
        let (_, _, left_width, right_width) = ColumnMetrics::column_metrics(&left, &right);
        left_width + COLUMN_GUTTER + right_width
    }

    #[test]
    fn assembled_len_counts_each_sections_own_heading_and_content_plus_one_blank_between_sections()
    {
        let sections = vec![synthetic_section("A", 2), synthetic_section("B", 3)];
        // A: 1 heading + 2 rows = 3. B: 1 heading + 3 rows = 4. One blank between them = 8.
        assert_eq!(HelpOverlay::assembled_len(&sections), 8);
        assert_eq!(HelpOverlay::assembled_len(&sections[..1]), 3);
        assert_eq!(HelpOverlay::assembled_len(&sections[..0]), 0);
    }

    /// `heading`'s own content must immediately follow its heading in `column`, contiguous and
    /// in order: the shape [`HelpOverlay::split_into_columns`] must never break, whichever
    /// column a section lands in.
    fn assert_section_whole_in(column: &[HelpLine], heading: &'static str, content: &[HelpLine]) {
        let heading_index = column
            .iter()
            .position(|line| matches!(line, HelpLine::Heading(h) if *h == heading))
            .unwrap_or_else(|| panic!("expected heading {heading:?} in {column:?}"));
        assert_eq!(
            &column[heading_index + 1..heading_index + 1 + content.len()],
            content,
            "expected {heading:?}'s own content immediately after its own heading in {column:?}"
        );
    }

    #[test]
    fn split_into_columns_keeps_every_sections_heading_together_with_its_own_content() {
        let sections = vec![
            synthetic_section("A", 2),
            synthetic_section("B", 20),
            synthetic_section("C", 3),
        ];
        let (left, right) = HelpOverlay::split_into_columns(sections.clone());
        for (heading, content) in &sections {
            let column = if left
                .iter()
                .any(|line| matches!(line, HelpLine::Heading(h) if h == heading))
            {
                &left
            } else {
                &right
            };
            assert_section_whole_in(column, heading, content);
        }
    }

    /// A, B, C cost 3, 21 and 4 assembled lines on their own. Every whole-section boundary:
    /// `[]|[A,B,C]` (diff 30), `[A]|[B,C]` (diff 23), `[A,B]|[C]` (diff 21), `[A,B,C]|[]`
    /// (diff 30). `[A,B]|[C]` is the closest, so B's own bulk lands with A on the left rather
    /// than forcing a near-even split some other way: sections are never split internally to
    /// chase a better balance.
    #[test]
    fn split_into_columns_chooses_the_section_boundary_that_balances_total_line_count_most_closely()
    {
        let sections = vec![
            synthetic_section("A", 2),
            synthetic_section("B", 20),
            synthetic_section("C", 3),
        ];
        let (left, right) = HelpOverlay::split_into_columns(sections);

        assert!(
            left.iter()
                .any(|line| matches!(line, HelpLine::Heading("A")))
        );
        assert!(
            left.iter()
                .any(|line| matches!(line, HelpLine::Heading("B")))
        );
        assert!(
            right
                .iter()
                .any(|line| matches!(line, HelpLine::Heading("C")))
        );
        assert!(
            !right
                .iter()
                .any(|line| matches!(line, HelpLine::Heading("A") | HelpLine::Heading("B")))
        );
        assert_eq!(
            left.len(),
            25,
            "expected A and B assembled together: {left:?}"
        );
        assert_eq!(right.len(), 4, "expected C alone: {right:?}");
    }

    /// One section that survives (a query narrow enough that only it matches anything) cannot
    /// be split at all: every boundary puts it whole in one column and leaves the other empty.
    /// This is what a single section "too tall" for a balanced split degrades to in the
    /// extreme: the split stays whole-section, it just cannot make the lone section's own
    /// bulk disappear, so the overlay ends up one column wide in every way that matters even
    /// though the frame fits two.
    #[test]
    fn split_into_columns_puts_a_lone_surviving_section_whole_in_the_left_column() {
        let sections = vec![synthetic_section("Only", 30)];
        let expected = HelpOverlay::assemble_sections(sections.clone());

        let (left, right) = HelpOverlay::split_into_columns(sections);

        assert_eq!(left, expected);
        assert!(
            right.is_empty(),
            "expected the right column empty: {right:?}"
        );
    }

    #[test]
    fn column_metrics_stays_one_column_below_the_threshold_and_switches_to_two_right_at_it() {
        let table = default_table();
        let context = Context::List;
        let glyphs = full_glyphs();
        let threshold = two_column_threshold(&table, context, glyphs);

        let below = ColumnMetrics::compute(&table, context, glyphs, threshold - 1);
        assert!(
            !below.two_columns,
            "expected one column just under the threshold ({threshold})"
        );

        let at = ColumnMetrics::compute(&table, context, glyphs, threshold);
        assert!(
            at.two_columns,
            "expected two columns right at the threshold ({threshold})"
        );
    }

    /// The concrete regression this ticket fixes: at a real 161-column terminal, the default
    /// List content, full glyphs, must reach two columns. Before this fix the threshold doubled
    /// the single widest line across the whole table (172, unreachable at any width a real
    /// terminal is likely to run) instead of sizing each column against its own content.
    #[test]
    fn a_real_161_column_terminal_lays_out_the_default_list_content_in_two_columns() {
        let table = default_table();
        let context = Context::List;
        let glyphs = full_glyphs();
        let frame = Rect::new(0, 0, 161, 40);

        let content_width = HelpLayout::compute(frame).content_area(frame).width;
        let metrics = ColumnMetrics::compute(&table, context, glyphs, content_width);
        assert!(
            metrics.two_columns,
            "expected a 161-column terminal ({content_width} content columns) to reach two \
             columns for List's own content"
        );

        let sections = HelpOverlay::built_sections(&table, context, glyphs, "");
        let (left, right) = HelpOverlay::laid_out(sections, &metrics);
        assert!(
            !left.is_empty() && !right.is_empty(),
            "expected both columns to hold content, got left={left:?} right={right:?}"
        );
    }

    /// A query narrow enough to leave only the legend section standing still renders one
    /// column, even though the frame is wide enough for two: [`Self::split_into_columns`]'s
    /// own "a lone surviving section cannot be split" rule, exercised through the real table
    /// and a real query rather than synthetic sections.
    #[test]
    fn a_query_leaving_only_the_legend_stays_one_column_even_at_a_frame_wide_enough_for_two() {
        let table = default_table();
        let context = Context::List;
        let glyphs = full_glyphs();
        let threshold = two_column_threshold(&table, context, glyphs);
        let frame = Rect::new(0, 0, threshold + BORDER_WIDTH, 40);

        let sections = HelpOverlay::built_sections(&table, context, glyphs, "child row");
        assert_eq!(
            sections.len(),
            1,
            "fixture sanity: \"child row\" must match only the legend's own ChildRow row"
        );
        let content_width = HelpLayout::compute(frame).content_area(frame).width;
        let metrics = ColumnMetrics::compute(&table, context, glyphs, content_width);
        assert!(
            metrics.two_columns,
            "fixture sanity: the frame must be wide enough for two columns"
        );

        let (left, right) = HelpOverlay::laid_out(sections, &metrics);
        assert!(
            left.iter()
                .any(|line| matches!(line, HelpLine::Heading(h) if *h == LEGEND_HEADING)),
            "expected the lone surviving section whole in the left column: {left:?}"
        );
        assert!(
            right.is_empty(),
            "expected the right column empty: {right:?}"
        );
    }

    /// At a frame wide enough for two columns, List's own real content splits List's own
    /// bindings and `global`'s together into the left column and the legend alone into the
    /// right one (the same boundary [`split_into_columns_chooses_the_section_boundary_that_balances_total_line_count_most_closely`]
    /// proves the algorithm picks in the abstract), and `draw` paints them at the two
    /// x-offsets [`ColumnMetrics::compute`] derives.
    #[test]
    fn draw_lays_two_columns_side_by_side_at_a_frame_wide_enough_for_them() {
        let table = default_table();
        let context = Context::List;
        let glyphs = full_glyphs();
        let threshold = two_column_threshold(&table, context, glyphs);
        let frame = Rect::new(0, 0, threshold + BORDER_WIDTH, 60);

        let sections = HelpOverlay::built_sections(&table, context, glyphs, "");
        let content_width = HelpLayout::compute(frame).content_area(frame).width;
        let metrics = ColumnMetrics::compute(&table, context, glyphs, content_width);
        assert!(
            metrics.two_columns,
            "fixture sanity: this frame must fit two columns"
        );
        let (left, right) = HelpOverlay::laid_out(sections, &metrics);
        assert!(
            !right.is_empty(),
            "fixture sanity: the legend must land in its own column"
        );
        assert!(
            matches!(right[0], HelpLine::Heading(LEGEND_HEADING)),
            "expected no wasted blank row above the right column's own first heading: {right:?}"
        );
        assert!(
            left.len() > right.len(),
            "fixture sanity: List's own bindings plus global must outlast the legend alone"
        );

        let overlay = HelpOverlay::default();
        let terminal = render(&overlay, frame.width, frame.height, context, &table);
        let buf = terminal.backend().buffer();
        let area = list_area(&overlay, frame);

        let first_left_char = leading_char(&left[0]);
        assert_eq!(
            buf[(area.x, area.y)].symbol(),
            first_left_char.to_string(),
            "expected the left column's own first line at the list's own origin"
        );

        let first_right_char = leading_char(&right[0]);
        assert_eq!(
            buf[(area.x + metrics.column_offset, area.y)].symbol(),
            first_right_char.to_string(),
            "expected the right column's own first line one column_offset to the right"
        );

        // Once the shorter (right) column runs out of rows, the left column keeps going and
        // nothing stray is painted where the right column used to be.
        let exhausted_row = right.len();
        assert!(
            exhausted_row < left.len(),
            "fixture sanity: the left column must outlast the right one"
        );
        let y = area.y + exhausted_row as u16;
        assert_eq!(
            buf[(area.x + metrics.column_offset, y)].symbol(),
            " ",
            "expected nothing painted in the right column once it runs out of rows"
        );
        assert_eq!(
            buf[(area.x, y)].symbol(),
            rendered_symbol(&left[exhausted_row]),
            "expected the left column to keep going past where the right one ran out"
        );
    }

    /// The scroll clamp folds against the taller column's own row count
    /// ([`HelpOverlay::visible_len`]), not the flat line total every section would sum to in
    /// one column: at a frame wide enough for two columns, the two must differ, and
    /// `visible_len` must agree with a lay-out built by hand from the same sections and
    /// metrics.
    #[test]
    fn visible_len_at_a_wide_frame_is_the_taller_columns_own_row_count_not_the_flat_total() {
        let table = default_table();
        let context = Context::List;
        let glyphs = full_glyphs();
        let threshold = two_column_threshold(&table, context, glyphs);
        let frame = Rect::new(0, 0, threshold + BORDER_WIDTH, 60);

        let flat_total = HelpOverlay::filtered_lines(&table, context, glyphs, "").len();
        let visible = HelpOverlay::visible_len(&table, context, glyphs, "", frame);
        assert!(
            visible < flat_total,
            "expected the two-column row count ({visible}) below the flat total \
             ({flat_total})"
        );

        let sections = HelpOverlay::built_sections(&table, context, glyphs, "");
        let content_width = HelpLayout::compute(frame).content_area(frame).width;
        let metrics = ColumnMetrics::compute(&table, context, glyphs, content_width);
        let (left, right) = HelpOverlay::laid_out(sections, &metrics);
        assert_eq!(visible, left.len().max(right.len()));
    }
}