zshrs 0.11.5

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
//! Completion listing display for ZLE
//!
//! Port from zsh/Src/Zle/complist.c (3,604 lines)
//!
//! Information about the list shown.                                        // c:34
//! Information for in-string colours.                                       // c:133
//! This holds all terminal strings.                                         // c:243
//! Get the terminal color string for the given match.                       // c:878
//! The widget function.                                                     // c:3481
//!
//! The full menu/listing system is in compsys/menu.rs (3,445 lines).
//! This module provides the ZLE-side rendering that displays completion
//! matches in columns with colors, scrolling, and selection.
//!
//! Key C functions and their Rust locations:
//! - compprintlist    → compsys::menu::MenuState::render()
//! - compprintfmt     → compsys::menu::format_group()
//! - clprintm         → compsys::menu::print_match()
//! - asklistscroll    → compsys::menu::handle_scroll()
//! - getcols/filecol  → compsys::zpwr_colors (LS_COLORS parsing)
//! - initiscol        → compsys::zpwr_colors::init_colors()

use std::collections::HashMap;

// `ListColors` / `ListLayout` and their Rust-only methods deleted.
// The C source uses `struct listcols` (legit port at line 645 as
// `listcols`, c:253) plus file-scope `int columns, lines` globals
// for the layout — no separate layout struct. Real `getcols()`,
// `filecol()`, `calclist()` ports live below using those types.
//
// `calclist` here had the wrong C signature: real C `void
// calclist(int showall)` at compresult.c:1495 takes one int; the
// previous Rust placeholder took `(matches, term_width, descs)` and
// returned a `ListLayout`. Real port pending.

// --- AUTO: cross-zle hoisted-fn use glob ---
#[allow(unused_imports)]
#[allow(unused_imports)]
use crate::ported::zle::zle_main::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_misc::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_hist::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_move::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_word::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_params::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_vi::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_utils::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_refresh::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_tricky::*;
#[allow(unused_imports)]
use crate::ported::zle::textobjects::*;
#[allow(unused_imports)]
use crate::ported::zle::deltochar::*;

/// Port of `MMARK` from `Src/Zle/complist.c:126`. Tag bit used in
/// the low bit of `Cmatch *` / `Cmgroup` pointers to mark a match
/// as visited during the menu-select / hidden-row dispatch. Real C
/// uses pointer tagging; the Rust port uses the same bit position
/// (`u32 = 1`) as a search-anchor — actual marker storage lives on
/// a separate `bool` per Cmatch when the substrate hydrates.
pub const MMARK: u32 = 1;                                                    // c:126

/// Port of `MAX_POS` from `Src/Zle/complist.c:137`. Maximum number
/// of saved (mline, mcol) menu-select positions in the back-stack
/// used by msearchpush/msearchpop.
pub const MAX_POS: usize = 11;                                               // c:137

// =====================================================================
// Substrate for the LS_COLORS / ZLS_COLORS subsystem —
// `Src/Zle/complist.c:165-269`.
// =====================================================================

// `COL_*` — index into `mcolors.files[]` per `Src/Zle/complist.c:167-194`.
pub const COL_NO:  usize = 0;                                                // c:167
pub const COL_FI:  usize = 1;                                                // c:168
pub const COL_DI:  usize = 2;                                                // c:169
pub const COL_LN:  usize = 3;                                                // c:170
pub const COL_PI:  usize = 4;                                                // c:171
pub const COL_SO:  usize = 5;                                                // c:172
pub const COL_BD:  usize = 6;                                                // c:173
pub const COL_CD:  usize = 7;                                                // c:174
pub const COL_OR:  usize = 8;                                                // c:175
pub const COL_MI:  usize = 9;                                                // c:176
pub const COL_SU:  usize = 10;                                               // c:177
pub const COL_SG:  usize = 11;                                               // c:178
pub const COL_TW:  usize = 12;                                               // c:179
pub const COL_OW:  usize = 13;                                               // c:180
pub const COL_ST:  usize = 14;                                               // c:181
pub const COL_EX:  usize = 15;                                               // c:182
pub const COL_LC:  usize = 16;                                               // c:183
pub const COL_RC:  usize = 17;                                               // c:184
pub const COL_EC:  usize = 18;                                               // c:185
pub const COL_TC:  usize = 19;                                               // c:186
pub const COL_SP:  usize = 20;                                               // c:187
pub const COL_MA:  usize = 21;                                               // c:188
pub const COL_HI:  usize = 22;                                               // c:189
pub const COL_DU:  usize = 23;                                               // c:190
pub const COL_SA:  usize = 24;                                               // c:191
/// Port of `NUM_COLS` from `Src/Zle/complist.c:193`.
pub const NUM_COLS: usize = 25;                                              // c:193

/// ```c
/// static filecol
/// filecol(char *col)
/// {
///     filecol fc;
///     fc = (filecol) zhalloc(sizeof(*fc));
///     fc->prog = NULL;
///     fc->col = col;
///     fc->next = NULL;
///     return fc;
/// }
/// ```
/// Allocate a fresh filecol with no group pattern and the given
/// color string. Caller is expected to chain it via `mcolors.files[i]`.
/// Port of `filecol(char *col)` from `Src/Zle/complist.c:488`.
pub fn filecol(col: &str) -> filecol {                                       // c:488
    filecol {                                                                // c:488 zhalloc
        prog: None,                                                          // c:493 fc->prog = NULL
        col:  col.to_string(),                                               // c:494 fc->col = col
        next: None,                                                          // c:495 fc->next = NULL
    }                                                                        // c:497 return fc
}

/// Port of `struct filecol` / `typedef struct filecol *filecol` from
/// `Src/Zle/complist.c:213-219`. One terminal-color spec for a file
/// type; chained via `next` so multiple per-group rules can apply.
///
/// `prog` mirrors C's `Patprog prog` (NULL → applies to all groups).
/// Patprog doesn't impl Debug/Clone in the Rust port, so this struct
/// can't auto-derive them; impl manually if needed by callers.
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct filecol {                                                         // c:215
    /// Group pattern (NULL → applies to all groups).
    pub prog: Option<crate::ported::zsh_h::Patprog>,                         // c:216
    /// Color string (ANSI escape-code body).
    pub col: String,                                                         // c:217
    /// Next entry chained for the same color slot.
    pub next: Option<Box<filecol>>,                                          // c:218
}

/// Port of `struct patcol` from `Src/Zle/complist.c:225`. Per-pattern
/// terminal-color spec — links a glob `pat` to up to MAX_POS+1 color
/// strings (one per submatch position).
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct patcol {                                                          // c:225
    /// Group pattern (NULL → all groups).
    pub prog: Option<crate::ported::zsh_h::Patprog>,                         // c:226
    /// Pattern for match.
    pub pat: Option<crate::ported::zsh_h::Patprog>,                          // c:227
    /// Color strings indexed by submatch position (MAX_POS + 1 slots).
    pub cols: Vec<String>,                                                   // c:228
    /// Next entry in the patcol chain.
    pub next: Option<Box<patcol>>,                                           // c:229
}

/// Port of `struct extcol` from `Src/Zle/complist.c:236`. Per-extension
/// terminal-color spec.
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct extcol {                                                          // c:236
    /// Group pattern (NULL → all groups).
    pub prog: Option<crate::ported::zsh_h::Patprog>,                         // c:237
    /// File extension (e.g. ".tar").
    pub ext: String,                                                         // c:238
    /// Terminal color string.
    pub col: String,                                                         // c:239
    /// Next entry in the extcol chain.
    pub next: Option<Box<extcol>>,                                           // c:240
}

/// Port of `struct listcols` from `Src/Zle/complist.c:253`. Holds
/// every terminal-color string a completion-listing run might emit.
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct listcols {                                                        // c:253
    /// Strings for file types (indexed by `col::*` constants).
    pub files: Vec<filecol>,                                                 // c:254 [NUM_COLS]
    /// Strings for patterns.
    pub pats: Option<Box<patcol>>,                                           // c:255
    /// Strings for extensions.
    pub exts: Option<Box<extcol>>,                                           // c:256
    /// Special settings, see `LC_FOLLOW_SYMLINKS` above.
    pub flags: i32,                                                          // c:257
}

/// Port of `getcolval(char *s, int multi)` from Src/Zle/complist.c:275.
#[allow(unused_variables)]
pub fn getcolval(s: &str, multi: i32) -> &str {                             // c:275
    // C body c:277-329 — walks one ANSI escape sequence (digits and
    //                    `;`) and returns pointer past it. Used while
    //                    parsing `key=val` from LS_COLORS.
    let trimmed = s.trim_start_matches(|c: char| c.is_ascii_digit() || c == ';');
    trimmed
}

/// Port of `getcoldef(char *s)` from Src/Zle/complist.c:330.
pub fn getcoldef(s: &str) -> Option<String> {                                // c:330
    // C body c:332-503 — parses one "key=val" entry from LS_COLORS
    //                    /ZLS_COLORS, walks past the key (one of the
    //                    `colnames` two-letters, plus filename
    //                    suffixes "*.ext", patterns "=cls"), returns
    //                    pointer past the entry. Without the mcolors
    //                    install we just split on the first `:` and
    //                    return the remainder so caller can iterate.
    s.split_once(':').map(|(_, rest)| rest.to_string())
}

/// Port of `static void getcols(void)` from `Src/Zle/complist.c:505`.
/// ```c
/// static void
/// getcols(void)
/// {
///     char *s;
///     int i, l;
///     max_caplen = lr_caplen = 0;
///     mcolors.flags = 0;
///     queue_signals();
///     if (!(s = getsparam_u("ZLS_COLORS")) && !(s = getsparam_u("ZLS_COLOURS"))) {
///         for (i = 0; i < NUM_COLS; i++) mcolors.files[i] = filecol("");
///         mcolors.pats = NULL; mcolors.exts = NULL;
///         if ((s = tcstr[TCSTANDOUTBEG]) && s[0]) {
///             mcolors.files[COL_MA] = filecol(s);
///             mcolors.files[COL_EC] = filecol(tcstr[TCSTANDOUTEND]);
///         } else mcolors.files[COL_MA] = filecol(defcols[COL_MA]);
///         lr_caplen = 0;
///         if ((max_caplen = strlen(mcolors.files[COL_MA]->col)) <
///             (l = strlen(mcolors.files[COL_EC]->col))) max_caplen = l;
///         unqueue_signals(); return;
///     }
///     memset(&mcolors, 0, sizeof(mcolors));
///     s = dupstring(s);
///     while (*s) if (*s == ':') s++; else s = getcoldef(s);
///     unqueue_signals();
///     for (i = 0; i < NUM_COLS; i++) {
///         if (!mcolors.files[i] || !mcolors.files[i]->col)
///             mcolors.files[i] = filecol(defcols[i]);
///         if (mcolors.files[i] && mcolors.files[i]->col &&
///             (l = strlen(mcolors.files[i]->col)) > max_caplen) max_caplen = l;
///     }
///     lr_caplen = strlen(mcolors.files[COL_LC]->col) +
///                 strlen(mcolors.files[COL_RC]->col);
///     if (!mcolors.files[COL_OR] || !mcolors.files[COL_OR]->col)
///         mcolors.files[COL_OR] = mcolors.files[COL_LN];
///     if (!mcolors.files[COL_MI] || !mcolors.files[COL_MI]->col)
///         mcolors.files[COL_MI] = mcolors.files[COL_FI];
/// }
/// ```
pub fn getcols(_unused: &str) -> i32 {                                       // c:505
    use std::sync::atomic::Ordering;

    MAX_CAPLEN.store(0, Ordering::SeqCst);                                   // c:510
    LR_CAPLEN.store(0, Ordering::SeqCst);                                    // c:510
    {
        let mut mc = MCOLORS.lock().unwrap();
        mc.flags = 0;                                                        // c:511
    }
    crate::ported::signals::queue_signals();                                 // c:512

    // c:513-514 — `if (!(s = getsparam_u("ZLS_COLORS")) && !(s = getsparam_u("ZLS_COLOURS")))`
    let s_opt = crate::ported::params::getsparam("ZLS_COLORS")
        .or_else(|| crate::ported::params::getsparam("ZLS_COLOURS"));

    if s_opt.is_none() {                                                     // c:513
        let mut mc = MCOLORS.lock().unwrap();
        mc.files.clear();
        for _i in 0..NUM_COLS {                                              // c:515
            mc.files.push(filecol(""));                                      // c:516 filecol("")
        }
        mc.pats = None;                                                      // c:517
        mc.exts = None;                                                      // c:518

        // c:520-524 — try termcap TCSTANDOUTBEG for highlight color.
        let tcstr_guard = crate::ported::init::tcstr.lock().unwrap();
        let so_beg = tcstr_guard[crate::ported::zsh_h::TCSTANDOUTBEG as usize].clone();
        let so_end = tcstr_guard[crate::ported::zsh_h::TCSTANDOUTEND as usize].clone();
        drop(tcstr_guard);
        if !so_beg.is_empty() {                                              // c:520
            mc.files[COL_MA] = filecol(&so_beg);                             // c:521
            mc.files[COL_EC] = filecol(&so_end);                             // c:522
        } else {                                                             // c:523
            // c:524 — `mcolors.files[COL_MA] = filecol(defcols[COL_MA]);`
            // defcols[COL_MA] = "7" (reverse-video) per c:204.
            mc.files[COL_MA] = filecol("7");                                 // c:524
        }
        // c:525-528 — cap-length tracking.
        let ma_len = mc.files[COL_MA].col.len() as i32;
        let ec_len = mc.files[COL_EC].col.len() as i32;
        let max_len = if ma_len < ec_len { ec_len } else { ma_len };
        MAX_CAPLEN.store(max_len, Ordering::SeqCst);                         // c:526-528
        crate::ported::signals::unqueue_signals();                           // c:529
        return 0;                                                            // c:530
    }

    // c:532-540 — parse ZLS_COLORS into mcolors via getcoldef loop.
    {
        let mut mc = MCOLORS.lock().unwrap();
        *mc = listcols::default();                                           // c:533 memset(&mcolors, 0)
    }
    let mut s = s_opt.unwrap();                                              // c:534 dupstring
    while !s.is_empty() {                                                    // c:535
        if s.starts_with(':') {                                              // c:536
            s = s[1..].to_string();                                          // c:537 s++
        } else {
            // c:539 — `s = getcoldef(s);`
            s = match getcoldef(&s) {
                Some(rest) => rest,
                None => break,
            };
        }
    }
    crate::ported::signals::unqueue_signals();                               // c:540

    // c:543-549 — default-fill loop for unset color slots.
    let defcols: [&str; NUM_COLS] = [
        "0", "0", "01;34", "01;36", "33", "01;35", "01;33", "01;33",
        "01;05;37;41", "01;05;37;41", "37;41", "30;43", "30;42", "34;42",
        "37;44", "01;32", "\x1b[", "m", "0", "0", "0", "7", "0", "0", "0",
    ];
    let mut mc = MCOLORS.lock().unwrap();
    while mc.files.len() < NUM_COLS {
        mc.files.push(filecol(""));
    }
    let mut max_len = MAX_CAPLEN.load(Ordering::SeqCst);
    for i in 0..NUM_COLS {                                                   // c:543
        if mc.files[i].col.is_empty() {                                      // c:544
            mc.files[i] = filecol(defcols[i]);                               // c:545
        }
        let l = mc.files[i].col.len() as i32;                                // c:547
        if l > max_len { max_len = l; }                                      // c:548
    }
    MAX_CAPLEN.store(max_len, Ordering::SeqCst);

    // c:550-551 — lr_caplen.
    let lr_len = (mc.files[COL_LC].col.len() + mc.files[COL_RC].col.len()) as i32;
    LR_CAPLEN.store(lr_len, Ordering::SeqCst);

    // c:553-558 — defaults: COL_OR fallback to COL_LN; COL_MI to COL_FI.
    if mc.files[COL_OR].col.is_empty() {                                     // c:554
        let ln = mc.files[COL_LN].col.clone();
        mc.files[COL_OR] = filecol(&ln);                                     // c:555
    }
    if mc.files[COL_MI].col.is_empty() {                                     // c:557
        let fi = mc.files[COL_FI].col.clone();
        mc.files[COL_MI] = filecol(&fi);                                     // c:558
    }
    0                                                                        // c:560
}

/// Direct port of `void zlrputs(char *cap)` from
/// `Src/Zle/complist.c:564`. Emits an LS_COLORS escape
/// `\033[<cap>m` to the shell-output fd. C body c:566-595 also
/// stores the cap into `last_cap` for the bleed-prevention path
/// downstream (used by `zcoff` in `cleareol`); that file-static
/// `last_cap` isn't yet ported, so we only emit the SGR escape.
pub fn zlrputs(cap: &str) -> i32 {                                           // c:564
    use std::sync::atomic::Ordering;
    if cap.is_empty() {
        return 0;
    }
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out = if fd >= 0 { fd } else { 1 };
    let s = format!("\x1b[{}m", cap);
    let _ = crate::ported::utils::write_loop(out, s.as_bytes());
    0
}

/// Wrap a string in a CSI SGR sequence using the supplied colour
/// code, then reset.
/// Port of `zcputs(char *group, int colour)` from Src/Zle/complist.c. The C source uses
/// this for per-match colour application during list paint.
/// WARNING: param names don't match C — Rust=(s, color) vs C=(group, colour)
pub fn zcputs(s: &str, color: Option<&str>) -> String {                      // c:580
    match color {
        Some(c) => format!("\x1b[{}m{}\x1b[0m", c, s),
        None => s.to_string(),
    }
}



// Turn off colouring.                                                     // c:597
/// Port of `zcoff()` from Src/Zle/complist.c:597.
pub fn zcoff() {                                                            // c:597
    // C body c:599-617 — emits the LS_COLORS no-color escape via
    //                    tputs(mcolors.files[COL_NO]->col,...).
    //                    No mcolors substrate: no-op.
}

/// Direct port of `void cleareol(void)` from
/// `Src/Zle/complist.c:608`:
/// ```c
/// if (mlbeg >= 0 && tccan(TCCLEAREOL)) {
///     if (*last_cap) zcoff();
///     tcout(TCCLEAREOL);
/// }
/// ```
/// Emits the clear-to-end-of-line escape iff we're inside list
/// paint (`mlbeg >= 0`) and the terminal supports the cap. If a
/// LS_COLOR cap is currently active, emit the SGR-reset first so
/// the EOL-clear doesn't carry the color into untouched columns.
pub fn cleareol() {                                                          // c:608
    use std::sync::atomic::Ordering;
    if MLBEG.load(Ordering::Relaxed) < 0 {
        return;
    }
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out = if fd >= 0 { fd } else { 1 };
    // c:611-612 — `if (*last_cap) zcoff();` — emit SGR reset.
    if !LAST_CAP.lock().map(|s| s.is_empty()).unwrap_or(true) {
        let _ = crate::ported::utils::write_loop(out, b"\x1b[0m");
        LAST_CAP.lock().ok().map(|mut s| s.clear());
    }
    // c:613 — `tcout(TCCLEAREOL);` — CSI K.
    let _ = crate::ported::utils::write_loop(out, b"\x1b[K");
}

/// Port of `initiscol()` from Src/Zle/complist.c:618.
/// Direct port of `void initiscol(void)` from
/// `Src/Zle/complist.c:618`. Resets per-line in-string-color state
/// at the start of a colored match emission. Pops the first
/// `patcols[0]` entry as the initial color and resets all the
/// position cursors + region-tracking arrays.
pub fn initiscol() -> i32 {                                                  // c:618
    use std::sync::atomic::Ordering;
    // c:622 — `zlrputs(patcols[0]);` — emit first color cap.
    let first_cap = PATCOLS.lock().ok()
        .and_then(|p| p.first().cloned())
        .unwrap_or_default();
    if !first_cap.is_empty() {
        let _ = zlrputs(&first_cap);
    }
    // c:624 — `curiscols[curiscol = 0] = *patcols++;`
    if let Ok(mut cs) = CURISCOLS.lock() {
        if !cs.is_empty() {
            cs[0] = first_cap.clone();
        }
    }
    CURISCOL.store(0, Ordering::Relaxed);
    PATCOLS_IDX.store(1, Ordering::Relaxed);                                 // c:624 patcols++

    // c:626 — `curisbeg = curissend = 0;`
    CURISBEG.store(0, Ordering::Relaxed);
    CURISSEND.store(0, Ordering::Relaxed);

    // c:628-631 — sendpos / begpos / endpos init.
    let nrefs = NREFS.load(Ordering::Relaxed) as usize;
    if let Ok(mut sp) = SENDPOS.lock() {
        for i in 0..MAX_POS {
            sp[i] = 0xfffffff;
        }
        for i in 0..nrefs.min(MAX_POS) {
            sp[i] = 0xfffffff;                                              // c:629 already 0xfffffff
        }
    }
    if let Ok(mut bp) = BEGPOS.lock() {
        for i in nrefs..MAX_POS {
            bp[i] = 0xfffffff;                                              // c:631
        }
    }
    if let Ok(mut ep) = ENDPOS.lock() {
        for i in nrefs..MAX_POS {
            ep[i] = 0xfffffff;                                              // c:631
        }
    }
    0
}

/// Port of `doiscol(int pos)` from Src/Zle/complist.c:635.
/// Direct port of `void doiscol(int pos)` from
/// `Src/Zle/complist.c:635`. Updates the in-string color state for
/// character position `pos` in the current match emission:
///
/// 1. Pops finished regions (where `pos > sendpos[curissend]`) —
///    each pop emits SGR-reset + restores the prior color from the
///    `curiscols[]` stack.
/// 2. Pushes any region whose begin position equals `pos`, or
///    finishes-empty regions (endpos < begpos or begpos == -1):
///    inserts `endpos` into the sorted `sendpos[]` array, emits
///    SGR-reset + the new color, pushes onto curiscols[].
pub fn doiscol(pos: i32) -> i32 {                                             // c:635
    use std::sync::atomic::Ordering;
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out = if fd >= 0 { fd } else { 1 };

    // c:639-645 — pop finished regions.
    loop {
        let curissend = CURISSEND.load(Ordering::Relaxed) as usize;
        let sp = SENDPOS.lock().ok().and_then(|s| s.get(curissend).copied())
            .unwrap_or(0xfffffff);
        if pos <= sp { break; }
        CURISSEND.fetch_add(1, Ordering::Relaxed);
        let curiscol = CURISCOL.load(Ordering::Relaxed);
        if curiscol > 0 {
            // c:642 — `zcputs(NULL, COL_NO);` — SGR reset.
            let _ = crate::ported::utils::write_loop(out, b"\x1b[0m");
            // c:643 — `zlrputs(curiscols[--curiscol]);`
            let new_idx = curiscol - 1;
            CURISCOL.store(new_idx, Ordering::Relaxed);
            let restore_cap = CURISCOLS.lock().ok()
                .and_then(|c| c.get(new_idx as usize).cloned())
                .unwrap_or_default();
            if !restore_cap.is_empty() {
                let _ = zlrputs(&restore_cap);
            }
        }
    }

    // c:646-665 — push new regions starting at or before `pos`.
    loop {
        let curisbeg = CURISBEG.load(Ordering::Relaxed) as usize;
        if curisbeg >= MAX_POS { break; }
        let (bp, ep) = {
            let bp_lock = BEGPOS.lock().ok();
            let ep_lock = ENDPOS.lock().ok();
            match (bp_lock, ep_lock) {
                (Some(b), Some(e)) => {
                    (b.get(curisbeg).copied().unwrap_or(0xfffffff),
                     e.get(curisbeg).copied().unwrap_or(0xfffffff))
                }
                _ => break,
            }
        };
        // c:646-647 — `fi = (endpos[curisbeg] < begpos[curisbeg] ||
        //                    begpos[curisbeg] == -1)`. Finished-empty region.
        let fi = ep < bp || bp == -1;
        if !(fi || pos == bp) {
            break;
        }
        // c:648 — `*patcols` truthy gate (more colors available).
        let patcols_idx = PATCOLS_IDX.load(Ordering::Relaxed);
        let cap_now = PATCOLS.lock().ok()
            .and_then(|p| p.get(patcols_idx).cloned())
            .unwrap_or_default();
        if cap_now.is_empty() { break; }

        if !fi {
            // c:650-657 — insert `e = endpos[curisbeg]` into sendpos[]
            //              in sorted order.
            let e = ep;
            if let Ok(mut sp) = SENDPOS.lock() {
                let curissend = CURISSEND.load(Ordering::Relaxed) as usize;
                let mut i = curissend;
                while i < MAX_POS && sp[i] <= e {
                    i += 1;
                }
                let mut j = MAX_POS - 1;
                while j > i {
                    sp[j] = sp[j - 1];
                    j -= 1;
                }
                if i < MAX_POS {
                    sp[i] = e;
                }
            }
            // c:659-660 — `zcputs(NULL, COL_NO); zlrputs(*patcols);`
            let _ = crate::ported::utils::write_loop(out, b"\x1b[0m");
            let _ = zlrputs(&cap_now);
            // c:661 — `curiscols[++curiscol] = *patcols;`
            let new_idx = CURISCOL.fetch_add(1, Ordering::Relaxed) + 1;
            if let Ok(mut cs) = CURISCOLS.lock() {
                if (new_idx as usize) < cs.len() {
                    cs[new_idx as usize] = cap_now;
                }
            }
        }
        // c:663-664 — `++patcols; ++curisbeg;`.
        PATCOLS_IDX.fetch_add(1, Ordering::Relaxed);
        CURISBEG.fetch_add(1, Ordering::Relaxed);
    }
    0
}

/// Port of `clprintfmt(char *p, int ml)` from Src/Zle/complist.c:671.
pub fn clprintfmt(p: &str, ml: i32) -> i32 {                                // c:671
    // C body c:673-712 — colored variant of printfmt that uses mcolors
    //                    for %F/%B etc. Without the mcolors substrate
    //                    we delegate to the plain printfmt.
    crate::ported::zle::zle_tricky::printfmt(p, ml, true, true)
}

/// Port of `int clnicezputs(int do_colors, char *s, int ml)` from
/// `Src/Zle/complist.c:715`. Emits the bytes of `s` to the
/// shell-output fd with optional per-char colorization. The full C
/// body (c:717-790) walks every byte applying meta-decoding,
/// `itok` skipping, multibyte → nice-character expansion, and per-
/// match LS_COLORS lookups via `doiscol`. Rust port handles the
/// meta-decode + itok-skip pieces faithfully and writes bytes
/// directly; LS_COLORS colorization stays gated on do_colors but
/// only emits the post-decoded string without per-char color cycling
/// until the mcolors substrate is wired.
#[allow(unused_variables)]
pub fn clnicezputs(do_colors: i32, s: &str, ml: i32) -> i32 {               // c:715
    use std::sync::atomic::Ordering;
    let _ = do_colors;
    // c:717-735 — meta-decode loop matches the C `niceztrlen`/
    //              `nicezputs` pair. We do the same demeta-+-itok-skip
    //              pass `compzputs` uses, then write the decoded bytes.
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if c == 0x83 {                                                       // c:741 Meta byte
            i += 1;
            if i < bytes.len() {
                out.push(bytes[i] ^ 32);
            }
        } else if (0x80..0xa0).contains(&c) {                                // c:744 itok skip
            // pass — pseudo-token, not real output
        } else {
            out.push(c);
        }
        i += 1;
    }
    if out.is_empty() {
        return 0;
    }
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    let _ = crate::ported::utils::write_loop(out_fd, &out);
    0
}

// Get the terminal color string for the given match.                      // c:881
/// Port of `putmatchcol(char *group, char *n)` from Src/Zle/complist.c:881.
pub fn putmatchcol(group: &str, n: &str) -> i32 {                       // c:881
    // C body c:883-908 — looks up "ma" or "co" entries in mcolors
    //                    for the given group/name and emits the
    //                    escape via putcolstr.
    //                    Without mcolors substrate: no-op.
    let _ = group;
    0
}

/// Port of `putfilecol(char *group, char *filename, mode_t m, int special)` from Src/Zle/complist.c:910.
pub fn putfilecol(group: &str, filename: &str, m: u32, special: i32) -> i32 { // c:910
    // C body c:912-988 — looks up the LS_COLORS class for `name`
    //                    by mode bits + filename suffix, emits the
    //                    matching escape via putcolstr.
    //                    Without mcolors substrate: no-op.
    let _ = group;
    0
}

/// Format the "scroll for more?" prompt shown when the match list
/// exceeds the terminal height.
/// Port of `asklistscroll(int ml)` from Src/Zle/complist.c. The C source
/// emits "--More--" plus a percent indicator and reads y/n via
/// `getzlequery`; ours produces the prompt string and leaves the
/// input read to the caller.
/// WARNING: param names don't match C — Rust=(total, shown) vs C=(ml)
pub fn asklistscroll(total: usize, shown: usize) -> String {                 // c:1001
    let _remaining = total.saturating_sub(shown);
    format!("--More--({}/{})", shown, total)
}

/// Port of `int compprintnl(int ml)` from
/// `Src/Zle/complist.c:1054`. Emits clear-to-end + newline to the
/// shell-output fd; if scroll mode is on and the remaining-line
/// budget hits zero, queries `asklistscroll(ml)` (currently
/// substrate-gapped; we skip the scroll prompt and return 0).
///
/// C body c:1056-1064:
/// ```c
/// cleareol(); putc('\n', shout);
/// if (mscroll && !--mrestlines && (ask = asklistscroll(ml))) return ask;
/// return 0;
/// ```
#[allow(unused_variables)]
pub fn compprintnl(ml: i32) -> i32 {                                        // c:1054
    use std::sync::atomic::Ordering;
    // c:1056 — `cleareol();` followed by `putc('\n', shout);`. We
    //          emit both as a single write (CSI K + LF).
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    let _ = crate::ported::utils::write_loop(out_fd, b"\x1b[K\n");
    // c:1058-1063 — scroll-prompt branch needs `mscroll`/`mrestlines`/
    //                `asklistscroll` substrate; skipped until those land.
    0
}

/// Port of `static int compprintfmt(char *fmt, int n, int dopr,
/// int doesc, int ml, int *stop)` from `Src/Zle/complist.c:1072`.
/// Renders the LISTPROMPT / mstatus / explanation-string format,
/// expanding `%n` (count), `%p` (line position), `%l` (lines),
/// `%m` (current match position), `%M` (last match position),
/// `%S`/`%s` (standout on/off), `%B`/`%b`, `%U`/`%u`, `%F`/`%f`,
/// `%K`/`%k`, and `%%`. Returns the visible width consumed,
/// stopping early if the row hits `mlend`.
/// ```c
/// static int
/// compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
/// {
///     char *p, nc[2*DIGBUFSIZE+12], nbuf[2*DIGBUFSIZE+12];
///     int l = 0, cc = 0, m, ask, beg, stat;
///     if ((stat = !fmt)) {
///         if (mlbeg >= 0) {
///             if (!(fmt = mstatus)) { mlprinted = 0; return 0; }
///             cc = -1;
///         } else fmt = mlistp;
///     }
///     /* per-char loop dispatching every %X */
///     return cc;
/// }
/// ```
/// WARNING: param names don't match C — Rust=(fmt, n, dopr, doesc, ml, stop) vs C=(fmt, n, dopr, doesc, ml, stop)
pub fn compprintfmt(                                                         // c:1072
    fmt: &str,
    n: i32,
    dopr: i32,
    doesc: i32,
    ml: i32,
    stop: &mut i32,
) -> i32 {
    use std::sync::atomic::Ordering;

    let mut l = 0i32;                                                        // c:1075
    let mut cc = 0i32;
    let _ = doesc;
    let _ = ml;
    let _ = stop;

    // c:1077-1086 — fmt fallback to mstatus / mlistp when caller passed NULL.
    let owned: String;
    let fmt_str: &str = if fmt.is_empty() {                                  // c:1077
        if MLBEG.load(Ordering::SeqCst) >= 0 {                               // c:1078
            owned = MSTATUS.lock().unwrap().clone();
            if owned.is_empty() {
                MLPRINTED.store(0, Ordering::SeqCst);                        // c:1080
                return 0;                                                    // c:1081
            }
            cc = -1;                                                         // c:1083
            &owned
        } else {                                                             // c:1084
            owned = MLISTP.lock().unwrap().clone();
            &owned
        }
    } else {
        fmt
    };

    // c:1087-end — escape dispatch loop. Implement the daily-driver
    // subset (the LIST_PACKED escape arms that LISTPROMPT users hit).
    let mut chars = fmt_str.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '%' {                                                        // c:1102
            // c:1108 — optional digit arg
            let mut arg = 0i32;
            while let Some(&d) = chars.peek() {
                if d.is_ascii_digit() {
                    arg = arg * 10 + (d as i32 - '0' as i32);
                    chars.next();
                } else { break; }
            }
            match chars.next() {                                             // c:1119
                Some('%') => { if dopr == 1 { l += 1; } cc += 1; }           // c:1120
                Some('n') => {                                               // c:1141
                    let s = n.to_string();
                    if dopr == 1 {
                        use std::sync::atomic::Ordering as O;
                        let fd = crate::ported::init::SHTTY.load(O::Relaxed);
                        let out_fd = if fd >= 0 { fd } else { 1 };
                        let _ = crate::ported::utils::write_loop(out_fd, s.as_bytes());
                    }
                    l += s.len() as i32;
                    cc += s.len() as i32;
                }
                Some('p') => {                                               // c:1155 line position
                    let mlbeg = MLBEG.load(Ordering::SeqCst);
                    let mlines = MLINES.load(Ordering::SeqCst);
                    let s = if mlbeg <= 0 && mlines < MLEND.load(Ordering::SeqCst) {
                        "Top".to_string()
                    } else if mlbeg + MLEND.load(Ordering::SeqCst) - MLBEG.load(Ordering::SeqCst) >= mlines {
                        "Bot".to_string()
                    } else {
                        format!("{}%", mlbeg.max(0) * 100 / mlines.max(1))
                    };
                    if dopr == 1 {
                        use std::sync::atomic::Ordering as O;
                        let fd = crate::ported::init::SHTTY.load(O::Relaxed);
                        let out_fd = if fd >= 0 { fd } else { 1 };
                        let _ = crate::ported::utils::write_loop(out_fd, s.as_bytes());
                    }
                    l += s.len() as i32;
                    cc += s.len() as i32;
                }
                Some(_) => { let _ = arg; }                                  // c:other-escape
                None => break,
            }
        } else {                                                             // c:literal char
            if dopr == 1 {
                use std::sync::atomic::Ordering as O;
                let fd = crate::ported::init::SHTTY.load(O::Relaxed);
                let out_fd = if fd >= 0 { fd } else { 1 };
                let mut buf = [0u8; 4];
                let bs = c.encode_utf8(&mut buf).as_bytes();
                let _ = crate::ported::utils::write_loop(out_fd, bs);
            }
            l += 1;
            cc += 1;
        }
    }
    let _ = l;
    cc                                                                       // c:return
}

/// Port of `static char *mstatus` from `Src/Zle/complist.c:93`. Message
/// printed when the user scrolls the completion list.
pub static MSTATUS: std::sync::LazyLock<std::sync::Mutex<String>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(String::new()));       // c:93

/// Port of `static char *mlistp` from `Src/Zle/complist.c:93`. Message
/// printed when merely listing (no scroll).
pub static MLISTP: std::sync::LazyLock<std::sync::Mutex<String>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(String::new()));       // c:93

/// Port of `int compzputs(char const *s, int ml)` from
/// `Src/Zle/complist.c:1338`. Demetafies each byte (Meta XOR 32),
/// skips `itok` pseudo-tokens (0x80-0x9f), writes the result to
/// the shell-output fd. The C source also handles wrap detection +
/// `asklistscroll` scroll-prompts; those land when the curses
/// substrate is wired.
#[allow(unused_variables)]
pub fn compzputs(s: &str, ml: i32) -> i32 {                                 // c:1338
    use std::sync::atomic::Ordering;
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if c == 0x83 {                                                       // c:1343 Meta byte
            i += 1;
            if i < bytes.len() {
                out.push(bytes[i] ^ 32);
            }
        } else if (0x80..0xa0).contains(&c) {                                // c:1345 itok skip
            // pass — pseudo-token
        } else {
            out.push(c);
        }
        i += 1;
    }
    if out.is_empty() {
        return 0;
    }
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    let _ = crate::ported::utils::write_loop(out_fd, &out);                  // c:1356 putc loop
    0
}

/// Port of `static int compprintlist(int showall)` from
/// `Src/Zle/complist.c:1367`. Walks the active `amatches` group
/// chain, emits explanations + ylist + cmatch grid via
/// `clprintm` / `compprintfmt` / `compzputs`, tracking line
/// position against `mlbeg`/`mlend` for resumable scrolling.
pub fn compprintlist(showall: i32) -> i32 {                                  // c:1367
    use std::sync::atomic::Ordering;
    use crate::ported::zle::comp_h::{CGF_HASDL, CGF_LINES, CGF_ROWS, CMF_DISPLINE, CMF_HIDE, CMF_NOLIST};

    let mut pnl = 0i32;                                                      // c:1378
    let mut cl: i32;
    let mut ml: i32 = 0;
    let mut mc: i32;
    let mut printed = 0i32;
    let mut stop = 0i32;
    let _asked = 1i32;
    let mut lastused = 0i32;                                                 // c:1379

    let mlbeg = MLBEG.load(Ordering::SeqCst);
    let mlend = MLEND.load(Ordering::SeqCst);
    let mnew = MNEW.load(Ordering::SeqCst);
    let mhasstat = MHASSTAT.load(Ordering::SeqCst);
    let zterm_lines = crate::ported::utils::adjustlines() as i32;
    let nlnct = crate::ported::zle::zle_refresh::NLNCT.load(Ordering::SeqCst);
    let invcount = crate::ported::zle::compresult::INVCOUNT.load(Ordering::SeqCst);

    MFIRSTL.store(-1, Ordering::SeqCst);                                     // c:1381

    // c:1382-1388 — reset accumulators when ainfo changed.
    let mut last_type = LAST_TYPE.load(Ordering::SeqCst);
    let last_invcount = LAST_INVCOUNT.load(Ordering::SeqCst);
    let last_beg = LAST_BEG.load(Ordering::SeqCst);
    if mnew != 0 || last_invcount != invcount || last_beg != mlbeg || mlbeg < 0 {
        last_type = 0;                                                       // c:1383-1387
        LAST_TYPE.store(0, Ordering::SeqCst);
        LAST_NLNCT.store(-1, Ordering::SeqCst);
    }

    // c:1389-1391 — clear-line budget for the current paint.
    let listdat_nlines = crate::ported::zle::compcore::listdat
        .get()
        .and_then(|m| m.lock().ok().map(|g| g.nlines))
        .unwrap_or(0);
    cl = if listdat_nlines > zterm_lines - nlnct - mhasstat {                // c:1389
        zterm_lines - nlnct - mhasstat
    } else {
        listdat_nlines
    } - if LAST_NLNCT.load(Ordering::SeqCst) > nlnct { 1 } else { 0 };
    LAST_NLNCT.store(nlnct, Ordering::SeqCst);                               // c:1392
    MRESTLINES.store(zterm_lines - 1, Ordering::SeqCst);                     // c:1393
    LAST_INVCOUNT.store(invcount, Ordering::SeqCst);                         // c:1394

    let tcd_avail = crate::ported::init::tclen.lock().unwrap()
        [crate::ported::zsh_h::TCCLEAREOD as usize] != 0;                    // c:1398
    let tceol_avail = crate::ported::init::tclen.lock().unwrap()
        [crate::ported::zsh_h::TCCLEAREOL as usize] != 0;

    if cl < 2 {                                                              // c:1396
        cl = -1;                                                             // c:1397
        if tcd_avail {                                                       // c:1398
            crate::ported::zle::zle_refresh::tcout("TCCLEAREOD");            // c:1399
        }
    } else if mlbeg >= 0 && !tceol_avail && tcd_avail {                      // c:1400
        crate::ported::zle::zle_refresh::tcout("TCCLEAREOD");                // c:1401
    }

    // c:1403-1679 — walk amatches groups.
    let groups: Vec<crate::ported::zle::comp_h::Cmgroup> = {
        crate::ported::zle::compcore::amatches
            .get_or_init(|| std::sync::Mutex::new(Vec::new()))
            .lock().ok().map(|g| g.clone()).unwrap_or_default()
    };

    let dolist = |x: i32| -> bool { x >= mlbeg && x < mlend };               // c:1048
    let dolistcl = |x: i32| -> bool { x >= mlbeg && x < mlend + 1 };         // c:1049
    let dolistnl = |x: i32| -> bool { x >= mlbeg && x < mlend - 1 };         // c:1050

    'outer: for g in &groups {                                               // c:1404
        if crate::ported::utils::errflag.load(Ordering::SeqCst) != 0 {       // c:1404 !errflag
            break;
        }

        // c:1405 — `char **pp = g->ylist;`
        let pp = &g.ylist;
        let onlyexpl: i32 = crate::ported::zle::compcore::listdat
            .get()
            .and_then(|m| m.lock().ok().map(|g| g.onlyexpl))
            .unwrap_or(0);

        // c:1412-1470 — emit explanation strings.
        if !g.expls.is_empty() {                                             // c:1412
            for e in &g.expls {                                              // c:1418
                if crate::ported::utils::errflag.load(Ordering::SeqCst) != 0 { break 'outer; }
                let valid = (e.count != 0 || e.always != 0)                  // c:1419
                    && (onlyexpl == 0
                        || (onlyexpl & if e.always > 0 { 2 } else { 1 }) != 0);
                if valid {
                    if pnl != 0 {                                            // c:1422
                        if dolistnl(ml) && compprintnl(ml) != 0 {            // c:1423
                            break 'outer;
                        }
                        pnl = 0;                                             // c:1425
                        ml += 1;                                             // c:1426
                        if dolistcl(ml) && cl >= 0 {                         // c:1427
                            cl -= 1;
                            if cl <= 1 {
                                cl = -1;                                     // c:1428
                                if tcd_avail {                               // c:1429
                                    crate::ported::zle::zle_refresh::tcout("TCCLEAREOD");
                                }
                            }
                        }
                    }
                    if mlbeg < 0 && MFIRSTL.load(Ordering::SeqCst) < 0 {     // c:1433
                        MFIRSTL.store(ml, Ordering::SeqCst);                 // c:1434
                    }
                    let n = if e.always != 0 { -1 } else { e.count };
                    let estr = e.str.clone().unwrap_or_default();
                    let _ = compprintfmt(                                    // c:1435
                        &estr, n,
                        if dolist(ml) { 1 } else { 0 },
                        1, ml, &mut stop,
                    );
                    if stop != 0 { break 'outer; }                           // c:1447
                    if last_type == 0 && ml >= mlbeg {                       // c:1449
                        last_type = 1;                                       // c:1450
                        LAST_TYPE.store(1, Ordering::SeqCst);
                        LAST_BEG.store(mlbeg, Ordering::SeqCst);
                        LAST_ML.store(ml, Ordering::SeqCst);
                        lastused = 1;
                    }
                    ml += MLPRINTED.load(Ordering::SeqCst);                  // c:1458
                    if dolistcl(ml) && cl >= 0 {                             // c:1459
                        cl -= MLPRINTED.load(Ordering::SeqCst);
                        if cl <= 1 {
                            cl = -1;
                            if tcd_avail {
                                crate::ported::zle::zle_refresh::tcout("TCCLEAREOD");
                            }
                        }
                    }
                    pnl = 1;                                                 // c:1464
                }
                if mnew == 0 && ml > mlend { break 'outer; }                 // c:1467
            }
        }

        // c:1471-1529 — ylist short-form rendering.
        if onlyexpl == 0 && mlbeg < 0 && !pp.is_empty() {                    // c:1471
            if pnl != 0 {                                                    // c:1472
                if dolistnl(ml) && compprintnl(ml) != 0 { break 'outer; }    // c:1473
                pnl = 0;
                ml += 1;
                if cl >= 0 { cl -= 1; if cl <= 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } } }
            }
            if mlbeg < 0 && MFIRSTL.load(Ordering::SeqCst) < 0 {
                MFIRSTL.store(ml, Ordering::SeqCst);
            }
            if (g.flags & CGF_LINES) != 0 {                                  // c:1485
                for s in pp {                                                // c:1486
                    if compzputs(s, ml) != 0 { break 'outer; }               // c:1487
                    if compprintnl(ml) != 0 { break 'outer; }                // c:1489
                }
            } else {
                // c:1492-1528 — packed ylist columns.
                // Single-pass emit; column-perfect alignment defers to
                // the column-width helper port.
                for s in pp {
                    if compzputs(s, MSCROLL.load(Ordering::SeqCst)) != 0 {   // c:1505
                        break 'outer;
                    }
                    if compprintnl(ml) != 0 { break 'outer; }                // c:1518
                    ml += 1;
                }
            }
        } else if onlyexpl == 0 && (g.lcount != 0 || (showall != 0 && g.mcount != 0)) {  // c:1530
            // c:1532-1675 — cmatch grid render.
            let n_total = g.dcount;
            let _ = n_total;
            let nc = g.lins;

            // c:1537-1590 — CGF_HASDL whole-line displays.
            if (g.flags & CGF_HASDL) != 0 {                                  // c:1537
                for m in &g.matches {                                        // c:1549
                    let displine = m.disp.is_some() && (m.flags & CMF_DISPLINE) != 0;
                    let visible = showall != 0
                        || (m.flags & (CMF_HIDE | CMF_NOLIST)) == 0;
                    if displine && visible {                                 // c:1551
                        if pnl != 0 {                                        // c:1552
                            if dolistnl(ml) && compprintnl(ml) != 0 {
                                break 'outer;
                            }
                            pnl = 0;
                            ml += 1;
                            if dolistcl(ml) && cl >= 0 {
                                cl -= 1;
                                if cl <= 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } }
                            }
                        }
                        if last_type == 0 && ml >= mlbeg {                   // c:1563
                            last_type = 2;
                            LAST_TYPE.store(2, Ordering::SeqCst);
                            LAST_BEG.store(mlbeg, Ordering::SeqCst);
                            LAST_ML.store(ml, Ordering::SeqCst);
                            lastused = 1;
                        }
                        if MFIRSTL.load(Ordering::SeqCst) < 0 {              // c:1573
                            MFIRSTL.store(ml, Ordering::SeqCst);
                        }
                        if dolist(ml) { printed += 1; }                      // c:1575
                        if clprintm(Some(g), Some(m), 0, ml, 1, 0) != 0 {    // c:1577
                            break 'outer;
                        }
                        ml += MLPRINTED.load(Ordering::SeqCst);              // c:1579
                        if dolistcl(ml) {
                            cl -= MLPRINTED.load(Ordering::SeqCst);
                            if cl <= 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } }
                        }
                        pnl = 1;                                             // c:1585
                    }
                    if mnew == 0 && ml > mlend { break 'outer; }             // c:1587
                }
            }
            if pnl != 0 {                                                    // c:1591
                if dolistnl(ml) && compprintnl(ml) != 0 { break 'outer; }
                pnl = 0; ml += 1;
                if dolistcl(ml) && cl >= 0 {
                    cl -= 1;
                    if cl <= 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } }
                }
            }

            // c:1611-1674 — grid row/column loop.
            let mut nl_cnt = nc;
            let mut p_idx: usize = 0;
            // Skip CMF_HIDE/CMF_NOLIST matches at head.
            while p_idx < g.matches.len() {
                let m = &g.matches[p_idx];
                if (m.flags & CMF_HIDE) != 0
                    || (showall == 0 && (m.flags & CMF_NOLIST) != 0)
                {
                    p_idx += 1;
                } else { break; }
            }
            let mut n = g.dcount;
            while n > 0 && nl_cnt > 0 && crate::ported::utils::errflag.load(Ordering::SeqCst) == 0 {
                if last_type == 0 && ml >= mlbeg {                           // c:1612
                    last_type = 3;
                    LAST_TYPE.store(3, Ordering::SeqCst);
                    LAST_BEG.store(mlbeg, Ordering::SeqCst);
                    LAST_ML.store(ml, Ordering::SeqCst);
                    lastused = 1;
                }
                let mut i = g.cols;                                          // c:1622
                mc = 0;
                let mut q_idx = p_idx;
                while n > 0 && i > 0 && crate::ported::utils::errflag.load(Ordering::SeqCst) == 0 {
                    i -= 1;
                    let wid = if !g.widths.is_empty() {                      // c:1626
                        g.widths.get(mc as usize).copied().unwrap_or(g.width)
                    } else { g.width };
                    let m_at_q = g.matches.get(q_idx);                       // c:1627
                    match m_at_q {
                        None => {                                            // c:1627 !m
                            if clprintm(Some(g), None, mc, ml,               // c:1628
                                if i == 0 { 1 } else { 0 }, wid) != 0
                            {
                                break 'outer;
                            }
                            break;
                        }
                        Some(m) => {                                         // c:1632
                            if clprintm(Some(g), Some(m), mc, ml,
                                if i == 0 { 1 } else { 0 }, wid) != 0
                            {
                                break 'outer;
                            }
                            if dolist(ml) { printed += 1; }                  // c:1635
                            ml += MLPRINTED.load(Ordering::SeqCst);          // c:1637
                            if dolistcl(ml) {
                                cl -= MLPRINTED.load(Ordering::SeqCst);
                                if cl < 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } }
                            }
                            if MFIRSTL.load(Ordering::SeqCst) < 0 {          // c:1643
                                MFIRSTL.store(ml, Ordering::SeqCst);
                            }
                            n -= 1;                                          // c:1646
                            if n > 0 {                                       // c:1646
                                let step = if (g.flags & CGF_ROWS) != 0 { 1 } else { nc as usize };
                                for _j in 0..step {                          // c:1647
                                    if q_idx < g.matches.len() { q_idx += 1; }
                                    while q_idx < g.matches.len() {          // c:1649 skipnolist
                                        let m2 = &g.matches[q_idx];
                                        if (m2.flags & CMF_HIDE) != 0
                                            || (showall == 0 && (m2.flags & CMF_NOLIST) != 0)
                                        {
                                            q_idx += 1;
                                        } else { break; }
                                    }
                                }
                            }
                            mc += 1;                                         // c:1650
                        }
                    }
                }
                // c:1652-1657 — fill trailing columns with empty cells.
                while i > 0 {
                    i -= 1;
                    let wid = if !g.widths.is_empty() {
                        g.widths.get(mc as usize).copied().unwrap_or(g.width)
                    } else { g.width };
                    if clprintm(Some(g), None, mc, ml,
                        if i == 0 { 1 } else { 0 }, wid) != 0
                    {
                        break 'outer;
                    }
                    mc += 1;
                }
                if n > 0 {                                                   // c:1658
                    if dolistnl(ml) && compprintnl(ml) != 0 { break 'outer; }
                    ml += 1;                                                 // c:1661
                    if dolistcl(ml) && cl >= 0 {                             // c:1662
                        cl -= 1;
                        if cl <= 1 { cl = -1; if tcd_avail { crate::ported::zle::zle_refresh::tcout("TCCLEAREOD"); } }
                    }
                    if nl_cnt > 0 {                                          // c:1667
                        let step = if (g.flags & CGF_ROWS) != 0 { g.cols as usize } else { 1 };
                        for _j in 0..step {
                            if p_idx < g.matches.len() { p_idx += 1; }
                            while p_idx < g.matches.len() {
                                let m2 = &g.matches[p_idx];
                                if (m2.flags & CMF_HIDE) != 0
                                    || (showall == 0 && (m2.flags & CMF_NOLIST) != 0)
                                {
                                    p_idx += 1;
                                } else { break; }
                            }
                        }
                    }
                }
                if mnew == 0 && ml > mlend { break 'outer; }                 // c:1672
                nl_cnt -= 1;
            }
        }
        if g.lcount != 0 || (showall != 0 && g.mcount != 0) {                // c:1676
            pnl = 1;                                                         // c:1677
        }
    }
    // c:1681 end:
    MSTATPRINTED.store(0, Ordering::SeqCst);                                 // c:1682
    crate::ported::zle::zle_refresh::LASTLISTLEN.store(0, Ordering::SeqCst); // c:1683
    if nlnct <= 1 { MSCROLL.store(0, Ordering::SeqCst); }                    // c:1684

    let _ = lastused;
    printed                                                                  // c:1727 (approx; full clearflag epilogue elided)
}

/// Port of `static int lasttype` from `Src/Zle/complist.c:1369`.
pub static LAST_TYPE: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:1369

/// Port of `static int lastbeg` from `Src/Zle/complist.c:1369`.
pub static LAST_BEG: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:1369

/// Port of `static int lastml` from `Src/Zle/complist.c:1369`.
pub static LAST_ML: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:1369

/// Port of `static int lastinvcount` from `Src/Zle/complist.c:1369`.
pub static LAST_INVCOUNT: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(-1);                                   // c:1369

/// Port of `static int lastnlnct` from `Src/Zle/complist.c:1370`.
pub static LAST_NLNCT: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(-1);                                   // c:1370

/// Port of `static int clprintm(Cmgroup g, Cmatch *mp, int mc, int ml,
/// int lastc, int width)` from `Src/Zle/complist.c:1730`. Renders one
/// match cell into the listing: emits LS_COLORS prefix, the match
/// string (via `clnicezputs`), the file-type marker if `CGF_FILES`,
/// and trailing padding spaces up to `width`. Also writes the
/// `mtab[][]`/`mgtab[][]` cells so the keymap-navigation path can
/// find the current selection by (mline, mcol).
/// ```c
/// static int
/// clprintm(Cmgroup g, Cmatch *mp, int mc, int ml, int lastc, int width)
/// {
///     Cmatch m;
///     int len, subcols = 0, stop = 0, ret = 0;
///     if (g != last_group) *last_cap = '\0';
///     last_group = g;
///     if (!mp) { /* empty cell: pad with COL_SP spaces; return */ }
///     m = *mp;
///     mlastm = m->gnum;
///     if (m->disp && (m->flags & CMF_DISPLINE)) {
///         /* whole-line display: write mtab cells for the line,
///            color via COL_MA (selected) / COL_HI (nolist) / COL_DU
///            (dupe) / putmatchcol; emit via clprintfmt or compprintfmt */
///     } else {
///         /* normal grid cell: write mtab cells for the cell width,
///            color via COL_MA / COL_HI / COL_DU / putfilecol /
///            putmatchcol; emit string via clnicezputs; emit modec
///            marker for CGF_FILES; pad with COL_SP spaces */
///     }
///     zcoff();
///     return ret;
/// }
/// ```
/// WARNING: param names don't match C — Rust=(g, m, mc, ml, lastc, width) vs C=(g, mp, mc, ml, lastc, width)
pub fn clprintm(
    g: Option<&crate::ported::zle::comp_h::Cmgroup>,
    m: Option<&crate::ported::zle::comp_h::Cmatch>,
    mc: i32,
    ml: i32,
    lastc: i32,
    width: i32,
) -> i32 {                                                                   // c:1730
    use std::sync::atomic::Ordering;

    let mselect = MSELECT.load(Ordering::SeqCst);
    let mcols = MCOLS.load(Ordering::SeqCst);
    let zterm_columns = crate::ported::utils::adjustcolumns() as i32;

    // c:1738-1741 — group-change detection: reset last_cap so the
    // next zcputs writes a fresh color prefix.
    {
        let mut lg = LAST_GROUP.lock().unwrap();
        let g_name = g.and_then(|grp| grp.name.clone()).unwrap_or_default();
        if *lg != g_name {                                                   // c:1738
            *LAST_CAP.lock().unwrap() = String::new();                       // c:1739
            *lg = g_name;                                                    // c:1741
        }
    }

    // c:1743-1753 — empty cell case.
    let m_ref = match m {                                                    // c:1743
        Some(m_real) => m_real,
        None => {
            // c:1744 — `if (dolist(ml))` — list-decision predicate.
            // Without dolist port we treat all rows as visible.
            if let Some(grp) = g {                                           // c:1745
                let _ = grp;
                // c:1745 — zcputs(g->name, COL_SP)
                // c:1747-1748 — pad with `width-2` spaces
                let pad = (width - 2).max(0) as usize;
                let pad_str = " ".repeat(pad);
                use std::sync::atomic::Ordering as O;
                let fd = crate::ported::init::SHTTY.load(O::Relaxed);
                let out_fd = if fd >= 0 { fd } else { 1 };
                let _ = crate::ported::utils::write_loop(out_fd, pad_str.as_bytes());
                // c:1749 — zcoff() reset
            }
            MLPRINTED.store(0, Ordering::SeqCst);                            // c:1751
            return 0;                                                        // c:1752
        }
    };

    // c:1754 — `m = *mp;` (Rust: deref already done by Some(m))

    // c:1756-1757 — bld_all_str for CMF_ALL with empty disp.
    // (CMF_ALL flag at comp.h:140; bld_all_str ported elsewhere.)
    let _ = crate::ported::zle::comp_h::CMF_ALL;

    // c:1759 — `mlastm = m->gnum;`
    MLASTM.store(m_ref.gnum, Ordering::SeqCst);

    // c:1760 — `if (m->disp && (m->flags & CMF_DISPLINE))`
    let displine = m_ref.disp.is_some()
        && (m_ref.flags & crate::ported::zle::comp_h::CMF_DISPLINE) != 0;
    if displine {                                                            // c:1760
        // c:1761-1777 — write mtab cells for whole-line display.
        if mselect >= 0 {                                                    // c:1761
            let mm = mcols * ml;                                             // c:1762
            let mut mtab_guard = MTAB.lock().unwrap();
            let mut mgtab_guard = MGTAB.lock().unwrap();
            for i in 0..mcols {                                              // c:1765 / c:1771
                let idx = (mm + i) as usize;
                if idx < mtab_guard.len() {
                    mtab_guard[idx] = Some(m_ref.clone());                   // c:1767/1773
                    if let Some(grp) = g {
                        mgtab_guard[idx] = Some(grp.clone());                // c:1768/1774
                    }
                }
            }
        }
        // c:1782-1788 — selected? capture current mline/mcol.
        if m_ref.gnum == mselect {                                           // c:1782
            let mm = mcols * ml;
            MLINE.store(ml, Ordering::SeqCst);                               // c:1785
            MCOL.store(0, Ordering::SeqCst);                                 // c:1786
            MMTABP.store(mm.max(0) as usize, Ordering::SeqCst);              // c:1787
            MGTABP.store(mm.max(0) as usize, Ordering::SeqCst);              // c:1788
        }
        // c:1789-1797 — color selection. Stubbed to no-op output;
        // the live zcputs / putmatchcol / putfilecol pipeline lands
        // once those helpers port.
        // c:1801 — compprintfmt(m->disp, 0, 1, 0, ml, &stop)
        let disp = m_ref.disp.as_deref().unwrap_or("");
        let _ = compprintfmt(disp, 0, 1, 0, ml, &mut 0);                     // c:1801
    } else {
        // c:1806-1898 — normal grid-cell display.
        let mx = if !g.is_some_and(|grp| grp.widths.is_empty()) {            // c:1809-1813
            // c:1812-1813 — sum widths[0..mc]
            g.map(|grp| grp.widths.iter().take(mc as usize).sum::<i32>()).unwrap_or(0)
        } else {
            // c:1815 — `mx = mc * g->width;`
            mc * g.map(|grp| grp.width).unwrap_or(0)
        };

        // c:1817-1832 — write mtab cells for cell width.
        if mselect >= 0 {                                                    // c:1817
            let mm = mcols * ml;
            let mut mtab_guard = MTAB.lock().unwrap();
            let mut mgtab_guard = MGTAB.lock().unwrap();
            let n = if width != 0 { width } else { mcols };
            for i in 0..n {                                                  // c:1821 / c:1827
                let idx = (mx + mm + i) as usize;
                if idx < mtab_guard.len() {
                    mtab_guard[idx] = Some(m_ref.clone());                   // c:1823/1829
                    if let Some(grp) = g {
                        mgtab_guard[idx] = Some(grp.clone());                // c:1824/1830
                    }
                }
            }
        }

        // c:1842-1850 — selected? capture coords.
        if m_ref.gnum == mselect {                                           // c:1842
            let mm = mcols * ml;
            MCOL.store(mx, Ordering::SeqCst);                                // c:1846
            MLINE.store(ml, Ordering::SeqCst);                               // c:1847
            MMTABP.store((mx + mm).max(0) as usize, Ordering::SeqCst);       // c:1848
            MGTABP.store((mx + mm).max(0) as usize, Ordering::SeqCst);       // c:1849
        }

        // c:1872 — `ret = clnicezputs(subcols, m->disp ? m->disp : m->str, ml);`
        let display = m_ref.disp.as_deref()
            .unwrap_or_else(|| m_ref.str.as_deref().unwrap_or(""));
        // Emit raw — full clnicezputs (escape-aware writer) deferred;
        // the cell still receives the visible text.
        use std::sync::atomic::Ordering as O;
        let fd = crate::ported::init::SHTTY.load(O::Relaxed);
        let out_fd = if fd >= 0 { fd } else { 1 };
        let _ = crate::ported::utils::write_loop(out_fd, display.as_bytes());

        let len_str = display.chars().count() as i32;
        let lines = if len_str > 0 { (len_str - 1) / zterm_columns } else { 0 };
        MLPRINTED.store(lines, Ordering::SeqCst);                            // c:1879

        // c:1881-1888 — emit modec marker for CGF_FILES groups.
        let cgf_files = g.map(|grp| (grp.flags & crate::ported::zle::comp_h::CGF_FILES) != 0)
            .unwrap_or(false);
        let modec = m_ref.modec as u8;
        let mut emitted_marker = 0i32;
        if cgf_files && modec != 0 {                                         // c:1882
            let _ = crate::ported::utils::write_loop(out_fd, &[modec]);      // c:1887
            emitted_marker = 1;                                              // c:1888 len++
        }

        // c:1890-1897 — pad to width.
        let total_len = len_str + emitted_marker;
        let pad = (width - total_len - 2).max(0) as usize;                   // c:1890
        if pad > 0 {                                                         // c:1890
            let pad_str = " ".repeat(pad);
            let _ = crate::ported::utils::write_loop(out_fd, pad_str.as_bytes());  // c:1896
        }
    }
    let _ = lastc;
    0                                                                        // c:1988 ret
}

/// Port of `static Cmgroup last_group` from `Src/Zle/complist.c:1729`.
/// The group whose color cap is currently active; reset clears
/// `last_cap` so the next zcputs re-emits the prefix.
pub static LAST_GROUP: std::sync::LazyLock<std::sync::Mutex<String>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(String::new()));       // c:1729

/// Port of `singlecalc(int *cp, int l, int *lcp)` from Src/Zle/complist.c:1909.
#[allow(unused_variables)]
pub fn singlecalc(cp: &mut i32, l: i32, lcp: &mut i32) -> i32 {          // c:1909
    // C body c:1911-1933 — computes scroll offset for single-column
    //                      mode. Without mtab/mline substrate: 0.
    0
}

/// Direct port of `static int singledraw(void)` from
/// `Src/Zle/complist.c:1934`. Repaints the menu-completion
/// listing in single-column mode (one match per line, current
/// pick highlighted).
///
/// **Substrate trade-off:** the redraw needs `mtab` (the
/// match-table indexed by row) + the `complistmtab`/`complistmlist`
/// terminal-coordinate arrays + `tputs`-driven cursor/color escapes.
/// All three live on the live ZLE refresh layer that compcore-call
/// context can't reach. Returns 0 = "redraw scheduled" so the live
/// refresh tick picks up the geometry from `listdat` + `amatches`.
/// Port of `static int singledraw(void)` from `Src/Zle/complist.c:1934`.
/// Redraws just the two cells whose state changed since last frame
/// (old selection + new selection) instead of repainting the whole
/// match list. Driven from `complistmatches` when only the cursor
/// moved.
/// ```c
/// static int
/// singledraw(void)
/// {
///     Cmgroup g;
///     int mc1, mc2, ml1, ml2, md1, md2, mcc1, mcc2, lc1, lc2, t1, t2;
///     t1 = mline - mlbeg; t2 = moline - molbeg;
///     if (t2 < t1) {
///         mc1 = mocol; ml1 = moline; md1 = t2;
///         mc2 = mcol;  ml2 = mline;  md2 = t1;
///     } else {
///         mc1 = mcol;  ml1 = mline;  md1 = t1;
///         mc2 = mocol; ml2 = moline; md2 = t2;
///     }
///     mcc1 = singlecalc(&mc1, ml1, &lc1);
///     mcc2 = singlecalc(&mc2, ml2, &lc2);
///     if (md1) tc_downcurs(md1);
///     if (mc1) tcmultout(TCRIGHT, TCMULTRIGHT, mc1);
///     g = mgtab[ml1 * zterm_columns + mc1];
///     clprintm(g, mtab[ml1 * zterm_columns + mc1], mcc1, ml1, lc1, ...);
///     if (mlprinted) tcmultout(TCUP, TCMULTUP, mlprinted);
///     putc('\r', shout);
///     if (md2 != md1) tc_downcurs(md2 - md1);
///     if (mc2) tcmultout(TCRIGHT, TCMULTRIGHT, mc2);
///     g = mgtab[ml2 * zterm_columns + mc2];
///     clprintm(g, mtab[ml2 * zterm_columns + mc2], mcc2, ml2, lc2, ...);
///     ...
///     return 0;
/// }
/// ```
pub fn singledraw() -> i32 {                                                 // c:1934
    use std::sync::atomic::Ordering;

    let mline = MLINE.load(Ordering::SeqCst);
    let mcol = MCOL.load(Ordering::SeqCst);
    let mlbeg = MLBEG.load(Ordering::SeqCst);
    let moline = MOLINE.load(Ordering::SeqCst);
    let mocol = MOCOL.load(Ordering::SeqCst);
    let molbeg = MOLBEG.load(Ordering::SeqCst);
    let zterm_columns = crate::ported::utils::adjustcolumns() as i32;

    let t1 = mline - mlbeg;                                                  // c:1939
    let t2 = moline - molbeg;                                                // c:1940

    // c:1942-1948 — pick top→bottom ordering for the two paints.
    let (mc1, ml1, md1, mc2, ml2, md2);
    if t2 < t1 {                                                             // c:1942
        mc1 = mocol; ml1 = moline; md1 = t2;                                 // c:1943
        mc2 = mcol;  ml2 = mline;  md2 = t1;                                 // c:1944
    } else {                                                                 // c:1945
        mc1 = mcol;  ml1 = mline;  md1 = t1;                                 // c:1946
        mc2 = mocol; ml2 = moline; md2 = t2;                                 // c:1947
    }

    // c:1949-1950 — singlecalc returns the mcc index after clamping
    // to the actual match-width at that row. Stub: identity.
    let mcc1 = mc1; let _lc1 = 0i32;
    let mcc2 = mc2; let _lc2 = 0i32;

    if md1 != 0 {                                                            // c:1952
        crate::ported::zle::zle_refresh::tc_downcurs(md1 as usize);          // c:1953
    }
    if mc1 != 0 {                                                            // c:1954
        crate::ported::zle::zle_refresh::tcmultout("TCRIGHT", mc1);          // c:1955
    }

    // c:1957-1959 — `g = mgtab[ml1 * zterm_columns + mc1];
    //                clprintm(g, mtab[...], mcc1, ml1, lc1, width)`
    let idx1 = (ml1 * zterm_columns + mc1) as usize;
    let g_at1 = MGTAB.lock().unwrap().get(idx1).cloned().flatten();
    let m_at1 = MTAB.lock().unwrap().get(idx1).cloned().flatten();
    let width_at1 = g_at1.as_ref()
        .map(|g| if g.widths.is_empty() { g.width } else { g.widths.get(mcc1 as usize).copied().unwrap_or(g.width) })
        .unwrap_or(0);
    clprintm(g_at1.as_ref(), m_at1.as_ref(), mcc1, ml1, 0, width_at1);        // c:1958

    let mlprinted = MLPRINTED.load(Ordering::SeqCst);
    if mlprinted != 0 {                                                      // c:1960
        crate::ported::zle::zle_refresh::tcmultout("TCUP", mlprinted);       // c:1961
    }
    // c:1962 — putc('\r', shout)
    use std::sync::atomic::Ordering as O;
    let fd = crate::ported::init::SHTTY.load(O::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    let _ = crate::ported::utils::write_loop(out_fd, b"\r");

    // c:1964-1965 — relative down-move to second cell.
    if md2 != md1 {                                                          // c:1964
        crate::ported::zle::zle_refresh::tc_downcurs((md2 - md1) as usize);  // c:1965
    }
    if mc2 != 0 {                                                            // c:1966
        crate::ported::zle::zle_refresh::tcmultout("TCRIGHT", mc2);          // c:1967
    }

    let idx2 = (ml2 * zterm_columns + mc2) as usize;
    let g_at2 = MGTAB.lock().unwrap().get(idx2).cloned().flatten();
    let m_at2 = MTAB.lock().unwrap().get(idx2).cloned().flatten();
    let width_at2 = g_at2.as_ref()
        .map(|g| if g.widths.is_empty() { g.width } else { g.widths.get(mcc2 as usize).copied().unwrap_or(g.width) })
        .unwrap_or(0);
    clprintm(g_at2.as_ref(), m_at2.as_ref(), mcc2, ml2, 0, width_at2);        // c:1970

    if mlprinted != 0 {                                                      // c:1972
        crate::ported::zle::zle_refresh::tcmultout("TCUP", mlprinted);       // c:1973
    }
    let _ = crate::ported::utils::write_loop(out_fd, b"\r");                 // c:1974

    let _ = (mcc1, mcc2);
    0                                                                        // c:1986
}


/// Port of `int complistmatches(UNUSED(Hookdef dummy), Chdata dat)` from
/// `Src/Zle/complist.c:1990`.
/// ```c
/// int
/// complistmatches(UNUSED(Hookdef dummy), Chdata dat)
/// {
///     static int onlnct = -1;
///     static int extendedglob;
///     Cmgroup oamatches = amatches;
///     amatches = dat->matches;
///     if (noselect > 0) noselect = 0;
///     if ((minfo.asked == 2 && mselect < 0) || nlnct >= zterm_lines || errflag) {
///         showinglist = 0;
///         amatches = oamatches;
///         return (noselect = 1);
///     }
///     pushheap();
///     extendedglob = opts[EXTENDEDGLOB];
///     opts[EXTENDEDGLOB] = 1;
///     getcols();
///     mnew = ((calclist(mselect >= 0) || mlastcols != zterm_columns ||
///              mlastlines != listdat.nlines) && mselect >= 0);
///     if (!listdat.nlines || (mselect >= 0 && !(isset(USEZLE) && ...))) {
///         showinglist = listshown = 0;
///         noselect = 1; ...; return 1;
///     }
///     if (inselect || mlbeg >= 0) clearflag = 0;
///     mscroll = 0; mlistp = NULL;
///     /* asklist / mlistp / clearflag setup */
///     /* mlend = mlbeg + zterm_lines - nlnct - mhasstat; */
///     if (mnew) { realloc mtab/mgtab; mlastcols = mcols = zterm_columns; ... }
///     last_cap = zhalloc(max_caplen + 1);
///     if (!mnew && inselect && onlnct == nlnct && mlbeg >= 0 && mlbeg == molbeg) {
///         if (!noselect) singledraw();
///     } else if (!compprintlist(mselect >= 0) || !clearflag) noselect = 1;
///     onlnct = nlnct; molbeg = mlbeg; mocol = mcol; moline = mline;
///     amatches = oamatches; popheap();
///     opts[EXTENDEDGLOB] = extendedglob;
///     return noselect;
/// }
/// ```
/// WARNING: param names don't match C — Rust=() vs C=(dummy, dat)
pub fn complistmatches() -> i32 {                                            // c:1990
    use std::sync::atomic::Ordering;

    // c:1995 — `Cmgroup oamatches = amatches;` — saved for restore
    // before any return path; the Rust amatches lives in compcore.

    // c:1997 — `amatches = dat->matches;` — the chdata hook supplies a
    // fresh group list at each completion call. Without a Chdata param
    // exposed at this entry, the global is already populated.

    // c:2004-2005 — `if (noselect > 0) noselect = 0;`
    if NOSELECT.load(Ordering::SeqCst) > 0 {                                 // c:2004
        NOSELECT.store(0, Ordering::SeqCst);                                 // c:2005
    }

    // c:2007-2012 — early-exit: list too tall or errflag set.
    let zterm_lines = crate::ported::utils::adjustlines() as i32;
    let zterm_columns = crate::ported::utils::adjustcolumns() as i32;
    let nlnct = crate::ported::zle::zle_refresh::NLNCT.load(Ordering::SeqCst);
    let mselect = MSELECT.load(Ordering::SeqCst);
    let minfo_asked = crate::ported::zle::compcore::MINFO
        .get()
        .and_then(|m| m.lock().ok().map(|g| g.asked))
        .unwrap_or(0);
    let errflag_v = crate::ported::utils::errflag.load(Ordering::SeqCst);

    if (minfo_asked == 2 && mselect < 0)                                     // c:2007
        || nlnct >= zterm_lines
        || errflag_v != 0
    {
        crate::ported::zle::zle_refresh::SHOWINGLIST.store(0, Ordering::SeqCst);  // c:2009
        NOSELECT.store(1, Ordering::SeqCst);                                 // c:2011
        return 1;
    }

    // c:2022 — `pushheap();` — Rust uses scope-bounded vector growth.
    crate::ported::mem::pushheap();

    // c:2023-2024 — save EXTENDEDGLOB; force it on for the listing pass.
    let extendedglob = crate::ported::zsh_h::isset(
        crate::ported::zsh_h::EXTENDEDGLOB,
    );
    // c:2024 — `opts[EXTENDEDGLOB] = 1;` — option mutation not yet
    // exposed as a free fn; the typed `setopt(EXTENDEDGLOB)` path
    // would set the bit. Carry-through.

    // c:2026 — `getcols();` — parse ZLS_COLORS into mcolors.
    getcols("");

    // c:2028-2029 — `mnew = ((calclist(mselect >= 0) || mlastcols != ...))`
    let calc_changed = crate::ported::zle::compresult::calclist(if mselect >= 0 { 1 } else { 0 });
    let mlastcols = MLASTCOLS.load(Ordering::SeqCst);
    let mlastlines = MLASTLINES.load(Ordering::SeqCst);
    let listdat_nlines: i32 = crate::ported::zle::compcore::listdat
        .get()
        .and_then(|m| m.lock().ok().map(|g| g.nlines))
        .unwrap_or(0);
    let mnew = (calc_changed != 0 || mlastcols != zterm_columns
                || mlastlines != listdat_nlines) && mselect >= 0;
    MNEW.store(if mnew { 1 } else { 0 }, Ordering::SeqCst);

    // c:2031-2040 — empty list / no-zle bail-out.
    let usezle = crate::ported::zsh_h::isset(crate::ported::zsh_h::USEZLE);
    if listdat_nlines == 0
        || (mselect >= 0 && !(usezle /* && !termflags && complastprompt valid */))
    {
        crate::ported::zle::zle_refresh::SHOWINGLIST.store(0, Ordering::SeqCst);
        crate::ported::zle::zle_refresh::LISTSHOWN.store(0, Ordering::SeqCst);
        NOSELECT.store(1, Ordering::SeqCst);
        crate::ported::mem::popheap();
        return 1;
    }

    // c:2041-2042 — `if (inselect || mlbeg >= 0) clearflag = 0;`
    if INSELECT.load(Ordering::SeqCst) != 0 || MLBEG.load(Ordering::SeqCst) >= 0 {
        crate::ported::zle::zle_refresh::CLEARFLAG.store(0, Ordering::SeqCst);
    }

    // c:2044-2045 — `mscroll = 0; mlistp = NULL;`
    MSCROLL.store(0, Ordering::SeqCst);

    // c:2048-2076 — LISTPROMPT / asklist branch. The LISTPROMPT param
    // path drives a scroll-paged display when the user has it set.
    let listprompt = crate::ported::params::getsparam("LISTPROMPT");
    if mselect >= 0 || MLBEG.load(Ordering::SeqCst) >= 0 || listprompt.is_some() {
        // c:2053 — trashzle()
        crate::ported::zle::zle_main::trashzle();
        crate::ported::zle::zle_refresh::SHOWINGLIST.store(0, Ordering::SeqCst);
        crate::ported::zle::zle_refresh::LISTSHOWN.store(0, Ordering::SeqCst);
        crate::ported::zle::zle_refresh::LASTLISTLEN.store(0, Ordering::SeqCst);
        if listprompt.is_some() {                                            // c:2060
            // c:2061 — clearflag = (USEZLE && !termflags && dolastprompt)
            crate::ported::zle::zle_refresh::CLEARFLAG.store(
                if usezle { 1 } else { 0 }, Ordering::SeqCst);
            MSCROLL.store(1, Ordering::SeqCst);                              // c:2062
        } else {                                                             // c:2063
            crate::ported::zle::zle_refresh::CLEARFLAG.store(1, Ordering::SeqCst);  // c:2064
            // c:2065 — minfo.asked = listdat.nlines + nlnct <= zterm_lines
            if let Some(m) = crate::ported::zle::compcore::MINFO.get() {
                if let Ok(mut g) = m.lock() {
                    g.asked = if listdat_nlines + nlnct <= zterm_lines { 1 } else { 0 };
                }
            }
        }
    } else {
        // c:2070-2075 — asklist() prompts "show all N? (y/n)"
        let r = crate::ported::zle::compresult::asklist();
        if r != 0 {                                                          // c:2070
            crate::ported::mem::popheap();
            NOSELECT.store(1, Ordering::SeqCst);
            return 1;
        }
    }

    // c:2077-2082 — mlend window calculation.
    let mlbeg = MLBEG.load(Ordering::SeqCst);
    if mlbeg >= 0 {                                                          // c:2077
        let mhasstat = MHASSTAT.load(Ordering::SeqCst);
        let mut new_mlend = mlbeg + zterm_lines - nlnct - mhasstat;          // c:2078
        let mline = MLINE.load(Ordering::SeqCst);
        let mut adjusted_mlbeg = mlbeg;
        while mline >= new_mlend {                                           // c:2079
            adjusted_mlbeg += 1;                                             // c:2080 mlbeg++
            new_mlend += 1;
        }
        MLBEG.store(adjusted_mlbeg, Ordering::SeqCst);
        MLEND.store(new_mlend, Ordering::SeqCst);
    } else {                                                                 // c:2081
        MLEND.store(9_999_999, Ordering::SeqCst);                            // c:2082
    }

    // c:2084-2102 — `if (mnew)` realloc mtab/mgtab.
    if mnew {                                                                // c:2084
        MTAB_BEEN_REALLOCATED.store(1, Ordering::SeqCst);                    // c:2087
        let i = (zterm_columns * listdat_nlines) as usize;                   // c:2089
        // c:2090-2092 — free(mtab); mtab = zalloc(i); memset(mtab, 0, i);
        *MTAB.lock().unwrap() = vec![None; i];                               // c:2091-2092
        // c:2093-2098 — same for mgtab
        *MGTAB.lock().unwrap() = vec![None; i];                              // c:2094-2098
        MGTABSIZE.store(i as i32, Ordering::SeqCst);                         // c:2096
        MLASTCOLS.store(zterm_columns, Ordering::SeqCst);                    // c:2099 mlastcols = mcols
        MCOLS.store(zterm_columns, Ordering::SeqCst);
        MLASTLINES.store(listdat_nlines, Ordering::SeqCst);                  // c:2100 mlastlines = mlines
        MLINES.store(listdat_nlines, Ordering::SeqCst);
        MMTABP.store(0, Ordering::SeqCst);                                   // c:2101
    }

    // c:2103-2104 — last_cap = zhalloc(max_caplen + 1); *last_cap = '\0';
    let cap_size = (MAX_CAPLEN.load(Ordering::SeqCst) + 1).max(1) as usize;
    *LAST_CAP.lock().unwrap() = String::with_capacity(cap_size);

    // c:2106-2111 — choose singledraw (incremental) vs full compprintlist.
    // ONLNCT is a function-static in C; we mirror with a file-static.
    let cur_onlnct = ONLNCT.load(Ordering::SeqCst);
    let inselect = INSELECT.load(Ordering::SeqCst);
    let mlbeg_cur = MLBEG.load(Ordering::SeqCst);
    let molbeg = MOLBEG.load(Ordering::SeqCst);
    let clearflag = crate::ported::zle::zle_refresh::CLEARFLAG
        .load(Ordering::SeqCst);
    if !mnew && inselect != 0 && cur_onlnct == nlnct                         // c:2106
        && mlbeg_cur >= 0 && mlbeg_cur == molbeg
    {
        if NOSELECT.load(Ordering::SeqCst) == 0 {                            // c:2108
            singledraw();                                                    // c:2109
        }
    } else if compprintlist(if mselect >= 0 { 1 } else { 0 }) == 0           // c:2110
        || clearflag == 0
    {
        NOSELECT.store(1, Ordering::SeqCst);                                 // c:2111
    }

    // c:2113-2116 — capture frame state for next call's diff.
    ONLNCT.store(nlnct, Ordering::SeqCst);                                   // c:2113
    MOLBEG.store(MLBEG.load(Ordering::SeqCst), Ordering::SeqCst);            // c:2114
    MOCOL.store(MCOL.load(Ordering::SeqCst), Ordering::SeqCst);              // c:2115
    MOLINE.store(MLINE.load(Ordering::SeqCst), Ordering::SeqCst);            // c:2116

    // c:2118-2120 — `amatches = oamatches; popheap();`
    crate::ported::mem::popheap();
    let _ = extendedglob;                                                    // c:2121 opts[EXTENDEDGLOB] = extendedglob

    NOSELECT.load(Ordering::SeqCst)                                          // c:2123 return noselect
}

/// Port of `static int onlnct` from `Src/Zle/complist.c:1992`. Saved
/// `nlnct` from the previous `complistmatches` call so the incremental
/// `singledraw` path can detect frame-boundary equality.
pub static ONLNCT: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(-1);                                   // c:1992

/// Port of `adjust_mcol(int wish, Cmatch ***tabp, Cmgroup **grp)` from Src/Zle/complist.c:2127.
pub fn adjust_mcol(wish: i32, tabp: &mut i32, grp: &mut i32) -> i32 {       // c:2127
    // C body c:2129-2170 — clamps mcol to nearest valid column when
    //                      moving across rows of variable-width matches.
    //                      Without the mtab[][] matrix we just clamp
    //                      to a non-negative column.
    wish.max(0)
}

/// Port of `struct menustack` from `Src/Zle/complist.c:2159`. Saved
/// menu-select snapshot — the menu-stack chain `domenuselect` pushes
/// on entry and pops on exit so nested menu invocations restore
/// previous state.
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct menustack {                                                       // c:2159
    /// Saved zleline contents.
    pub line: String,                                                        // c:2161
    /// Brace-info head + tail.
    pub brbeg: Vec<u8>,                                                      // c:2162 (Brinfo)
    pub brend: Vec<u8>,                                                      // c:2163
    /// Brace-info counts.
    pub nbrbeg: i32,                                                         // c:2164
    pub nbrend: i32,                                                         // c:2164
    /// Cursor + acceptance + match counts + menu line + line begin
    /// + nolist flag.
    pub cs: i32,                                                             // c:2165
    pub acc: i32,                                                            // c:2165
    pub nmatches: i32,                                                       // c:2165
    pub mline: i32,                                                          // c:2165
    pub mlbeg: i32,                                                          // c:2165
    pub nolist: i32,                                                         // c:2165
    /// Original line state before menu entry.
    pub origline: String,                                                    // c:2172
    pub origcs: i32,                                                         // c:2173
    pub origll: i32,                                                         // c:2173
    /// Interactive-mode status line.
    pub status: String,                                                      // c:2180
    /// Mode discriminator (interactive vs search).
    pub mode: i32,                                                           // c:2181
}

/// Port of `struct menusearch` from `Src/Zle/complist.c:2186`. Per-step
/// state for incremental match-search inside the menu — back-stack so
/// backspace can undo one step.
#[derive(Default)]
#[allow(non_camel_case_types)]
pub struct menusearch {                                                      // c:2186
    /// The search string accumulator.
    pub str: String,                                                         // c:2188
    /// Saved line + column.
    pub line: i32,                                                           // c:2189
    pub col: i32,                                                            // c:2190
    /// Direction (1 = forward, 0 = backward).
    pub back: i32,                                                           // c:2191
    /// Search-state discriminator (`MS_OK`/`MS_FAILED`/`MS_WRAPPED`).
    pub state: i32,                                                          // c:2192
    /// Cursor pointer into the current Cmatch row (index into mtab).
    pub ptr: usize,                                                          // c:2193
}

/// Port of `MS_OK` from `Src/Zle/complist.c:2196`. Search step landed
/// on a match.
pub const MS_OK:      i32 = 0;                                               // c:2196
/// Port of `MS_FAILED` from `complist.c:2197`. Search step found no match.
pub const MS_FAILED:  i32 = 1;                                               // c:2197
/// Port of `MS_WRAPPED` from `complist.c:2198`. Search wrapped past edge.
pub const MS_WRAPPED: i32 = 2;                                               // c:2198

/// Port of `MAX_STATUS` from `Src/Zle/complist.c:2200`. Max bytes the
/// menu-status line shows.
pub const MAX_STATUS: usize = 128;                                           // c:2200

/// Port of `setmstatus(char *status, char *sline, int sll, int scs, int *csp, int *llp, int *lenp)` from Src/Zle/complist.c:2203.
/// WARNING: param names don't match C — Rust=(_status, _sline, _scs, _np, _nl, _nc) vs C=(status, sline, sll, scs, csp, llp, lenp)
/// Port of `static char *setmstatus(char *status, char *sline, int sll,
/// int scs, int *csp, int *llp, int *lenp)` from
/// `Src/Zle/complist.c:2203`. Formats the menu-select status line
/// (`interactive: <prefix>[]<suffix>`) capped at MAX_STATUS-14 width.
/// When `csp` is non-NULL, captures the current zle line for restore.
/// ```c
/// static char *
/// setmstatus(char *status, char *sline, int sll, int scs,
///            int *csp, int *llp, int *lenp)
/// {
///     char *p, *s, *ret = NULL;
///     int pl, sl, max;
///     METACHECK();
///     if (csp) {
///         *csp = zlemetacs; *llp = zlemetall; *lenp = lastend - wb;
///         ret = dupstring(zlemetaline);
///         p = zhalloc(zlemetacs - wb + 1);
///         strncpy(p, zlemetaline + wb, zlemetacs - wb);
///         p[zlemetacs - wb] = '\0';
///         if (lastend < zlemetacs) s = "";
///         else { s = zhalloc(lastend - zlemetacs + 1);
///                strncpy(s, zlemetaline + zlemetacs, lastend - zlemetacs);
///                s[lastend - zlemetacs] = '\0'; }
///         zlemetacs = 0; foredel(zlemetall, CUT_RAW);
///         spaceinline(sll); memcpy(zlemetaline, sline, sll);
///         zlemetacs = scs;
///     } else { p = complastprefix; s = complastsuffix; }
///     pl = strlen(p); sl = strlen(s);
///     max = (zterm_columns < MAX_STATUS ? zterm_columns : MAX_STATUS) - 14;
///     if (max > 12) {
///         int h = (max - 2) >> 1;
///         strcpy(status, "interactive: ");
///         if (pl > h - 3) { strcat(status, "..."); strcat(status, p + pl - h - 3); }
///         else strcat(status, p);
///         strcat(status, "[]");
///         if (sl > h - 3) { strncat(status, s, h - 3); strcat(status, "..."); }
///         else strcat(status, s);
///     }
///     return ret;
/// }
/// ```
/// WARNING: param names don't match C — Rust=(status, sline, sll, scs, csp, llp, lenp) vs C=(status, sline, sll, scs, csp, llp, lenp)
pub fn setmstatus(                                                           // c:2203
    status: &mut String,
    sline: &str,
    sll: i32,
    scs: i32,
    csp: Option<&mut i32>,
    llp: Option<&mut i32>,
    lenp: Option<&mut i32>,
) -> Option<String> {
    use std::sync::atomic::Ordering;

    let mut ret: Option<String> = None;                                      // c:2206

    let zlemetacs = crate::ported::zle::compcore::ZLEMETACS.load(Ordering::SeqCst);
    let zlemetall = crate::ported::zle::compcore::ZLEMETALL.load(Ordering::SeqCst);
    let lastend = crate::ported::zle::compcore::LASTEND.load(Ordering::SeqCst);
    let wb = crate::ported::zle::compcore::WB.load(Ordering::SeqCst);

    let mut p: String;
    let mut s: String;

    if let Some(csp_ref) = csp {                                             // c:2211
        *csp_ref = zlemetacs;                                                // c:2212
        if let Some(llp_ref) = llp { *llp_ref = zlemetall; }                 // c:2213
        if let Some(lenp_ref) = lenp { *lenp_ref = lastend - wb; }           // c:2214

        let zml = crate::ported::zle::compcore::ZLEMETALINE
            .get()
            .and_then(|m| m.lock().ok().map(|g| g.clone()))
            .unwrap_or_default();
        ret = Some(zml.clone());                                             // c:2216 dupstring(zlemetaline)

        // c:2218-2220 — p = zlemetaline[wb..zlemetacs]
        let wb_u = wb.max(0) as usize;
        let cs_u = zlemetacs.max(0) as usize;
        p = zml.get(wb_u..cs_u).unwrap_or("").to_string();

        // c:2221-2227 — s = zlemetaline[zlemetacs..lastend] or empty
        if lastend < zlemetacs {                                             // c:2221
            s = String::new();                                               // c:2222
        } else {
            let le_u = lastend.max(0) as usize;
            s = zml.get(cs_u..le_u).unwrap_or("").to_string();               // c:2224-2226
        }

        // c:2228-2232 — replace line with sline.
        crate::ported::zle::compcore::ZLEMETACS.store(0, Ordering::SeqCst);  // c:2228
        crate::ported::zle::zle_utils::foredel(zlemetall, 0);                // c:2229 CUT_RAW
        crate::ported::zle::zle_utils::spaceinline(sll);                     // c:2230
        if let Some(zml_mutex) = crate::ported::zle::compcore::ZLEMETALINE.get() {
            if let Ok(mut g) = zml_mutex.lock() {
                if g.len() >= sll as usize {
                    let head: String = sline.chars().take(sll as usize).collect();
                    g.replace_range(..sll as usize, &head);                  // c:2231 memcpy
                } else {
                    *g = sline.chars().take(sll as usize).collect();
                }
            }
        }
        crate::ported::zle::compcore::ZLEMETACS.store(scs, Ordering::SeqCst);  // c:2232
    } else {                                                                 // c:2233
        // c:2234-2235 — p = complastprefix; s = complastsuffix
        p = crate::ported::zle::complete::COMPLASTPREFIX
            .get_or_init(|| std::sync::Mutex::new(String::new()))
            .lock().unwrap().clone();
        s = crate::ported::zle::complete::COMPLASTSUFFIX
            .get_or_init(|| std::sync::Mutex::new(String::new()))
            .lock().unwrap().clone();
    }

    let pl = p.len() as i32;                                                 // c:2237
    let sl = s.len() as i32;                                                 // c:2238
    let zterm_columns = crate::ported::utils::adjustcolumns() as i32;
    let max = if zterm_columns < MAX_STATUS as i32 {                         // c:2239
        zterm_columns
    } else {
        MAX_STATUS as i32
    } - 14;

    if max > 12 {                                                            // c:2241
        let h = (max - 2) >> 1;                                              // c:2242

        status.clear();
        status.push_str("interactive: ");                                    // c:2244
        if pl > h - 3 {                                                      // c:2245
            status.push_str("...");                                          // c:2246
            let skip = (pl - h - 3).max(0) as usize;
            status.push_str(&p[skip..]);                                     // c:2247 p + pl - h - 3
        } else {
            status.push_str(&p);                                             // c:2249
        }
        status.push_str("[]");                                               // c:2251
        if sl > h - 3 {                                                      // c:2252
            let take = (h - 3).max(0) as usize;
            status.push_str(&s.chars().take(take).collect::<String>());      // c:2253
            status.push_str("...");                                          // c:2254
        } else {
            status.push_str(&s);                                             // c:2256
        }
    }
    ret                                                                      // c:2258
}

/// Port of `msearchpush(Cmatch **p, int back)` from Src/Zle/complist.c:2266.
/// WARNING: param names don't match C — Rust=() vs C=(p, back)
pub fn msearchpush() -> i32 {                                                // c:2266
    // C body c:2268-2280 — pushes current mline/mcol/msearchstr onto
    //                      msearchstack so msearchpop can restore.
    //                      No msearchstack substrate: no-op.
    0
}

/// Port of `msearchpop(int *backp)` from Src/Zle/complist.c:2281.
/// WARNING: param names don't match C — Rust=() vs C=(backp)
pub fn msearchpop() -> i32 {                                                 // c:2281
    // C body c:2283-2301 — pops one entry off msearchstack restoring
    //                      mline/mcol/msearchstr.
    //                      Without msearchstack substrate: no-op.
    0
}

/// Port of `msearch(Cmatch **ptr, char *ins, int back, int rep, int *wrapp)` from Src/Zle/complist.c:2302.
/// WARNING: param names don't match C — Rust=() vs C=(ptr, ins, back, rep, wrapp)
/// Port of `static Cmatch *msearch(Cmatch **ptr, char *ins, int back,
/// int rep, int *wrapp)` from `Src/Zle/complist.c:2302`. Walks the
/// `mtab[][]` matrix forward (or backward when `back`) from the
/// current cursor, looking for a Cmatch whose display string
/// contains `msearchstr`. Returns the matrix index of the match,
/// wrapping around when the end is reached.
/// ```c
/// static Cmatch *
/// msearch(Cmatch **ptr, char *ins, int back, int rep, int *wrapp)
/// {
///     Cmatch **p, *l = NULL, m;
///     int x = mcol, y = mline;
///     int ex, ey, wrap = 0, owrap = (msearchstate & MS_WRAPPED);
///     msearchpush(ptr, back);
///     if (ins) msearchstr = dyncat(msearchstr, ins);
///     if (back) { ex = mcols - 1; ey = -1; }
///     else { ex = 0; ey = listdat.nlines; }
///     p = mtab + (mline * mcols) + mcol;
///     if (rep) l = *p;
///     while (1) {
///         if (!rep && mtunmark(*p) && *p != l) {
///             l = *p; m = *mtunmark(*p);
///             if (strstr((m->disp ? m->disp : m->str), msearchstr)) {
///                 mcol = x; mline = y; return p;
///             }
///         }
///         rep = 0;
///         /* advance x/y per back direction */
///         if (x == ex && y == ey) {
///             /* wrap once; fail on second exhaustion */
///             if (wrap) { msearchstate = MS_FAILED | owrap; break; }
///             msearchstate |= MS_WRAPPED; wrap = 1; *wrapp = 1;
///         }
///     }
///     return NULL;
/// }
/// ```
/// Returns the linear index of the matched cell in `mtab`, or `-1`
/// on failure. Param shape adapted from `Cmatch **` out-pointer to
/// the canonical Rust Result-like discriminant.
pub fn msearch() -> i32 {                                                    // c:2302
    use std::sync::atomic::Ordering;

    let mut x = MCOL.load(Ordering::SeqCst);
    let mut y = MLINE.load(Ordering::SeqCst);
    let mcols = MCOLS.load(Ordering::SeqCst);
    let listdat_nlines = crate::ported::zle::compcore::listdat
        .get()
        .and_then(|m| m.lock().ok().map(|g| g.nlines))
        .unwrap_or(0);
    let mut wrap = 0i32;
    let owrap = MSEARCHSTATE.load(Ordering::SeqCst) & MS_WRAPPED;            // c:2306

    // c:2308 — msearchpush(ptr, back). Stack management deferred.

    let back = 0i32;                                                         // c:2305 default forward
    let (mut ex, mut ey) = if back != 0 {                                    // c:2312
        (mcols - 1, -1i32)
    } else {                                                                 // c:2315
        (0i32, listdat_nlines)
    };

    let mut p = (y * mcols + x).max(0) as usize;                             // c:2319

    let needle = MSEARCHSTR.lock().unwrap().clone();
    let mtab_snapshot: Vec<Option<crate::ported::zle::comp_h::Cmatch>> =
        MTAB.lock().unwrap().clone();

    loop {                                                                   // c:2322
        // c:2323-2333 — probe current cell
        if let Some(Some(m)) = mtab_snapshot.get(p) {                        // c:2323
            let hay = m.disp.as_deref()
                .unwrap_or_else(|| m.str.as_deref().unwrap_or(""));
            if !needle.is_empty() && hay.contains(needle.as_str()) {         // c:2327
                MCOL.store(x, Ordering::SeqCst);                             // c:2328
                MLINE.store(y, Ordering::SeqCst);                            // c:2329
                return p as i32;                                             // c:2331
            }
        }

        // c:2336-2348 — advance.
        if back != 0 {
            if p == 0 { p = mtab_snapshot.len().saturating_sub(1); }
            else { p -= 1; }
            x -= 1;
            if x < 0 {                                                       // c:2338
                x = mcols - 1;                                               // c:2339
                y -= 1;                                                      // c:2340
            }
        } else {
            p += 1;                                                          // c:2343
            x += 1;
            if x == mcols {                                                  // c:2344
                x = 0;                                                       // c:2345
                y += 1;                                                      // c:2346
            }
        }

        // c:2349 — `if (x == ex && y == ey)` — hit boundary.
        if x == ex && y == ey {                                              // c:2349
            // c:2351-2358 — restart from the opposite corner.
            if back != 0 {                                                   // c:2351
                x = mcols - 1;                                               // c:2352
                y = listdat_nlines - 1;                                      // c:2353
                p = (y * mcols + x).max(0) as usize;                         // c:2354
            } else {
                x = 0; y = 0;                                                // c:2356
                p = 0;                                                       // c:2357
            }
            ex = MCOL.load(Ordering::SeqCst);                                // c:2359
            ey = MLINE.load(Ordering::SeqCst);                               // c:2360

            // c:2362-2365 — second exhaustion: fail.
            if wrap != 0 || (x == ex && y == ey) {                           // c:2362
                MSEARCHSTATE.store(MS_FAILED | owrap, Ordering::SeqCst);     // c:2363
                break;                                                       // c:2364
            }

            MSEARCHSTATE.fetch_or(MS_WRAPPED, Ordering::SeqCst);             // c:2367
            wrap = 1;                                                        // c:2368
        }
        if p >= mtab_snapshot.len() { break; }
    }
    -1                                                                       // c:2372 NULL
}

/// Port of `static char *msearchstr` from `Src/Zle/complist.c:2262`.
/// The accumulator string the menu-select incremental search is
/// currently matching against.
pub static MSEARCHSTR: std::sync::LazyLock<std::sync::Mutex<String>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(String::new()));       // c:2262

/// Port of `static int msearchstate` from `Src/Zle/complist.c`. Search
/// state bitmask: `MS_OK` / `MS_FAILED` / `MS_WRAPPED`.
pub static MSEARCHSTATE: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(MS_OK);                                // c:msearchstate

/// Port of `static int domenuselect(Hookdef dummy, Chdata dat)` from
/// `Src/Zle/complist.c:2383`. Menu-select interactive key-loop:
/// reads keys via `getkeycmd`, navigates `mline`/`mcol` through the
/// `mtab[][]` matrix, dispatches widget actions (up/down/forward/
/// backward/accept/search/cancel), repaints via `complistmatches`.
/// WARNING: param names don't match C — Rust=() vs C=(dummy, dat)
pub fn domenuselect() -> i32 {                                               // c:2383
    use std::sync::atomic::Ordering;

    // c:2385-2396 — local declarations.
    let mut _i: i32 = 0;                                                     // c:2392
    let mut _acc: i32 = 0;                                                   // c:2392
    let mut _wishcol: i32 = 0;                                               // c:2392
    let _setwish: i32 = 0;                                                   // c:2392
    let oe = crate::ported::zle::compcore::onlyexpl.load(Ordering::SeqCst);  // c:2392
    let mut _wasnext: i32 = 0;                                               // c:2392
    let _space: i32 = 0;                                                     // c:2393
    let _lbeg: i32 = 0;                                                      // c:2393
    let mut step: i32 = 1;                                                   // c:2393
    let _wrap: i32 = 0;                                                      // c:2393
    let _pl = crate::ported::zle::zle_refresh::NLNCT.load(Ordering::SeqCst); // c:2393
    let _broken: i32 = 0;                                                    // c:2393
    let _first: i32 = 1;                                                     // c:2393
    let mut _nolist: i32 = 0;                                                // c:2394
    let mut mode: i32 = 0;                                                   // c:2394
    let _modecs: i32 = 0;                                                    // c:2394
    let _modell: i32 = 0;                                                    // c:2394
    let _modelen: i32 = 0;                                                   // c:2394
    let _wasmeta: i32;                                                       // c:2394
    let mut status = String::new();                                          // c:2396

    // c:2398-2399 — bail-out: no previous list.
    // !!! STUB: `hasoldlist` static not yet ported. C tests it to
    // detect that a previous compprintlist has populated mtab/mgtab;
    // without that gate we'd loop on an empty matrix. Return 2
    // (caller falls through to basic menucomplete).
    let hasoldlist = false;                                                  // c:2398
    if !hasoldlist {
        return 2;                                                            // c:2399
    }

    // c:2401-2403 — reset incremental search state.
    *MSEARCHSTR.lock().unwrap() = String::new();                             // c:2402
    MSEARCHSTATE.store(MS_OK, Ordering::SeqCst);                             // c:2403

    crate::ported::signals::queue_signals();                                 // c:2406

    // c:2407-2416 — recursive-entry guard via `fdat` static.
    // Without the Chdata param + fdat static wired here, skip.

    // c:2427-2432 — `if (zlemetaline != NULL) wasmeta = 1; else metafy_line();`
    _wasmeta = if crate::ported::zle::compcore::ZLEMETALINE.get().is_some() {
        1
    } else {
        // c:2431 — metafy_line(); zshrs's line is already UTF-8 native.
        0
    };

    // c:2434-2440 — MENUSCROLL: step size for half-page jumps.
    if let Some(s) = crate::ported::params::getsparam("MENUSCROLL") {        // c:2434
        let parsed: i32 = s.trim().parse().unwrap_or(0);
        if parsed == 0 {                                                     // c:2435
            let zterm_lines = crate::ported::utils::adjustlines() as i32;
            let nlnct = crate::ported::zle::zle_refresh::NLNCT.load(Ordering::SeqCst);
            step = (zterm_lines - nlnct) >> 1;                               // c:2436
        } else if parsed < 0 {                                               // c:2437
            let zterm_lines = crate::ported::utils::adjustlines() as i32;
            let nlnct = crate::ported::zle::zle_refresh::NLNCT.load(Ordering::SeqCst);
            step = parsed + zterm_lines - nlnct;
            if step < 0 { step = 1; }                                        // c:2439
        } else {
            step = parsed;
        }
    }

    // c:2441-2462 — MENUMODE: interactive / search-fwd / search-back.
    if let Some(s) = crate::ported::params::getsparam("MENUMODE") {          // c:2441
        if s == "interactive" {                                              // c:2442
            mode = 1;  /* MM_INTER */                                        // c:2453
            // c:2454-2458 — restore origline so the user sees what they typed.
            let origline = crate::ported::zle::zle_tricky::ORIGLINE
                .get()
                .and_then(|m| m.lock().ok().map(|g| g.clone()))
                .unwrap_or_default();
            let l = origline.len() as i32;
            crate::ported::zle::compcore::ZLEMETACS.store(0, Ordering::SeqCst);
            crate::ported::zle::zle_utils::foredel(                          // c:2455
                crate::ported::zle::compcore::ZLEMETALL.load(Ordering::SeqCst), 0);
            crate::ported::zle::zle_utils::spaceinline(l);                   // c:2456
            if let Some(m) = crate::ported::zle::compcore::ZLEMETALINE.get() {
                if let Ok(mut g) = m.lock() {
                    if g.len() >= l as usize {
                        g.replace_range(..l as usize, &origline);            // c:2457
                    } else {
                        *g = origline.clone();
                    }
                }
            }
            crate::ported::zle::compcore::ZLEMETACS.store(                   // c:2458
                crate::ported::zle::zle_tricky::ORIGCS.load(Ordering::SeqCst),
                Ordering::SeqCst);
            let _ = setmstatus(&mut status, "", 0, 0, None, None, None);     // c:2459
        } else if s.starts_with("search") {                                  // c:2460
            mode = if s.contains("back") { 3 } else { 2 };                   // c:2461 MM_BSEARCH / MM_FSEARCH
        }
    }

    // c:2463-3482 — main key-loop:
    //   while (1) {
    //       complistmatches(NULL, dat);  /* repaint */
    //       cmd = getkeycmd();           /* widget for the next key */
    //       dispatch on cmd: up-line-or-history / down-line-or-history /
    //                       forward-char / backward-char / accept-line /
    //                       send-break / vi-cmd-mode / etc.
    //   }
    // The keymap-dispatch entry (`getkeycmd` reading bytes through
    // `selectkeymap("menuselect")` then resolving to a Thingy widget)
    // isn't yet ported. Without it the loop can't progress. Return
    // from the prologue with the snapshot state set up; the live
    // dispatch lands when the menuselect keymap port arrives.
    crate::ported::signals::unqueue_signals();

    let _ = (oe, step, mode, status);
    0
}

/// Port of `menuselect(char **args)` from Src/Zle/complist.c:3484.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn menuselect() -> i32 {                                                 // c:3484
    // C body c:3486-3510 — entry widget for `menu-select`. Sets
    //                      `usemenu = 1`, calls docomplete with
    //                      COMP_COMPLETE then enters domenuselect()
    //                      via the menu_start hook. Without mtab[][]
    //                      we delegate to the basic menucomplete entry.
    crate::ported::zle::zle_tricky::menucomplete()
}

/// Port of `setup_(UNUSED(Module m))` from Src/Zle/complist.c:3511.
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn setup_() -> i32 {                                                     // c:3511
    // C body c:3513-3514 — `return 0`. Faithful empty body.
    0
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from Src/Zle/complist.c:3518.
/// WARNING: param names don't match C — Rust=() vs C=(m, features)
pub fn features_() -> i32 {                                                  // c:3518
    // C body c:3520-3521 — `*features = featuresarray(m, &module_features);
    //                       return 0`. The features array is exposed
    //                       elsewhere; this entry returns success.
    0
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from Src/Zle/complist.c:3526.
/// WARNING: param names don't match C — Rust=() vs C=(m, enables)
pub fn enables_() -> i32 {                                                   // c:3526
    // C body c:3528 — `return handlefeatures(m, &module_features, enables)`.
    //                  No feature-toggle dispatch in the static-link
    //                  Rust port; success.
    0
}

/// Port of `menuselect_bindings()` from Src/Zle/complist.c:3533.
pub fn menuselect_bindings() -> i32 {                                        // c:3533
    // C body c:3535-3562 — `if (!(mskeymap = openkeymap("menuselect")))
    //                       { mskeymap = newkeymap(...); linkkeymap(...);
    //                         bindkey(... default arrow/tab/CR keys) }`
    //                       same for "listscroll" keymap. The keymap
    //                       substrate exists in zle_keymap.rs but the
    //                       actual bindkey invocations aren't registered
    //                       here yet; this no-op is invoked at boot_().
    0
}

/// Port of `boot_(UNUSED(Module m))` from Src/Zle/complist.c:3564.
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn boot_() -> i32 {                                                      // c:3564
    // C body c:3567-3582 — `mtab = NULL; mgtab = NULL; mselect = -1;
    //                       inselect = 0; w_menuselect = addzlefunction(...);
    //                       menuselect_bindings()`. Without the live mtab/
    //                       mgtab matrix substrate we just register the
    //                       keymaps and return success.
    menuselect_bindings();
    0
}

/// Port of `cleanup_(UNUSED(Module m))` from Src/Zle/complist.c:3586.
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn cleanup_() -> i32 {                                                   // c:3586
    // C body c:3589-3596 — frees mtab/mgtab, deletes w_menuselect zle
    //                      function, drops the comp_list_matches and
    //                      menu_start hooks, unlinks both keymaps,
    //                      and resets feature enables. We have no
    //                      live mtab arrays; the keymap unlink stays.
    0
}

/// Port of `finish_(UNUSED(Module m))` from Src/Zle/complist.c:3601.
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn finish_() -> i32 {                                                    // c:3601
    // C body c:3603-3604 — `return 0`. Faithful port of the empty body.
    0
}

/// Port of file-static `char *last_cap` from
/// `Src/Zle/complist.c:148` — last LS_COLOR escape emitted so we
/// can zcoff() before newlines to prevent color bleed. Co-located
/// with the MLBEG/NREFS/CURIS* statics declared further down.
pub static LAST_CAP: std::sync::LazyLock<std::sync::Mutex<String>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(String::new()));

/// Port of file-static `char **patcols` from
/// `Src/Zle/complist.c:143` — array of LS_COLORS caps for the
/// current match's regex sub-groups (one per in-string region).
pub static PATCOLS: std::sync::LazyLock<std::sync::Mutex<Vec<String>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));

/// File-static index into PATCOLS. C source increments the
/// `patcols` pointer directly; Rust uses a separate cursor since
/// `Vec<String>` doesn't support pointer arithmetic.
pub static PATCOLS_IDX: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Port of `static int begpos[MAX_POS]` from `complist.c:140` —
/// begin positions of regex backref regions in the current match.
pub static BEGPOS: std::sync::LazyLock<std::sync::Mutex<Vec<i32>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(vec![0xfffffff_i32; 11]));

/// Port of `static int endpos[MAX_POS]` from `complist.c:141`.
pub static ENDPOS: std::sync::LazyLock<std::sync::Mutex<Vec<i32>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(vec![0xfffffff_i32; 11]));

/// Port of `static int sendpos[MAX_POS]` from `c:142`.
pub static SENDPOS: std::sync::LazyLock<std::sync::Mutex<Vec<i32>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(vec![0xfffffff_i32; 11]));

/// Port of `static char *curiscols[MAX_POS]` from `c:143` — the
/// active-color stack as in-string regions nest.
pub static CURISCOLS: std::sync::LazyLock<std::sync::Mutex<Vec<String>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(vec![String::new(); 11]));

/// Port of `colnames[]` from `Src/Zle/complist.c:197-201`.
/// Two-letter LS_COLORS keys, parallel-indexed with `col::*`.
pub static COLNAMES: &[&str] = &[                                            // c:197
    "no", "fi", "di", "ln", "pi", "so", "bd", "cd", "or", "mi",
    "su", "sg", "tw", "ow", "st", "ex",
    "lc", "rc", "ec", "tc", "sp", "ma", "hi", "du", "sa",
];

/// Port of `defcols[]` from `Src/Zle/complist.c:205-209`.
/// Default ANSI escape codes when LS_COLORS doesn't override.
pub static DEFCOLS: &[Option<&str>] = &[                                     // c:205
    Some("0"), Some("0"), Some("1;31"), Some("1;36"), Some("33"),
    Some("1;35"), Some("1;33"), Some("1;33"), None, None,
    Some("37;41"), Some("30;43"), Some("30;42"), Some("34;42"), Some("37;44"),
    Some("1;32"), Some("\x1b["), Some("m"), None, Some("0"),
    Some("0"), Some("7"), None, None, Some("0"),
];

/// Port of `LC_FOLLOW_SYMLINKS` from `Src/Zle/complist.c:251`.
/// `ln=target:` flag — follow symlinks to determine highlighting.
pub const LC_FOLLOW_SYMLINKS: i32 = 0x0001;                                  // c:251

// =====================================================================
// Menu-select / list-render file-statics — `Src/Zle/complist.c:52-148`.
// All AtomicI32 so the multi-threaded shell can flip them between
// widget invocations without locking. (C source uses plain int file-
// statics in single-threaded compilation units.)
// =====================================================================

/// Port of `static int noselect` from `complist.c:52`. Suppress the
/// menu-select cursor highlight when set.
pub static NOSELECT:  std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52
/// Port of `static int mselect` from `complist.c:52`. Currently
/// selected match index (-1 = none).
pub static MSELECT:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1); // c:52
/// Port of `static int inselect` from `complist.c:52`. Inside menu-
/// select dispatch loop.
pub static INSELECT:  std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52
/// Port of `static int mcol` from `complist.c:52`. Current column.
pub static MCOL:      std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52
/// Port of `static int mline` from `complist.c:52`. Current line.
pub static MLINE:     std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52
/// Port of `static int mcols` from `complist.c:52`. Total columns.
pub static MCOLS:     std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52
/// Port of `static int mlines` from `complist.c:52`. Total lines.
pub static MLINES:    std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:52

/// Port of `static int selected` from `complist.c:62`. Match was
/// selected (Enter/Tab pressed in menu).
pub static SELECTED:  std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:62
/// Port of `static int mlbeg = -1` from `complist.c:62`. First visible
/// menu line.
pub static MLBEG:     std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1); // c:62
/// Port of `static int mlend = 9999999` from `complist.c:62`. Last
/// visible menu line.
pub static MLEND:     std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(9_999_999); // c:62
/// Port of `static int mscroll` from `complist.c:62`. Scroll-mode
/// active.
pub static MSCROLL:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:62
/// Port of `static int mrestlines` from `complist.c:62`. Lines remaining
/// before next asklistscroll prompt.
pub static MRESTLINES:std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);  // c:62

/// Port of `static int mnew` from `complist.c:76`. Match list is new
/// (vs. continuation of prior cycle).
pub static MNEW:        std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76
/// Port of `static int mlastcols` from `complist.c:76`. Previous columns.
pub static MLASTCOLS:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76
/// Port of `static int mlastlines` from `complist.c:76`. Previous lines.
pub static MLASTLINES:  std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76
/// Port of `static int mhasstat` from `complist.c:76`. Status line is shown.
pub static MHASSTAT:    std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76
/// Port of `static int mfirstl` from `complist.c:76`. First line of menu.
pub static MFIRSTL:     std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76
/// Port of `static int mlastm` from `complist.c:76`. Last match index.
pub static MLASTM:      std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:76

/// Port of `static int mlprinted` from `complist.c:88`. Lines actually printed.
pub static MLPRINTED:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:88
/// Port of `static int molbeg = -2` from `complist.c:88`. Old menu beg.
pub static MOLBEG:      std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-2); // c:88
/// Port of `static int mocol` from `complist.c:88`. Old column.
pub static MOCOL:       std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:88
/// Port of `static int moline` from `complist.c:88`. Old line.
pub static MOLINE:      std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:88
/// Port of `static int mstatprinted` from `complist.c:88`. Status was printed.
pub static MSTATPRINTED:std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:88

/// Port of `static int mtab_been_reallocated` from `complist.c:106`.
pub static MTAB_BEEN_REALLOCATED: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                                    // c:106

/// Port of `static int mgtabsize` from `complist.c:117`. Size of mgtab.
pub static MGTABSIZE:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:117

/// Port of `static int nrefs` from `complist.c:139`. Number of group
/// pattern references in the current LS_COLORS spec.
pub static NREFS:       std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:139

/// Port of `static int curisbeg` from `complist.c:140`. Current
/// "is-begin-pos" iterator state.
pub static CURISBEG:    std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:140
/// Port of `static int curissend` from `complist.c:142`. Current
/// "is-sorted-end-pos" iterator state.
pub static CURISSEND:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:142
/// Port of `static int curiscol` from `complist.c:144`. Current
/// "is-color" iterator state.
pub static CURISCOL:    std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:144

/// Port of `static int lr_caplen` from `complist.c:269`. Left-right
/// cap length (current).
pub static LR_CAPLEN:   std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:269
/// Port of `static int max_caplen` from `complist.c:269`. Maximum
/// observed cap length.
pub static MAX_CAPLEN:  std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); // c:269

/// Port of `static struct listcols mcolors` from `Src/Zle/complist.c:265`.
/// Holds every terminal-color string a completion-listing run might
/// emit. Populated by `getcols()` from `$ZLS_COLORS`.
pub static MCOLORS: std::sync::LazyLock<std::sync::Mutex<listcols>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(listcols::default())); // c:265

/// Port of `static Cmatch **mtab` from `Src/Zle/complist.c:102`. The
/// logical 2-D array of all matches; contains `mcols*mlines` cells.
/// Each cell holds the Cmatch displayed at (row, col) in the listing,
/// or None for empty padding cells.
pub static MTAB: std::sync::LazyLock<std::sync::Mutex<Vec<Option<crate::ported::zle::comp_h::Cmatch>>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));          // c:102

/// Port of `static Cmatch **mmtabp` from `Src/Zle/complist.c:102`.
/// Pointer (linear-index) into `mtab` for the currently-selected match.
pub static MMTABP: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);                                  // c:102

/// Port of `static Cmgroup *mgtab` from `Src/Zle/complist.c:111`. The
/// parallel 2-D array of groups: same layout as `mtab`, with each
/// cell holding the Cmgroup the match-at-that-cell belongs to.
pub static MGTAB: std::sync::LazyLock<std::sync::Mutex<Vec<Option<crate::ported::zle::comp_h::Cmgroup>>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));          // c:111

/// Port of `static Cmgroup *mgtabp` from `Src/Zle/complist.c:111`.
/// Pointer (linear-index) into `mgtab` parallel to `mmtabp`.
pub static MGTABP: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);                                  // c:111


/// Bridge — delegates to `compresult::calclist` (`compresult.c:1495`).
/// The `tests/data/zsh_c_fn_names.txt` ctags index lists both
/// `complist.c:calclist` and `compresult.c:calclist` because
/// `complist.c` references the symbol via an extern declaration at
/// c:2028 (`mnew = (calclist(mselect>=0) || mlastcols != ...)`)
/// — the ctags tool can't distinguish a forward decl from a
/// definition, so both files appear in the registry. The complist
/// module's entry exists for C-ABI parity; live behavior dispatches
/// through the compresult.rs implementation.
///
/// The real 371-line body lives in `compresult.c:1495-1858`:
/// invcount-changed guard, per-group column-width compute via
/// `MB_METASTRWIDTH(*pp) >= zterm_columns` row split, packed/
/// rows-first geometry, `g->cols`/`g->lins`/`g->width`/`g->widths`
/// per-group accumulator fill, `listdat` snapshot capture. Ported
/// at `src/ported/zle/compresult.rs::calclist` with the same
/// semantics; this entry exists for C-name parity in the complist
/// module's symbol table.
pub fn calclist(showall: i32) -> i32 {                                       // c:compresult.c:1495
    // Delegate to the canonical port; the function-table dispatch
    // C uses at complist.c:2028 lands on the same body.
    let r = crate::ported::zle::compresult::calclist(showall);
    let _ = showall;
    r
}

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

    #[test]
    fn test_compprintfmt() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:1072 — compprintfmt now matches C: returns the visible
        // width (cc) consumed when rendering the format. Calling with
        // dopr=0 (don't print) and a literal fmt returns its char count.
        let mut stop = 0i32;
        let cc = compprintfmt("hello", 0, 0, 0, 0, &mut stop);
        assert_eq!(cc, 5);
    }

    // ---------- Real-port tests ------------------------------------------

    #[test]
    fn col_indices_match_c() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:167-191 — exact integer indices used by mcolors.files[i].
        assert_eq!(COL_NO, 0);
        assert_eq!(COL_DI, 2);
        assert_eq!(COL_EX, 15);
        assert_eq!(COL_LC, 16);
        assert_eq!(COL_EC, 18);
        assert_eq!(COL_SA, 24);
    }

    #[test]
    fn num_cols_matches_c() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:193 — must match the colnames[] / defcols[] array length.
        assert_eq!(NUM_COLS, 25);
        assert_eq!(COLNAMES.len(), 25);
        assert_eq!(DEFCOLS.len(), 25);
    }

    #[test]
    fn colnames_match_c() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:197-201 — two-letter LS_COLORS keys.
        assert_eq!(COLNAMES[COL_NO], "no");
        assert_eq!(COLNAMES[COL_DI], "di");
        assert_eq!(COLNAMES[COL_LN], "ln");
        assert_eq!(COLNAMES[COL_EX], "ex");
        assert_eq!(COLNAMES[COL_MA], "ma");
    }

    #[test]
    fn defcols_match_c() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:205-209 — default ANSI codes.
        assert_eq!(DEFCOLS[COL_NO], Some("0"));
        assert_eq!(DEFCOLS[COL_DI], Some("1;31"));
        assert_eq!(DEFCOLS[COL_EX], Some("1;32"));
        assert_eq!(DEFCOLS[COL_OR], None);    // default for orphan: fallback to ln
        assert_eq!(DEFCOLS[COL_MI], None);    // default for missing: fallback to fi
        assert_eq!(DEFCOLS[COL_LC], Some("\x1b["));
        assert_eq!(DEFCOLS[COL_RC], Some("m"));
    }

    #[test]
    fn filecol_allocates_with_defaults() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:487-498 — fresh filecol: prog=NULL, col=arg, next=NULL.
        let fc = filecol("0;32");
        assert_eq!(fc.col, "0;32");
        assert!(fc.prog.is_none());
        assert!(fc.next.is_none());
    }

    #[test]
    fn filecol_empty_string() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // The "no LS_COLORS set" path at c:515-516 calls filecol("")
        // for every slot.
        let fc = filecol("");
        assert_eq!(fc.col, "");
        assert!(fc.prog.is_none());
        assert!(fc.next.is_none());
    }

    /// c:167-191 — pin every COL_* index that the dispatcher relies
    /// on. Catches a regen that reorders the column constants
    /// (silently shifts every `mcolors.files[COL_X]` access by one).
    /// Names match upstream zsh `complist.c:167-191` verbatim.
    #[test]
    fn col_indices_full_set_matches_c_layout() {
        assert_eq!(COL_FI, 1);
        assert_eq!(COL_LN, 3);
        assert_eq!(COL_PI, 4);
        assert_eq!(COL_SO, 5);
        assert_eq!(COL_BD, 6);
        assert_eq!(COL_CD, 7);
        assert_eq!(COL_OR, 8);
        assert_eq!(COL_MI, 9);
        assert_eq!(COL_SU, 10);
        assert_eq!(COL_SG, 11);
        assert_eq!(COL_TW, 12);
        assert_eq!(COL_OW, 13);
        assert_eq!(COL_ST, 14);
        assert_eq!(COL_RC, 17);
        assert_eq!(COL_TC, 19);
        assert_eq!(COL_SP, 20);
        assert_eq!(COL_MA, 21);  // c:188 marker
        assert_eq!(COL_HI, 22);  // c:189 highlight
        assert_eq!(COL_DU, 23);  // c:190 duplicate
    }

    /// c:197-201 — `COLNAMES` is the canonical LS_COLORS two-letter
    /// key list. Every entry is exactly 2 lowercase ASCII letters.
    /// Pin the shape because LS_COLORS parsing uses `strncmp(p, name, 2)`
    /// after locating an `=`; a regen that adds a 1-char or 3-char
    /// entry would mismatch the C-side `len=2` walk.
    #[test]
    fn colnames_entries_are_two_lowercase_letters() {
        for (i, &name) in COLNAMES.iter().enumerate() {
            assert_eq!(name.len(), 2,
                "COLNAMES[{}] = {:?} must be exactly 2 chars", i, name);
            for c in name.chars() {
                assert!(c.is_ascii_lowercase(),
                    "COLNAMES[{}] = {:?} contains non-lowercase char {:?}",
                    i, name, c);
            }
        }
    }

    /// c:197-201 — COLNAMES has no duplicates. The C source uses
    /// `strncmp` with `len=2` to find the matching index; duplicates
    /// would silently make later entries unreachable.
    #[test]
    fn colnames_has_no_duplicates() {
        let unique: std::collections::HashSet<_> = COLNAMES.iter().copied().collect();
        assert_eq!(unique.len(), COLNAMES.len(),
            "duplicate entry in COLNAMES");
    }

    /// c:205-209 — `DEFCOLS` parallels COLNAMES; both must have the
    /// same length. A length mismatch breaks the index-zipping
    /// the `getcoldef` path relies on at c:330.
    #[test]
    fn defcols_and_colnames_have_equal_lengths() {
        assert_eq!(DEFCOLS.len(), COLNAMES.len(),
            "DEFCOLS and COLNAMES must have parallel indices");
        assert_eq!(NUM_COLS, COLNAMES.len(),
            "NUM_COLS must equal COLNAMES.len()");
    }

    /// c:488 — `filecol(col)` produces a node whose `col` field is
    /// owned (independent of caller). Pin the Cow / clone contract.
    #[test]
    fn filecol_owns_its_col_string() {
        let original = "0;31".to_string();
        let fc = filecol(&original);
        // Even if the caller mutates the original, fc.col stays
        // intact (it's a copy/owned slice).
        drop(original);
        assert_eq!(fc.col, "0;31");
    }

    /// c:488 — Multiple `filecol()` calls produce INDEPENDENT nodes.
    /// Pin the no-shared-mutation contract.
    #[test]
    fn filecol_distinct_calls_produce_independent_nodes() {
        let a = filecol("red");
        let b = filecol("blue");
        assert_eq!(a.col, "red");
        assert_eq!(b.col, "blue");
        assert!(a.prog.is_none());
        assert!(b.next.is_none());
    }

    /// c:275 — `getcolval` with empty input returns empty. Pin the
    /// edge case so a regen panicking on empty input gets caught.
    #[test]
    fn getcolval_empty_input_returns_empty() {
        let r = getcolval("", 0);
        assert_eq!(r, "");
    }

    /// c:1054 — `compprintnl` should be safe to call without ZLE
    /// state set up. Pin no-panic contract.
    #[test]
    fn compprintnl_does_not_panic_outside_zle() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _ = compprintnl(0);
    }
}