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
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
//! `buf` holds metafied bytes (`Src/prompt.c` `char *buf`); callers that need
//! Unicode text run `unmetafy` (see [`buf_vars::expanded_utf8`]).
//!
//! `prompt_tls` holds values C reads as file-scope globals. Call
//! `prompt_tls::sync_from_globals` before expansion to refresh from
//! the canonical C globals (paramtab, LASTVAL, curhist, JOBTAB, ...).

use std::cell::RefCell;
use std::env;
/// Thread-local mirrors of zsh globals read during `promptexpand()` (logical
/// `$PWD`, `$?`, `cmdstack`, …). C uses scattered globals; zshrs uses TLS,
/// then copies into `buf_vars` for each expansion walk.
pub(crate) mod prompt_tls {
    use std::cell::RefCell;
    use std::env;

    thread_local! {
        pub(super) static PWD: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static HOME: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static USER: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static HOST: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static HOST_SHORT: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static TTY: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static LASTVAL: RefCell<i32> = const { RefCell::new(0) };
        pub(super) static HISTNUM: RefCell<i64> = const { RefCell::new(1) };
        pub(super) static SHLVL: RefCell<i32> = const { RefCell::new(1) };
        pub(super) static NUM_JOBS: RefCell<i32> = const { RefCell::new(0) };
        pub(super) static IS_ROOT: RefCell<bool> = const { RefCell::new(false) };
        pub(super) static CMDSTACK: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
        pub(super) static PSVAR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
        pub(super) static TERM_WIDTH: RefCell<usize> = const { RefCell::new(80) };
        pub(super) static LINENO: RefCell<i64> = const { RefCell::new(1) };
        pub(super) static SCRIPTNAME: RefCell<Option<String>> = const { RefCell::new(None) };
        pub(super) static SCRIPTFILENAME: RefCell<Option<String>> =
            const { RefCell::new(None) };
        pub(super) static ARGEXTRA: RefCell<String> = const { RefCell::new(String::new()) };
        pub(super) static FUNC_LINE_BASE: RefCell<Option<i64>> = const { RefCell::new(None) };
        pub(super) static FUNCSTACK_FILENAME: RefCell<Option<String>> =
            const { RefCell::new(None) };
    }

    /// Populate prompt-side thread-locals from the C globals each
    /// `Src/prompt.c` field maps to. Replaces an earlier read of
    /// `ShellExecutor` state with the canonical C source:
    ///   - `$PWD`/`$HOME`/`$USER`/`$SHLVL`/`$LINENO` etc. → paramtab
    ///     reads via `getsparam(name)` (params.c:3076)
    ///   - `$?` → LASTVAL atomic (builtin.c:6443 lastval)
    ///   - `curhist` → HISTNUM atomic (hist.c:233)
    ///   - active job count → JOBTAB scan (jobs.c:88)
    ///   - PSVAR → paramtab "psvar" array
    ///   - term width → `adjustcolumns()` (utils.c)
    ///   - scriptname → utils.rs::scriptname()
    pub(crate) fn sync_from_globals() {
        use crate::ported::params::getsparam;

        let pwd = getsparam("PWD")
            .filter(|p| !p.is_empty())
            .or_else(|| env::var("PWD").ok().filter(|p| !p.is_empty()))
            .or_else(|| {
                env::current_dir()
                    .ok()
                    .map(|p| p.to_string_lossy().to_string())
            })
            .unwrap_or_else(|| "/".to_string());
        let home = getsparam("HOME").unwrap_or_default();
        let user = getsparam("USER")
            .or_else(|| getsparam("LOGNAME"))
            .or_else(|| env::var("USER").ok())
            .or_else(|| env::var("LOGNAME").ok())
            .unwrap_or_else(|| "user".to_string());
        let host = getsparam("HOST")
            .or_else(|| {
                hostname::get().ok().map(|h| h.to_string_lossy().to_string())
            })
            .unwrap_or_else(|| "localhost".to_string());
        let host_short = host.split('.').next().unwrap_or(&host).to_string();
        let shlvl = getsparam("SHLVL")
            .and_then(|s| s.parse().ok())
            .or_else(|| env::var("SHLVL").ok().and_then(|s| s.parse().ok()))
            .unwrap_or(1);
        PWD.with(|c| *c.borrow_mut() = pwd);
        HOME.with(|c| *c.borrow_mut() = home);
        USER.with(|c| *c.borrow_mut() = user);
        HOST.with(|c| *c.borrow_mut() = host);
        HOST_SHORT.with(|c| *c.borrow_mut() = host_short);
        TTY.with(|c| c.borrow_mut().clear());
        // c:builtin.c:6443 lastval — the C global $?. The canonical
        // store is `builtin::LASTVAL` (AtomicI32). All status writes
        // (vm.last_status updates, exec.last_status setters, and
        // signals.rs:759 SIGCHLD) keep this current via
        // `LASTVAL.store`; prompt expansion just reads it.
        LASTVAL.with(|c| {
            *c.borrow_mut() = crate::ported::builtin::LASTVAL
                .load(std::sync::atomic::Ordering::Relaxed);
        });
        // c:hist.c:233 curhist
        HISTNUM.with(|c| {
            *c.borrow_mut() =
                crate::ported::hist::curhist.load(std::sync::atomic::Ordering::Relaxed);
        });
        SHLVL.with(|c| *c.borrow_mut() = shlvl);
        // c:jobs.c:88 jobtab — count in-use job slots
        NUM_JOBS.with(|c| {
            *c.borrow_mut() = crate::ported::jobs::JOBTAB
                .get_or_init(|| std::sync::Mutex::new(Vec::new()))
                .lock()
                .map(|t| t.iter().filter(|j| j.is_inuse()).count() as i32)
                .unwrap_or(0);
        });
        IS_ROOT.with(|c| *c.borrow_mut() = unsafe { libc::geteuid() } == 0);
        // c:prompt.c:56 cmdstack — the canonical store is the
        // file-static CMDSTACK at the bottom of this file.
        CMDSTACK.with(|c| {
            *c.borrow_mut() = super::CMDSTACK.with(|stack| stack.borrow().clone());
        });
        // c:params.c PSVAR special — array read from paramtab.
        PSVAR.with(|c| {
            *c.borrow_mut() = crate::ported::params::paramtab().read()
                .ok()
                .and_then(|t| t.get("psvar").and_then(|p| p.u_arr.clone()))
                .unwrap_or_default();
        });
        // c:utils.c adjustcolumns — re-read TIOCGWINSZ.
        TERM_WIDTH.with(|c| {
            *c.borrow_mut() = crate::ported::utils::adjustcolumns();
        });
        LINENO.with(|c| {
            *c.borrow_mut() = getsparam("LINENO")
                .and_then(|s| s.parse::<i64>().ok())
                .unwrap_or(1);
        });
        // c:utils.c:36 scriptname
        let scriptname = crate::ported::utils::scriptname_get();
        SCRIPTNAME.with(|c| *c.borrow_mut() = scriptname.clone()
            .or_else(|| getsparam("0")));
        SCRIPTFILENAME.with(|c| *c.borrow_mut() = scriptname.clone()
            .or_else(|| getsparam("0")));
        FUNC_LINE_BASE.with(|c| *c.borrow_mut() = None);
        FUNCSTACK_FILENAME.with(|c| {
            *c.borrow_mut() = crate::ported::modules::parameter::FUNCSTACK
                .lock().ok()
                .and_then(|s| s.last().and_then(|fs| fs.filename.clone()));
        });
        ARGEXTRA.with(|c| {
            *c.borrow_mut() = getsparam("ZSH_ARGZERO")
                .or_else(|| env::args().next())
                .unwrap_or_else(|| "zsh".to_string());
        });
    }
}

/// `struct buf_vars` from `Src/prompt.c:76-121`. `dontcount` is C `%{`/`%}`
/// nesting; `in_escape` holds readline `\x01`/`\x02` glue only.
/// `last` pointer / full trunc `bp1` realloc: TODO.
#[allow(non_camel_case_types)]
pub struct buf_vars {                                                        // c:Src/prompt.c:76
    pwd: String,
    home: String,
    user: String,
    host: String,
    host_short: String,
    tty: String,
    lastval: i32,
    histnum: i64,
    shlvl: i32,
    num_jobs: i32,
    is_root: bool,
    cmd_stack: Vec<u8>,
    psvar: Vec<String>,
    term_width: usize,
    lineno: i64,
    scriptname: Option<String>,
    scriptfilename: Option<String>,
    argzero: String,
    func_line_base: Option<i64>,
    funcstack_filename: Option<String>,
    pub buf: Vec<u8>,
    pub bufspc: usize,
    pub bp: usize,
    pub bufline: usize,
    pub bp1: Option<usize>,
    pub fm: String,
    pub fm_pos: usize,
    pub truncwidth: i32,
    pub dontcount: i32,
    pub trunccount: i32,
    pub rstring: Option<String>,
    pub Rstring: Option<String>,
    attrs: zattr,
    in_escape: bool,
    prompt_percent: bool,
    prompt_bang: bool,
}

// Note: there is no Rust helper for `cmdnames[cmdstack[t0]]` — C
// uses the bare array indexing inline (`Src/prompt.c:835`,
// `:846`, `:861`, `:872`). Use `CMDNAMES.get(b as usize).copied()`
// at every call site to mirror that pattern faithfully.

// `pub struct zattr` and `pub enum Color` — DELETED per user
// directive. Both were Rust-only abstractions over the canonical
// `zattr` (u64) bitfield from `Src/zsh.h:2685-2741`. C packs every
// attribute (bold/faint/standout/underline/italic) PLUS the
// foreground colour (24 bits), background colour (24 bits), and
// 24-bit-or-palette flags into a single 64-bit word. The Rust
// port now uses the canonical `crate::ported::zsh_h::zattr`
// directly; helpers below mirror the C bit-twiddling macros.
//
// Bit layout (matches Src/zsh.h:2694-2741 exactly):
//   0x0001 TXTBOLDFACE / 0x0002 TXTFAINT / 0x0004 TXTSTANDOUT /
//   0x0008 TXTUNDERLINE / 0x0010 TXTITALIC / 0x0020 TXTFGCOLOUR /
//   0x0040 TXTBGCOLOUR / 0x4000 TXT_ATTR_FG_24BIT /
//   0x8000 TXT_ATTR_BG_24BIT
//   bits 16-39: TXT_ATTR_FG_COL_MASK (palette index 0-255 OR
//               packed RGB if TXT_ATTR_FG_24BIT)
//   bits 40-63: TXT_ATTR_BG_COL_MASK (same for BG)
// `zattr` is the canonical C typedef from Src/zsh.h:2689
// (`typedef uint64_t zattr;`). Imported directly below.
use crate::ported::zsh_h::{
    TXTBOLDFACE, TXTFGCOLOUR, TXTBGCOLOUR, TXTSTANDOUT, TXTUNDERLINE, // c:zsh.h:2694
    TXT_ATTR_FG_COL_MASK, TXT_ATTR_FG_COL_SHIFT,
    TXT_ATTR_BG_COL_MASK, TXT_ATTR_BG_COL_SHIFT,
    TXT_ATTR_FG_24BIT, TXT_ATTR_BG_24BIT,
    TXT_ATTR_FG_MASK, TXT_ATTR_BG_MASK,
    zattr,
};
use crate::zsh_h::{Inpar, Nularg, Outpar};

// ---------------------------------------------------------------------------
// Remaining missing functions from prompt.c
// ---------------------------------------------------------------------------

/// Get a prompt-friendly path with optional tilde substitution.
/// Port of `promptpath(char *p, int npath, int tilde)` from Src/prompt.c:134 — used for `%~`,
/// `%/`, `%c`, etc. The `npath` argument trims to the last N
/// components.
/// WARNING: param names don't match C — Rust=(path, npath, tilde, home) vs C=(p, npath, tilde)
pub fn promptpath(path: &str, npath: usize, tilde: bool, home: &str) -> String { // c:134
    let display = if tilde && !home.is_empty() && path.starts_with(home) {
        let rest = &path[home.len()..];
        if rest.is_empty() || rest.starts_with('/') {
            format!("~{}", rest)
        } else {
            path.to_string()
        }
    } else {
        path.to_string()
    };

    if npath == 0 {
        return display;
    }

    // Take last npath components
    let components: Vec<&str> = display.split('/').filter(|s| !s.is_empty()).collect();
    if components.len() <= npath {
        return display;
    }
    components[components.len() - npath..].join("/")
}

// `pub struct PromptExpandResult` — DELETED per user directive.
// Was a Rust-only bundle for C's three outparams. C signature
// `char *promptexpand(char *s, int ns, const char *marker, char
// *rs, char *Rs)` (`Src/prompt.c:182`) writes through `rs`/`Rs`
// pointers and returns the expanded `char *`. Rust port now
// returns a `(String, Option<usize>, Option<usize>)` tuple
// matching C's outparam shape directly.

/// Port of `promptexpand(char *s, int ns, const char *marker, char *rs, char *Rs)` from `Src/prompt.c:182`.
///
/// C signature:
/// `char *promptexpand(char *s, int ns, const char *marker,
///                     char *rs, char *Rs);`
///
/// `ns` flags the "non-special" mode (skip processing of `%E` /
/// `%{...%}`); `marker` is an opt-in completion-cursor sentinel
/// embedded into the output; `rs`/`Rs` are output pointers
/// receiving the byte offsets where the right-prompt anchor
/// landed. Rust returns the four values as a tuple
/// `(expanded, rs_offset, cap_rs_offset)`.
/// WARNING: param names don't match C — Rust=(_ns, _marker) vs C=(s, ns, marker, rs, Rs)
pub fn promptexpand(                                                         // c:182
    s: &str,
    _ns: i32,
    _marker: Option<&str>,
) -> (String, Option<usize>, Option<usize>) {
    let expanded = expand_prompt(s);
    // C: `*rs = bv.bp - bv.buf` at `%E` / `%>` markers. Rust
    // expander loses that metadata, so a second pass on `s` is the
    // closest approximation. Source-offset → expanded-offset is
    // 1:1 except where expansion lengthens.
    let rs_offset = s.find("%E").or_else(|| s.find("%E)")); // c:Src/prompt.c:257
    let cap_rs_offset = s.find("%>>"); // c:Src/prompt.c:257
    (expanded, rs_offset, cap_rs_offset)
}

/// Escape text attributes back to a `%`-prefixed prompt string.
/// Port of `zattrescape(zattr atr, int *len)` from Src/prompt.c:257 — inverse of
/// `parsehighlight()`; used by the `print -P` output path.
/// WARNING: param names don't match C — Rust=(attrs) vs C=(atr, len)
pub fn zattrescape(attrs: zattr) -> String {                             // c:257
    let mut result = String::new();
    if attrs & TXTBOLDFACE != 0 { result.push_str("%B"); } // c:259
    if attrs & TXTUNDERLINE != 0 { result.push_str("%U"); } // c:259
    if attrs & TXTSTANDOUT != 0 { result.push_str("%S"); } // c:259
    if attrs & TXTFGCOLOUR != 0 { // c:266
        let raw = (attrs & TXT_ATTR_FG_COL_MASK) >> TXT_ATTR_FG_COL_SHIFT;
        let c = if attrs & TXT_ATTR_FG_24BIT != 0 {
            COLOR_24BIT | (raw as Color & 0x00ff_ffff)
        } else { raw as Color };
        result.push_str(&format!("%F{{{}}}", color_name(c)));
    }
    if attrs & TXTBGCOLOUR != 0 { // c:266
        let raw = (attrs & TXT_ATTR_BG_COL_MASK) >> TXT_ATTR_BG_COL_SHIFT;
        let c = if attrs & TXT_ATTR_BG_24BIT != 0 {
            COLOR_24BIT | (raw as Color & 0x00ff_ffff)
        } else { raw as Color };
        result.push_str(&format!("%K{{{}}}", color_name(c)));
    }
    result
}

/// Parse a `,`-separated highlight specification.
/// Port of `parsehighlight(char *arg, char endchar, zattr *atr, zattr *mask)` from Src/prompt.c:285 — handles
// Parse the argument for %H                                                // c:285
/// `bold` / `underline` / `standout` / `none` plus `fg=NAME` and
/// `bg=NAME` color targets.
/// WARNING: param names don't match C — Rust=(spec) vs C=(arg, endchar, atr, mask)
pub fn parsehighlight(spec: &str) -> zattr {                             // c:285
    let mut attrs: zattr = 0;
    for part in spec.split(',') {
        let part = part.trim();
        match part {
            "bold" => attrs |= TXTBOLDFACE, // c:288
            "underline" => attrs |= TXTUNDERLINE, // c:288
            "standout" => attrs |= TXTSTANDOUT, // c:288
            "none" => {
                attrs = 0; // c:288
            }
            s if s.starts_with("fg=") => {
                if let Some(code) = match_named_colour(&s[3..]) { // c:295
                    attrs = zattr_set_fg_palette(attrs, code); // c:295
                }
            }
            s if s.starts_with("bg=") => {
                if let Some(code) = match_named_colour(&s[3..]) { // c:295
                    attrs = zattr_set_bg_palette(attrs, code); // c:295
                }
            }
            _ => {}
        }
    }
    attrs
}

/// Parse a single colour character from a `%F{...}` argument.
/// Port of `parsecolorchar(zattr arg, int is_fg)` from Src/prompt.c:318.
pub fn parsecolorchar(arg: &str, is_fg: bool) -> Option<(Color, String)> {   // c:318
    let color = color_from_name(arg)?; // c:318 (match_colour)
    let ansi = color_to_ansi(color, is_fg); // c:2440
    Some((color, ansi))
}

// ---------------------------------------------------------------------------
// Remaining prompt.c entry points (after `putpromptchar` / `buf_vars`)
// ---------------------------------------------------------------------------

/// Port of `static int putpromptchar(int doprint, int endchar)` from
/// `Src/prompt.c:359`. Delegates to `buf_vars::run_putpromptchar` +
/// `buf_vars::process_percent` — the 566-line C body's per-`%X`
/// escape table lives there split across the inherent-method
/// dispatch (~100 lines each, real ports). The free-fn entry exists
/// for C-ABI parity so cross-module call sites match the C symbol.
pub fn putpromptchar(bv: &mut buf_vars, doprint: i32, endchar: i32) -> i32 { // c:359
    // Delegates to the buf_vars method that holds the real loop.
    bv.run_putpromptchar(doprint, endchar)
}

/// Internal prompt char output.
/// Port of `pputc(char c)` from Src/prompt.c:976 — the C source's
/// per-character buffer-append helper. Rust's `String::push`
/// covers it directly; this wrapper exists for call-site parity.
/// WARNING: param names don't match C — Rust=(buf, c) vs C=(c)
pub fn pputc(buf: &mut String, c: char) {                                    // c:976
    buf.push(c);
}

// Make sure there is room for `need' more characters in the buffer.       // c:991
/// Ensure the prompt buffer has at least `need` bytes free.
/// Port of `addbufspc(int need)` from Src/prompt.c:991 — the C source
/// reallocates the heap buffer; Rust's `String` does this
/// automatically so this is a no-op.
/// WARNING: param names don't match C — Rust=(_buf, _need) vs C=(need)
pub fn addbufspc(_buf: &mut String, _need: usize) {                         // c:991
    // Rust String handles allocation automatically
}

/// Append a string to the prompt buffer.
/// Port of `stradd(char *d)` from Src/prompt.c:1016.
/// WARNING: param names don't match C — Rust=(buf, s) vs C=(d)
pub fn stradd(buf: &mut String, s: &str) {                                   // c:1016
    buf.push_str(s);
}

/// Port of `void tsetcap(int cap, int flags)` from `Src/prompt.c:1083`.
/// Emit a terminal capability escape — raw to tty (TSC_RAW), to
/// shout (default), or into the prompt buffer with Inpar/Outpar
/// markers for visible-width counting (TSC_PROMPT).
/// ```c
/// void
/// tsetcap(int cap, int flags)
/// {
///     if (tccan(cap) && !(termflags & (TERM_NOUP|TERM_BAD|TERM_UNKNOWN))) {
///         switch (flags) {
///         case TSC_RAW:   tputs(tcstr[cap], 1, putraw); break;
///         case 0:
///         default:        tputs(tcstr[cap], 1, putshout); break;
///         case TSC_PROMPT:
///             if (!bv->dontcount) { addbufspc(1); *bv->bp++ = Inpar; }
///             tputs(tcstr[cap], 1, putstr);
///             if (!bv->dontcount) {
///                 int glitch = 0;
///                 if (cap == TCSTANDOUTBEG || cap == TCSTANDOUTEND)
///                     glitch = tgetnum("sg");
///                 else if (cap == TCUNDERLINEBEG || cap == TCUNDERLINEEND)
///                     glitch = tgetnum("ug");
///                 if (glitch < 0) glitch = 0;
///                 addbufspc(glitch + 1);
///                 while (glitch--) *bv->bp++ = Nularg;
///                 *bv->bp++ = Outpar;
///             }
///             break;
///         }
///     }
/// }
/// ```
/// WARNING: param names don't match C — Rust=(cap, flags) vs C=(cap, flags)
pub fn tsetcap(cap: i32, flags: i32) -> String {                             // c:1083
    use std::sync::atomic::Ordering;
    use crate::ported::zsh_h::{TERM_BAD, TERM_NOUP, TERM_UNKNOWN, TSC_RAW, TSC_PROMPT};

    let mut out = String::new();

    // c:1085 — `if (tccan(cap) && !(termflags & ...))`
    let tclen_guard = crate::ported::init::tclen.lock().unwrap();
    let cap_ok = cap >= 0 && (cap as usize) < tclen_guard.len()
        && tclen_guard[cap as usize] != 0;
    drop(tclen_guard);
    let termflags = crate::ported::params::TERMFLAGS.load(Ordering::SeqCst);
    if !(cap_ok && (termflags & (TERM_NOUP | TERM_BAD | TERM_UNKNOWN)) == 0) {
        return out;
    }

    let cap_str = crate::ported::init::tcstr.lock().unwrap()
        .get(cap as usize).cloned().unwrap_or_default();

    match flags {                                                            // c:1086
        x if x == TSC_RAW => {                                               // c:1087
            // c:1088 — `tputs(tcstr[cap], 1, putraw);` — raw write to tty fd.
            let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
            let out_fd = if fd >= 0 { fd } else { 2 };
            let _ = crate::ported::utils::write_loop(out_fd, cap_str.as_bytes());
        }
        x if x == TSC_PROMPT => {                                            // c:1094
            // c:1095-1113 — TSC_PROMPT: emit into the prompt buffer
            // wrapped in Inpar/Outpar markers so the screen-width
            // counter (countprompt) knows to skip the escape.
            //
            // The previous Rust port used '\x01' / '\x02' as the
            // markers, but the canonical token bytes are
            // Inpar=0x88 (zsh.h:163) and Outpar=0x8a (zsh.h:165).
            // countprompt was looking for the canonical values, so
            // tsetcap-emitted escapes were ALSO counted as visible
            // width — a tcap-based prompt would wrap a column early.
            // Pair the wrapping with countprompt's recognition; both
            // sides now use the canonical bytes.
            out.push(crate::ported::zsh_h::Inpar);                           // c:1097 Inpar marker
            out.push_str(&cap_str);                                          // c:1099
            // c:1101-1106 — glitch detection (sg / ug termcap nums).
            // tgetnum() not yet ported as a free fn; assume 0 (no glitch)
            // which matches modern terminals.
            out.push(crate::ported::zsh_h::Outpar);                          // c:1112 Outpar marker
        }
        _ => {                                                               // c:1090 default
            // c:1092 — `tputs(tcstr[cap], 1, putshout);`
            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, cap_str.as_bytes());
        }
    }
    out
}

/// Port of `int putstr(int d)` from `Src/prompt.c:1121`. tputs
/// per-byte output callback: emit `d` into the prompt-buffer via
/// `pputc`. Used by `tsetcap(cap, TSC_PROMPT)` to capture termcap
/// emissions into bv->buf.
/// ```c
/// int putstr(int d) { pputc(d); return 0; }
/// ```
/// WARNING: param names don't match C — Rust=(d) vs C=(d)
pub fn putstr(d: &str) -> String {                                           // c:1121
    // c:1123 — `pputc(d); return 0;` Output goes into the prompt buf.
    // Caller-supplied string is returned for the buf_vars dispatch to
    // append; this mirrors the C pputc-then-return-0 semantic since
    // Rust has no shared bv->bp cursor at this layer.
    d.to_string()
}

/// Handle `%>...>` / `%<...<` / `%[truncchar string]` truncation.
/// Port of `prompttrunc(int arg, int truncchar, int doprint, int endchar)` from Src/prompt.c:1276.
///
/// Port of `static int prompttrunc(int arg, int truncchar, int doprint,
/// int endchar)` from `Src/prompt.c:1276`. Implements the `%<...<`,
/// `%>...>`, `%[...]` truncation syntax: stashes the truncation
/// string, recurses `putpromptchar` to expand the bounded region,
/// then either left- or right-truncates to fit `arg` screen cells.
///
/// Operates on the `buf_vars` scratch struct (file-statics in C:
/// `bv->fm` / `bv->bp` / `bv->buf` / `bv->truncwidth` /
/// `bv->dontcount` / `bv->trunccount`) — see c:76-121 for the
/// struct layout. Rust port takes `&mut buf_vars` to match.
/// WARNING: param names match C — Rust=(bv, arg, truncchar, doprint, endchar) vs C=(arg, truncchar, doprint, endchar)
pub fn prompttrunc(bv: &mut buf_vars, arg: i32, truncchar: i32,              // c:1276
                   doprint: i32, endchar: i32) -> i32 {
    if arg > 0 {                                                             // c:1278
        // c:1279 — `char ch = *bv->fm;` (peek)
        let ch = bv.fm.as_bytes().get(bv.fm_pos).copied().unwrap_or(0);
        let truncatleft = ch == b'<';                                        // c:1280
        let w = bv.bp;                                                       // c:1281 bp - buf

        // c:1288-1293 — re-entry guard: if a truncation is already
        // active, back up to the % marker and return so the outer
        // call can finish first.
        if bv.truncwidth != 0 {                                              // c:1288
            while bv.fm_pos > 0 {
                bv.fm_pos -= 1;                                              // c:1289
                if bv.fm.as_bytes().get(bv.fm_pos).copied().unwrap_or(0) == b'%' {
                    break;
                }
            }
            if bv.fm_pos > 0 { bv.fm_pos -= 1; }                             // c:1291
            return 0;                                                        // c:1292
        }

        bv.truncwidth = arg;                                                 // c:1295
        if bv.fm.as_bytes().get(bv.fm_pos).copied().unwrap_or(0) != b']' {   // c:1296
            bv.fm_pos += 1;                                                  // c:1297
        }

        // c:1298-1303 — copy truncation string into buf until truncchar.
        let tchar = truncchar as u8;
        while let Some(&c) = bv.fm.as_bytes().get(bv.fm_pos) {               // c:1298
            if c == 0 || c == tchar { break; }
            let mut cur = c;
            if cur == b'\\' && bv.fm.as_bytes().get(bv.fm_pos + 1).is_some() {  // c:1299
                bv.fm_pos += 1;
                cur = bv.fm.as_bytes()[bv.fm_pos];
            }
            // c:1301 — addbufspc(1)
            if bv.bp >= bv.buf.len() {
                bv.buf.resize(bv.bp + 1, 0);
            }
            bv.buf[bv.bp] = cur;                                             // c:1302 *bv->bp++ = *bv->fm++
            bv.bp += 1;
            bv.fm_pos += 1;
        }
        if bv.fm.as_bytes().get(bv.fm_pos).copied().unwrap_or(0) == 0 {      // c:1304
            return 0;                                                        // c:1305
        }
        if bv.bp == w && truncchar == b']' as i32 {                          // c:1306
            if bv.bp >= bv.buf.len() {
                bv.buf.resize(bv.bp + 1, 0);
            }
            bv.buf[bv.bp] = b'<';                                            // c:1308
            bv.bp += 1;
        }
        // c:1310 — `ptr = bv->buf + w;` (truncation-string start)
        let ptr = w;
        // c:1317 — `truncstr = ztrduppfx(ptr, bv->bp - ptr);`
        let trunc_bytes = bv.buf[ptr..bv.bp].to_vec();
        let truncstr = String::from_utf8_lossy(&trunc_bytes).into_owned();

        bv.bp = ptr;                                                         // c:1319
        let w_save = bv.bp;                                                  // c:1320
        bv.fm_pos += 1;                                                      // c:1321
        bv.trunccount = bv.dontcount;                                        // c:1322
        // c:1323 — `putpromptchar(doprint, endchar);` — recurse to
        // expand the bounded region; output goes into bv.buf at bp.
        putpromptchar(bv, doprint, endchar);                                 // c:1323
        bv.trunccount = 0;                                                   // c:1324
        let ptr = w_save;                                                    // c:1325
        // c:1326 — `*bv->bp = '\0';` — null-terminate.
        if bv.bp < bv.buf.len() {
            bv.buf[bv.bp] = 0;
        }

        // c:1343-1344 — `countprompt(ptr, &w, 0, -1)`: compute screen width.
        let region_bytes = &bv.buf[ptr..bv.bp];
        let region_str = std::str::from_utf8(region_bytes).unwrap_or("");
        let mut visible_w: i32 = 0;
        // Count chars (rough screen width — C's countprompt skips
        // escape sequences and counts MB_METASTRWIDTH; collapsed to
        // char count here since the bv buffer stores expanded text).
        for _ in region_str.chars() { visible_w += 1; }

        if visible_w > bv.truncwidth {                                       // c:1344
            // c:1354-1410 — truncate. truncstr is the marker; replace
            // either the head (truncatleft=true: e.g. `%<...<`) or
            // tail (truncatleft=false: `%>...>`) with the marker.
            let maxwidth = bv.truncwidth - truncstr.chars().count() as i32;
            if maxwidth < 0 {
                // truncation marker is longer than the budget — use marker only
                bv.bp = ptr;
                let mb = truncstr.as_bytes();
                for &b in mb {
                    if bv.bp >= bv.buf.len() { bv.buf.resize(bv.bp + 1, 0); }
                    bv.buf[bv.bp] = b;
                    bv.bp += 1;
                }
            } else {
                let region_chars: Vec<char> = region_str.chars().collect();
                let len = region_chars.len() as i32;
                let keep = maxwidth.max(0) as usize;
                let kept: String = if truncatleft {                          // c:1354 ch == '<'
                    // keep tail: drop (len-keep) chars from front, prefix marker
                    let drop_n = (len - keep as i32).max(0) as usize;
                    let suffix: String = region_chars[drop_n..].iter().collect();
                    format!("{}{}", truncstr, suffix)
                } else {
                    // keep head: take first `keep` chars, append marker
                    let prefix: String = region_chars[..keep.min(region_chars.len())].iter().collect();
                    format!("{}{}", prefix, truncstr)
                };
                // Rewrite buf[ptr..] with `kept`.
                bv.bp = ptr;
                for &b in kept.as_bytes() {
                    if bv.bp >= bv.buf.len() { bv.buf.resize(bv.bp + 1, 0); }
                    bv.buf[bv.bp] = b;
                    bv.bp += 1;
                }
            }
        }
        if bv.bp < bv.buf.len() {
            bv.buf[bv.bp] = 0;                                               // c:1421 terminate
        }

        bv.truncwidth = 0;                                                   // c:1431
    }
    0                                                                        // c:1471
}

/// Push a parser context token. Port of `cmdpush()` from
/// Src/prompt.c. Bounded at CMDSTACKSZ; over-push is silently
/// ignored (matches the C source's `cmdsp < CMDSTACKSZ` guard).
/// C body (2 lines):
///   `if (cmdsp >= 0 && cmdsp < CMDSTACKSZ) cmdstack[cmdsp++] = cmdtok;`
pub fn cmdpush(cmdtok: u8) {                                                 // c:1624
    CMDSTACK.with(|s| { let mut st = s.borrow_mut(); if st.len() < CMDSTACKSZ { st.push(cmdtok); } });
}

/// Pop the top parser context token. Port of `cmdpop()` from
/// Src/prompt.c. Empty-stack pop is a no-op (the C source emits
/// a `BUG: cmdstack empty` debug print and continues).
pub fn cmdpop() {
    CMDSTACK.with(|s| {
        s.borrow_mut().pop();
    });
}

/// Port of `applytextattributes(int flags)` from `Src/prompt.c:1645`.
///
/// C body diff-syncs `txtcurrentattrs` against `txtpendingattrs`
/// and emits the minimal termcap-driven sequence to transition
/// the terminal — `tsetcap(TCALLATTRSOFF…)`, `TCBOLDFACEBEG`, etc.
///
/// Rust port: returns the SGR diff string built by [`treplaceattrs`]
/// over the (current, pending) pair, and updates current = pending.
/// The previous port was an empty `void` shim that emitted nothing
/// — output gets emitted at flush time, which broke any caller
/// expecting incremental attr changes. New shape returns the diff
/// the caller can write to the terminal.
///
/// `_flags` parameter (currently unused in zshrs port — C uses it
/// to gate "force reset" mode).
#[allow(unused_variables)]
pub fn applytextattributes(flags: i32) -> String {
    let mut current = current_attrs_lock().lock().expect("current_attrs poisoned");
    let pending = pending_attrs_lock()
        .lock()
        .expect("pending_attrs poisoned")
        .clone();

    // SGR diff emission — inlined from the prior Rust-only helper that
    // miscarried the `treplaceattrs` name. C emits the same diff via
    // sequential tsetcap calls (Src/prompt.c:1640-1718). Rust returns
    // the assembled escape string for the caller to write.
    let mut result = String::new();
    let old = *current;
    let new = pending;

    let old_b = old & TXTBOLDFACE != 0;
    let new_b = new & TXTBOLDFACE != 0;
    let old_u = old & TXTUNDERLINE != 0;
    let new_u = new & TXTUNDERLINE != 0;
    let old_s = old & TXTSTANDOUT != 0;
    let new_s = new & TXTSTANDOUT != 0;

    let need_reset = (old_b && !new_b) || (old_u && !new_u) || (old_s && !new_s);

    if need_reset {
        result.push_str("\x1b[0m");
        if new_b { result.push_str("\x1b[1m"); }
        if new_u { result.push_str("\x1b[4m"); }
        if new_s { result.push_str("\x1b[7m"); }
    } else {
        if !old_b && new_b { result.push_str("\x1b[1m"); }
        if !old_u && new_u { result.push_str("\x1b[4m"); }
        if !old_s && new_s { result.push_str("\x1b[7m"); }
    }

    if (old & TXT_ATTR_FG_MASK) != (new & TXT_ATTR_FG_MASK) {
        if new & TXTFGCOLOUR != 0 {
            let raw = (new & TXT_ATTR_FG_COL_MASK) >> TXT_ATTR_FG_COL_SHIFT;
            let c = if new & TXT_ATTR_FG_24BIT != 0 {
                COLOR_24BIT | (raw as Color & 0x00ff_ffff)
            } else { raw as Color };
            result.push_str(&color_to_ansi(c, true));
        } else {
            result.push_str("\x1b[39m");
        }
    }
    if (old & TXT_ATTR_BG_MASK) != (new & TXT_ATTR_BG_MASK) {
        if new & TXTBGCOLOUR != 0 {
            let raw = (new & TXT_ATTR_BG_COL_MASK) >> TXT_ATTR_BG_COL_SHIFT;
            let c = if new & TXT_ATTR_BG_24BIT != 0 {
                COLOR_24BIT | (raw as Color & 0x00ff_ffff)
            } else { raw as Color };
            result.push_str(&color_to_ansi(c, false));
        } else {
            result.push_str("\x1b[49m");
        }
    }

    let diff = result;
    *current = pending;
    diff
}

/// Port of `void treplaceattrs(zattr newattrs)` from `Src/prompt.c:1719`.
/// ```c
/// void
/// treplaceattrs(zattr newattrs)
/// {
///     if (newattrs == TXT_ERROR) return;
///     if (txtunknownattrs) {
///         txtcurrentattrs &= ~txtunknownattrs;
///         txtcurrentattrs |= txtunknownattrs & ~newattrs;
///     }
///     txtpendingattrs = newattrs;
/// }
/// ```
/// State-mutator only — the actual escape emission happens in
/// `applytextattributes`. C's behavior: clear any "unknown" bits
/// from current and re-set their inverse so applytextattributes
/// detects them as changed, then stash newattrs in pending.
pub fn treplaceattrs(newattrs: zattr) {                                       // c:1719
    if newattrs == crate::ported::zsh_h::TXT_ERROR {                          // c:1721
        return;                                                               // c:1722
    }
    let unknown = txtunknownattrs.load(std::sync::atomic::Ordering::SeqCst);  // c:1724
    if unknown != 0 {                                                         // c:1724
        let mut cur = current_attrs_lock().lock().expect("current_attrs poisoned");
        *cur &= !unknown;                                                     // c:1728
        *cur |= unknown & !newattrs;                                          // c:1729
    }
    *pending_attrs_lock().lock().expect("pending_attrs poisoned") = newattrs; // c:1732
}

/// Port of `mod_export zattr txtunknownattrs` from `Src/prompt.c:46`.
/// Mask of text-attribute bits whose state is unknown because they
/// came from escape sequences the prompt parser didn't recognise.
pub static txtunknownattrs: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);                                     // c:46

/// Set text attributes (full apply).
/// Port of `tsetattrs(zattr newattrs)` from Src/prompt.c:1737.
pub fn tsetattrs(newattrs: zattr) -> String {                               // c:1737
    apply_text_attributes(newattrs)
}

/// Unset (clear) text attributes via SGR-22/24/27 + 39/49.
/// Port of `tunsetattrs(zattr newattrs)` from Src/prompt.c:1755.
pub fn tunsetattrs(newattrs: zattr) -> String {                             // c:1755
    let mut result = String::new();
    if newattrs & TXTBOLDFACE != 0 { result.push_str("\x1b[22m"); }
    if newattrs & TXTUNDERLINE != 0 {
        result.push_str("\x1b[24m");
    }
    if newattrs & TXTSTANDOUT != 0 { result.push_str("\x1b[27m"); }
    if newattrs & TXTFGCOLOUR != 0 { result.push_str("\x1b[39m"); }
    if newattrs & TXTBGCOLOUR != 0 { result.push_str("\x1b[49m"); }
    result
}

/// Promote the 256-color value embedded in `atr` to an explicit
/// 24-bit RGB value. Port of `map256toRGB(zattr *atr, int shift, zattr set24)` from Src/prompt.c.
/// Used by the prompt-output path when the terminal supports
/// truecolor and we want to emit RGB rather than the smaller
/// 256-palette code.
///
/// `shift` selects fg-byte vs bg-byte position inside `atr`;
/// `set24` is the bit that marks "this slot is now 24-bit".
/// Algorithm mirrors the C: 16-231 are the 6×6×6 color cube,
/// 232-255 are the 24-step grayscale ramp.
#[allow(non_snake_case)]
pub fn map256toRGB(atr: &mut u64, shift: u32, set24: u64) {
    if (*atr & set24) != 0 {
        return;
    }
    let colour: u32 = ((*atr >> shift) & 0xff) as u32;
    if colour < 16 {
        return;
    }
    let (red, green, blue) = if (16..232).contains(&colour) {
        let mut c = colour - 16;
        let blue = (if c != 0 { 0x37 } else { 0 }) + 40 * (c % 6);
        c /= 6;
        let green = (if c != 0 { 0x37 } else { 0 }) + 40 * (c % 6);
        c /= 6;
        let red = (if c != 0 { 0x37 } else { 0 }) + 40 * c;
        (red, green, blue)
    } else {
        let v = 8 + 10 * (colour - 232);
        (v, v, v)
    };
    *atr &= !((0xffffff_u64) << shift);
    *atr |= set24 | ((((red as u64) << 8 | green as u64) << 8 | blue as u64) << shift);
}

/// Mix two sets of text attributes through a mask.
/// Port of `mixattrs(zattr primary, zattr mask, zattr secondary)` from Src/prompt.c:1802 — primary wins
/// where the mask says "set"; secondary fills the rest.
pub fn mixattrs(primary: zattr, mask: zattr, secondary: zattr) -> zattr {
    // Bit-level mix: for each TXT* bit set in `mask`, take the
    // value from `primary`; else from `secondary`. Mirrors the C
    // idiom `(mask & primary) | (!mask & secondary)`.
    let mut out: zattr = 0;
    for bit in [TXTBOLDFACE, TXTUNDERLINE, TXTSTANDOUT] {
        if mask & bit != 0 { out |= primary & bit; } else { out |= secondary & bit; }
    }
    if mask & TXTFGCOLOUR != 0 { out |= primary & TXT_ATTR_FG_MASK; }
    else { out |= secondary & TXT_ATTR_FG_MASK; }
    if mask & TXTBGCOLOUR != 0 { out |= primary & TXT_ATTR_BG_MASK; }
    else { out |= secondary & TXT_ATTR_BG_MASK; }
    out
}

// ---------------------------------------------------------------------------
// Missing functions from prompt.c
// ---------------------------------------------------------------------------

/// Truncate the prompt to a maximum width.
/// Port of `prompttrunc(int arg, int truncchar, int doprint, int endchar)` from Src/prompt.c:1276 — the C source
/// implements the `%N>string>` (right-truncate) and `%N<string<`
/// (left-truncate) sequences with a configurable indicator.
/// Port of `countprompt(char *str, int *wp, int *hp, int overf)` from `Src/prompt.c:1140`.
///
/// C signature:
/// `void countprompt(char *str, int *wp, int *hp, int overf);`
///
/// Walks the expanded prompt counting visible columns, wrapping
/// to the next line every `terminal_width` characters and bumping
/// the height counter. Returns `(width, height)` — `width` is the
/// column on the FINAL line; `height` is total line count
/// including the first.
///
/// Faithful to C's prompt.c:1140 logic:
/// - `\t` advances to the next 8-column boundary (`w = (w | 7) + 1`).
/// - `\n` resets `w` to 0 and bumps `h`.
/// - `\x01`/`\x02` (RL_PROMPT_*_IGNORE) toggle visibility skip.
/// - `\x1b[...m` ANSI escapes consumed without counting.
/// - Wrap rule: `while w > terminal_width && overf >= 0` →
///   `h++; w -= terminal_width` (matches the C overflow loop at
///   line 1158 + 1255).
/// - Final-column-equals-width edge case: when `w == terminal_width
///   && overf == 0`, snap to (0, h+1) — mirrors C lines 1265-1268.
///
// by locating them and finding out their screen width.                    // c:1135
/// Previous Rust port took only `&str` and returned `(width,
/// newlines)` — missing the `terminal_width` overflow tracking
/// and the `overf` flag entirely.

// `pub struct CmdStack` + `impl CmdStack { new, push, pop, top,
// depth, as_slice }` — DELETED per user directive. C source uses
// `unsigned char *cmdstack` + `int cmdsp` flat globals
// (`Src/prompt.c:1915`) plus `cmdpush()`/`cmdpop()` functions
// (`Src/prompt.c:1915`). The Rust-only `CmdStack` wrapper had
// zero callers outside this file. The canonical port lives on
// `prompt_tls::CMDSTACK` and `ShellExecutor.cmd_stack: Vec<u8>`.
// `cmdpush()`/`cmdpop()` thread-local stack mirrors C file-statics.

/// Resolve a color name to an ANSI base index.
/// Port of `match_named_colour(const char **teststrp)` from Src/prompt.c:1915 —
/// walks `colour_names[]` (now `COLOUR_NAMES` at file head), then
/// falls through to numeric parsing. Returns palette index 0-7
/// for basic colours, 8 for "default" sentinel (per C:1909),
/// numeric value for raw integers.
/// Port of `void countprompt(char *str, int *wp, int *hp, int overf)`
/// from `Src/prompt.c:1140`. Walks the expanded prompt counting visible
/// columns: handles `\t` (tab to next 8-col boundary), `\n` (reset
/// column, bump row), `Inpar`/`Outpar` (`%{...%}` invisible regions),
/// and `Nularg` (1-width opaque placeholder for `tputs` glitches).
/// Writes width/height into `wp`/`hp` out-params. `overf` flag: when
/// non-negative, wrap on column overflow (incrementing `*hp`); when -1,
/// allow overflow (used by truncation pre-pass).
/// ```c
/// void
/// countprompt(char *str, int *wp, int *hp, int overf)
/// {
///     int w = 0, h = 1, multi = 0, wcw = 0;
///     int s = 1;  /* visible flag */
///     for (; *str; str++) {
///         while (w > zterm_columns && overf >= 0 && !multi) {
///             h++;
///             if (wcw) { w = wcw; break; }
///             else w -= zterm_columns;
///         }
///         wcw = 0;
///         if (*str == Inpar) s = 0;
///         else if (*str == Outpar) s = 1;
///         else if (*str == Nularg) w++;
///         else if (s) {
///             /* meta-decode, tab/newline/wide-char/cntrl handling */
///         }
///     }
///     *wp = w; *hp = h;
/// }
/// ```
/// WARNING: param names match C — Rust=(str, wp, hp, overf) vs C=(str, wp, hp, overf)
pub fn countprompt(s: &str, wp: &mut i32, hp: &mut i32, overf: i32) {        // c:1140
    let zterm_columns = crate::ported::utils::adjustcolumns() as i32;
    let mut w: i32 = 0;                                                      // c:1142
    let mut h: i32 = 1;
    let multi = 0i32;                                                        // c:1142
    let mut wcw: i32 = 0;
    let mut visible = true;                                                  // c:1143 s = 1

    for c in s.chars() {
        // c:1158-1173 — overflow wrap loop.
        while w > zterm_columns && overf >= 0 && multi == 0 {                // c:1158
            h += 1;                                                          // c:1159
            if wcw != 0 {                                                    // c:1160
                w = wcw;                                                     // c:1165
                break;                                                       // c:1166
            } else {
                w -= zterm_columns;                                          // c:1171
            }
        }
        wcw = 0;                                                             // c:1174

        // c:1179-1185 — Inpar/Outpar/Nularg dispatch.
        //
        // The previous Rust port used '\x01' / '\x02' / '\x03' for
        // these three tokens, which are the WRONG values. The
        // canonical token bytes are:
        //   Inpar  = 0x88 (Src/zsh.h:163)
        //   Outpar = 0x8a (Src/zsh.h:165)
        //   Nularg = 0xa1 (Src/zsh.h:206)
        //
        // Effect of the previous bug: every prompt with `%{...%}`
        // (non-printing escapes — which lex as Inpar..Outpar after
        // promptexpand) skipped the `s = 0` flag flip and counted
        // the escape bytes as visible width. Multi-line prompts
        // with `%{...%}` wrap at wrong columns.
        if c == crate::ported::zsh_h::Inpar {                                // c:1179 Inpar
            visible = false;                                                 // c:1180 s = 0
        } else if c == crate::ported::zsh_h::Outpar {                        // c:1181 Outpar
            visible = true;                                                  // c:1182 s = 1
        } else if c == crate::ported::zsh_h::Nularg {                        // c:1183 Nularg
            w += 1;                                                          // c:1184
        } else if visible {                                                  // c:1185
            // c:1202-1208 — tab / newline.
            if c == '\t' {                                                   // c:1202
                w = (w | 7) + 1;                                             // c:1203
                continue;
            } else if c == '\n' {                                            // c:1205
                w = 0;                                                       // c:1206
                h += 1;                                                      // c:1207
                continue;                                                    // c:1208
            }
            // c:1234 — `w += WCWIDTH_WINT(wc)` — width of the char.
            let cw = unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as i32;
            wcw = cw;                                                        // c:1233 wcw = wcw
            w += cw;                                                         // c:1234
        }
    }
    // c:1265-1268 — final-column edge case: w == zterm_columns && overf == 0.
    if w == zterm_columns && overf == 0 {                                    // c:1265
        w = 0;                                                               // c:1266
        h += 1;                                                              // c:1267
    }
    *wp = w;                                                                 // c:1273 *wp = w
    *hp = h;                                                                 // c:1274 *hp = h
}

pub fn match_named_colour(teststrp: &str) -> Option<u8> {                        // c:1915
    // c:1925-1928 uses `strncmp` (case-SENSITIVE) against the
    // ansi_colours table. The previous Rust port `to_lowercase`-ed
    // the input first which made the function case-INsensitive,
    // accepting `"RED"` where C rejects it. Fixed 2026-05 to match
    // the C strncmp contract: input must already be lowercase.
    for (i, &n) in COLOUR_NAMES.iter().enumerate() {                             // c:1925
        if n == teststrp {                                                       // c:1926 strncmp(teststr, *cptr, len)
            return Some(i as u8);                                                // c:1927
        }
    }
    // Rust-port extension: fall through to numeric parse so callers
    // can spell `color 38` etc. (C returns -1 here; the numeric path
    // is wired further up the dispatch chain in upstream zsh, but
    // the Rust port colocates it because there's no shared call site
    // yet). Pin via the regression test if this lands a divergent
    // behavior in practice.
    teststrp.parse::<u8>().ok()
}

/// Port of `static int truecolor_terminal(void)` from Src/prompt.c:1935.
///
/// C body (c:1935-1944):
/// ```c
/// char **f, **flist = getaparam(".term.extensions");
/// int result;
/// for (f = flist; f && *f; f++) {
///     result = **f != '-';
///     if (!strcmp(*f + !result, "truecolor"))
///         return result;
/// }
/// return 0; /* disabled by default */
/// ```
///
/// Walks `$.term.extensions` (a shell array of capability names; entries
/// prefixed with `-` mean "disabled"). Returns true when `truecolor` is
/// present and not negated. The previous Rust port did a heuristic
/// COLORTERM/TERM-string match — not how C decides. Off-by-default
/// matches C's final `return 0`.
pub fn truecolor_terminal() -> bool {                                       // c:1935
    if let Some(flist) = crate::ported::params::getaparam(".term.extensions") {
        for f in &flist {                                                   // c:1939
            if f.is_empty() { continue; }
            // c:1940 — `result = **f != '-'`; the `-` prefix disables.
            let (result, name) = match f.strip_prefix('-') {
                Some(rest) => (false, rest),
                None       => (true,  f.as_str()),
            };
            if name == "truecolor" {                                        // c:1941
                return result;                                              // c:1942
            }
        }
    }
    false                                                                    // c:1944
}

impl buf_vars {
    pub fn new(input: &str) -> Self {
        Self {
            pwd: prompt_tls::PWD.with(|c| c.borrow().clone()),
            home: prompt_tls::HOME.with(|c| c.borrow().clone()),
            user: prompt_tls::USER.with(|c| c.borrow().clone()),
            host: prompt_tls::HOST.with(|c| c.borrow().clone()),
            host_short: prompt_tls::HOST_SHORT.with(|c| c.borrow().clone()),
            tty: prompt_tls::TTY.with(|c| c.borrow().clone()),
            lastval: prompt_tls::LASTVAL.with(|c| *c.borrow()),
            histnum: prompt_tls::HISTNUM.with(|c| *c.borrow()),
            shlvl: prompt_tls::SHLVL.with(|c| *c.borrow()),
            num_jobs: prompt_tls::NUM_JOBS.with(|c| *c.borrow()),
            is_root: prompt_tls::IS_ROOT.with(|c| *c.borrow()),
            cmd_stack: prompt_tls::CMDSTACK.with(|c| c.borrow().clone()),
            psvar: prompt_tls::PSVAR.with(|c| c.borrow().clone()),
            term_width: prompt_tls::TERM_WIDTH.with(|c| *c.borrow()),
            lineno: prompt_tls::LINENO.with(|c| *c.borrow()),
            scriptname: prompt_tls::SCRIPTNAME.with(|c| c.borrow().clone()),
            scriptfilename: prompt_tls::SCRIPTFILENAME.with(|c| c.borrow().clone()),
            argzero: prompt_tls::ARGEXTRA.with(|c| c.borrow().clone()),
            func_line_base: prompt_tls::FUNC_LINE_BASE.with(|c| *c.borrow()),
            funcstack_filename: prompt_tls::FUNCSTACK_FILENAME.with(|c| c.borrow().clone()),
            buf: vec![0u8; 256],
            bufspc: 256,
            bp: 0,
            bufline: 0,
            bp1: None,
            fm: input.to_string(),
            fm_pos: 0,
            truncwidth: 0,
            dontcount: 0,
            trunccount: 0,
            rstring: None,
            Rstring: None,
            attrs: 0 as zattr, // c:zsh.h:2685 (zattr=0 == no attrs)
            in_escape: false,
            prompt_percent: true, // c:325 (PROMPTPERCENT default)
            prompt_bang: true,    // c:325 (PROMPTBANG default)
        }
    }

    pub fn with_prompt_percent(mut self, enable: bool) -> Self {
        self.prompt_percent = enable;
        self
    }

    pub fn with_prompt_bang(mut self, enable: bool) -> Self {
        self.prompt_bang = enable;
        self
    }

    fn fork_snapshot(&self, input: String) -> buf_vars {
        buf_vars {
            pwd: self.pwd.clone(),
            home: self.home.clone(),
            user: self.user.clone(),
            host: self.host.clone(),
            host_short: self.host_short.clone(),
            tty: self.tty.clone(),
            lastval: self.lastval,
            histnum: self.histnum,
            shlvl: self.shlvl,
            num_jobs: self.num_jobs,
            is_root: self.is_root,
            cmd_stack: self.cmd_stack.clone(),
            psvar: self.psvar.clone(),
            term_width: self.term_width,
            lineno: self.lineno,
            scriptname: self.scriptname.clone(),
            scriptfilename: self.scriptfilename.clone(),
            argzero: self.argzero.clone(),
            func_line_base: self.func_line_base,
            funcstack_filename: self.funcstack_filename.clone(),
            buf: Vec::new(),
            bufspc: 0,
            bp: 0,
            bufline: 0,
            bp1: None,
            fm: input,
            fm_pos: 0,
            truncwidth: 0,
            dontcount: 0,
            trunccount: 0,
            rstring: None,
            Rstring: None,
            attrs: self.attrs,
            in_escape: false,
            prompt_percent: self.prompt_percent,
            prompt_bang: self.prompt_bang,
        }
    }

    /// Src/prompt.c:991 `addbufspc`
    fn addbufspc(&mut self, need: usize) {
        let need = need.saturating_mul(2).max(need.max(1));
        self.buf.reserve(need);
        self.bufspc = self.buf.capacity();
    }

    /// Src/prompt.c:976 `pputc` — metafy high bytes.
    fn pputc(&mut self, c: u8) {
        self.addbufspc(2);
        let bp = self.bp;
        if crate::ported::utils::imeta_byte(c) {
            self.buf.resize(bp + 2, 0);
            self.buf[bp] = crate::ported::utils::Meta;
            self.buf[bp + 1] = c ^ 32;
            self.bp = bp + 2;
        } else {
            self.buf.resize(bp + 1, 0);
            self.buf[bp] = c;
            self.bp = bp + 1;
        }
        if c == b'\n' && self.dontcount == 0 {
            self.bufline = self.bp;
        }
    }

    fn out_raw_byte(&mut self, b: u8) {
        self.addbufspc(1);
        let bp = self.bp;
        self.buf.resize(bp + 1, 0);
        self.buf[bp] = b;
        self.bp = bp + 1;
    }

    fn out_char(&mut self, c: char) {
        let mut tmp = [0u8; 4];
        let enc = c.encode_utf8(&mut tmp);
        for &b in enc.as_bytes() {
            self.pputc(b);
        }
    }

    fn out_str(&mut self, s: &str) {
        for &b in s.as_bytes() {
            self.pputc(b);
        }
    }

    /// Append raw metafied bytes from a nested `putpromptchar` (`%(…)` branches).
    fn append_buf_from(&mut self, other: &buf_vars) {
        let end = other.bp.min(other.buf.len());
        if end == 0 {
            return;
        }
        self.addbufspc(end);
        let bp0 = self.bp;
        self.buf.resize(bp0 + end, 0);
        self.buf[bp0..bp0 + end].copy_from_slice(&other.buf[..end]);
        self.bp = bp0 + end;
        if self.dontcount == 0 {
            for i in 0..end {
                if other.buf[i] == b'\n' {
                    self.bufline = bp0 + i + 1;
                }
            }
        }
    }

    /// After expansion: `unmetafy` for display (lossy UTF-8).
    pub fn expanded_utf8(&self) -> String {
        let end = self.bp.min(self.buf.len());
        let mut v = self.buf[..end].to_vec();
        crate::ported::utils::unmetafy(&mut v);
        String::from_utf8_lossy(&v).into_owned()
    }

    /// Src/prompt.c:236-246 — strip Inpar/Outpar/Nularg when `ns == 0`.
    fn strip_prompt_tokens_ns0(&mut self) {
        let end = self.bp.min(self.buf.len());
        let mut v = Vec::with_capacity(end);
        let mut i = 0usize;
        while i < end {
            let b = self.buf[i];
            if b == crate::ported::utils::Meta {
                if i + 1 < end {
                    v.push(b);
                    v.push(self.buf[i + 1]);
                    i += 2;
                } else {
                    i += 1;
                }
                continue;
            }
            if b == Inpar as u8 || b == Outpar as u8 || b == Nularg as u8 {
                i += 1;
                continue;
            }
            v.push(b);
            i += 1;
        }
        self.buf = v;
        self.bp = self.buf.len();
    }

    pub fn finish_expanded_string(&mut self, keep_spacing_tokens: bool) -> String {
        if !keep_spacing_tokens {
            self.strip_prompt_tokens_ns0();
        }
        self.expanded_utf8()
    }

    /// Src/prompt.c:359 — core of `putpromptchar(int doprint, int endchar)`.
    pub(crate) fn run_putpromptchar(&mut self, doprint: i32, endchar: i32) -> i32 {
        loop {
            if self.fm_pos >= self.fm.len() {
                return 0;
            }
            let ec = endchar as u8;
            if ec != 0 {
                let b = self.fm.as_bytes()[self.fm_pos];
                if b == ec {
                    return endchar;
                }
            }

            let c = match self.peek() {
                Some(c) => c,
                None => return 0,
            };

            if c == '%' && self.prompt_percent {
                self.advance();
                self.process_percent(doprint);
            } else if c == '!' && self.prompt_bang {
                if doprint != 0 {
                    self.advance();
                    if self.peek() == Some('!') {
                        self.advance();
                        self.out_char('!');
                    } else {
                        self.out_str(&self.histnum.to_string());
                    }
                } else {
                    self.advance();
                    if self.peek() == Some('!') {
                        self.advance();
                    }
                }
            } else {
                self.advance();
                if doprint != 0 {
                    self.out_char(c);
                }
            }
        }
    }

    fn peek(&self) -> Option<char> {
        self.fm[self.fm_pos..].chars().next()
    }

    fn advance(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.fm_pos += c.len_utf8();
        Some(c)
    }

    fn parse_number(&mut self) -> Option<i32> {
        let start = self.fm_pos;
        let mut negative = false;

        if self.peek() == Some('-') {
            negative = true;
            self.advance();
        }

        while let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                self.advance();
            } else {
                break;
            }
        }

        if self.fm_pos == start || (negative && self.fm_pos == start + 1) {
            if negative {
                self.fm_pos = start;
            }
            return None;
        }

        let num_str = &self.fm[if negative { start + 1 } else { start }..self.fm_pos];
        let num: i32 = num_str.parse().ok()?;
        Some(if negative { -num } else { num })
    }

    fn parse_braced_arg(&mut self) -> Option<String> {
        if self.peek() != Some('{') {
            return None;
        }
        self.advance(); // skip {

        let start = self.fm_pos;
        let mut depth = 1;

        while let Some(c) = self.advance() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(self.fm[start..self.fm_pos - 1].to_string());
                    }
                }
                '\\' => {
                    self.advance(); // skip escaped char
                }
                _ => {}
            }
        }

        None
    }

    /// Get path with tilde substitution
    fn path_with_tilde(&self, path: &str) -> String {
        if !self.home.is_empty() && path.starts_with(&self.home) {
            format!("~{}", &path[self.home.len()..])
        } else {
            path.to_string()
        }
    }

    /// Get trailing path components
    fn trailing_path(&self, path: &str, n: usize, with_tilde: bool) -> String {
        let path = if with_tilde {
            self.path_with_tilde(path)
        } else {
            path.to_string()
        };

        if n == 0 {
            return path;
        }

        let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        if components.len() <= n {
            return path;
        }

        components[components.len() - n..].join("/")
    }

    /// Get leading path components
    fn leading_path(&self, path: &str, n: usize) -> String {
        if n == 0 {
            return path.to_string();
        }

        let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        if components.len() <= n {
            return path.to_string();
        }

        let result = components[..n].join("/");
        if path.starts_with('/') {
            format!("/{}", result)
        } else {
            result
        }
    }

    /// Start escape sequence (non-printing characters)
    fn start_escape(&mut self) {
        if !self.in_escape {
            self.out_char('\x01'); // RL_PROMPT_START_IGNORE
            self.in_escape = true;
        }
    }

    /// End escape sequence
    fn end_escape(&mut self) {
        if self.in_escape {
            self.out_char('\x02'); // RL_PROMPT_END_IGNORE
            self.in_escape = false;
        }
    }

    /// Apply text attributes incrementally. zsh emits just the new
    /// SGR codes (no leading `\e[0m`) when adding attrs to a default
    /// state — only emit a reset when there's nothing to apply (rare,
    /// covered by the explicit `%b`/`%f`/`%k`/`%u` reset handlers).
    fn apply_attrs(&mut self) {
        self.start_escape();
        if self.attrs & TXTBOLDFACE != 0 { // c:1645
            self.out_str("\x1b[1m");
        }
        if self.attrs & TXTUNDERLINE != 0 { // c:1645
            self.out_str("\x1b[4m");
        }
        if self.attrs & TXTSTANDOUT != 0 { // c:1645
            // zsh emits italic (`3m`) for `%S` standout, not reverse
            // video (`7m`). Match zsh's actual prompt output.
            self.out_str("\x1b[3m");
        }
        if self.attrs & TXTFGCOLOUR != 0 { // c:1645
            let raw = (self.attrs & TXT_ATTR_FG_COL_MASK) >> TXT_ATTR_FG_COL_SHIFT;
            let c = if self.attrs & TXT_ATTR_FG_24BIT != 0 {
                COLOR_24BIT | (raw as Color & 0x00ff_ffff)
            } else { raw as Color };
            self.out_str(&color_to_ansi(c, true));
        }
        if self.attrs & TXTBGCOLOUR != 0 { // c:1645
            let raw = (self.attrs & TXT_ATTR_BG_COL_MASK) >> TXT_ATTR_BG_COL_SHIFT;
            let c = if self.attrs & TXT_ATTR_BG_24BIT != 0 {
                COLOR_24BIT | (raw as Color & 0x00ff_ffff)
            } else { raw as Color };
            self.out_str(&color_to_ansi(c, false));
        }
        self.end_escape();
    }

    /// Parse conditional %(x.true.false)
    fn parse_conditional(&mut self, arg: i32, doprint: i32) -> bool {
        if self.peek() != Some('(') {
            return false;
        }
        self.advance(); // skip (

        // Parse condition character
        let cond_char = match self.advance() {
            Some(c) => c,
            None => return false,
        };

        // Evaluate condition
        let test = match cond_char {
            '/' | 'c' | '.' | '~' | 'C' => {
                // Directory depth test
                let path = self.path_with_tilde(&self.pwd);
                let depth = path.matches('/').count() as i32;
                if arg == 0 {
                    depth > 0
                } else {
                    depth >= arg
                }
            }
            '?' => self.lastval == arg,
            '#' => {
                let euid = unsafe { libc::geteuid() };
                euid == arg as u32
            }
            'L' => self.shlvl >= arg,
            'j' => self.num_jobs >= arg,
            'v' => (arg as usize) <= self.psvar.len(),
            'V' => {
                if arg <= 0 || (arg as usize) > self.psvar.len() {
                    false
                } else {
                    !self.psvar[arg as usize - 1].is_empty()
                }
            }
            '_' => self.cmd_stack.len() >= arg as usize,
            't' | 'T' | 'd' | 'D' | 'w' => {
                let now = chrono::Local::now();
                match cond_char {
                    't' => now.format("%M").to_string().parse::<i32>().unwrap_or(0) == arg,
                    'T' => now.format("%H").to_string().parse::<i32>().unwrap_or(0) == arg,
                    'd' => now.format("%d").to_string().parse::<i32>().unwrap_or(0) == arg,
                    'D' => now.format("%m").to_string().parse::<i32>().unwrap_or(0) == arg - 1,
                    'w' => now.format("%w").to_string().parse::<i32>().unwrap_or(0) == arg,
                    _ => false,
                }
            }
            '!' => self.is_root,
            _ => false,
        };

        // Get separator
        let sep = match self.advance() {
            Some(c) => c,
            None => return false,
        };

        // Parse true branch
        let true_start = self.fm_pos;
        let mut depth = 1;
        while let Some(c) = self.peek() {
            if c == '(' {
                depth += 1;
            } else if c == ')' {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            } else if c == sep && depth == 1 {
                break;
            }
            self.advance();
        }
        let true_branch = self.fm[true_start..self.fm_pos].to_string();

        if self.peek() != Some(sep) {
            return false;
        }
        self.advance(); // skip separator

        // Parse false branch
        let false_start = self.fm_pos;
        depth = 1;
        while let Some(c) = self.peek() {
            if c == '(' {
                depth += 1;
            } else if c == ')' {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            self.advance();
        }
        let false_branch = self.fm[false_start..self.fm_pos].to_string();

        if self.peek() != Some(')') {
            return false;
        }
        self.advance(); // skip )

        // Src/prompt.c:511-516 — `putpromptchar(test && doprint, sep)` then
        // `putpromptchar(!test && doprint, ')' )`; same `bv->buf`, we append serially.
        let mut tsub = self.fork_snapshot(true_branch);
        tsub.run_putpromptchar(if test { doprint } else { 0 }, 0);
        self.append_buf_from(&tsub);
        let mut fsub = self.fork_snapshot(false_branch);
        fsub.run_putpromptchar(if test { 0 } else { doprint }, 0);
        self.append_buf_from(&fsub);

        true
    }

    /// Parse and process a % escape sequence
    fn process_percent(&mut self, doprint: i32) {
        let arg = self.parse_number().unwrap_or(0);

        // Check for conditional
        if self.peek() == Some('(') {
            self.parse_conditional(arg, doprint);
            return;
        }

        if doprint == 0 {
            // Src/prompt.c:520-538 — parse-only skips; C `default: continue` advances
            // past one opcode byte after the (already-parsed) numeric arg.
            match self.peek() {
                Some('[') => {
                    self.advance();
                    let _ = self.parse_number();
                    while self.peek() != Some(']') {
                        if self.advance().is_none() {
                            break;
                        }
                    }
                    let _ = self.advance();
                    return;
                }
                Some('<') | Some('>') => {
                    let end = self.peek().unwrap();
                    self.advance();
                    while self.peek() != Some(end) {
                        if self.advance().is_none() {
                            break;
                        }
                    }
                    let _ = self.advance();
                    return;
                }
                Some('D') => {
                    self.advance();
                    if self.peek() == Some('{') {
                        while self.peek() != Some('}') {
                            if self.advance().is_none() {
                                break;
                            }
                        }
                        let _ = self.advance();
                    }
                    return;
                }
                _ => {
                    let _ = self.advance();
                    return;
                }
            }
        }

        let c = match self.advance() {
            Some(c) => c,
            None => return,
        };

        match c {
            // Directory
            '~' => {
                let path = if arg == 0 {
                    self.path_with_tilde(&self.pwd)
                } else if arg > 0 {
                    self.trailing_path(&self.pwd, arg as usize, true)
                } else {
                    self.leading_path(&self.path_with_tilde(&self.pwd), (-arg) as usize)
                };
                self.out_str(&path);
            }
            'd' | '/' => {
                let path = if arg == 0 {
                    self.pwd.clone()
                } else if arg > 0 {
                    self.trailing_path(&self.pwd, arg as usize, false)
                } else {
                    self.leading_path(&self.pwd, (-arg) as usize)
                };
                self.out_str(&path);
            }
            'c' | '.' => {
                let n = if arg == 0 {
                    1
                } else {
                    arg.unsigned_abs() as usize
                };
                let path = self.trailing_path(&self.pwd, n, true);
                self.out_str(&path);
            }
            'C' => {
                let n = if arg == 0 {
                    1
                } else {
                    arg.unsigned_abs() as usize
                };
                let path = self.trailing_path(&self.pwd, n, false);
                self.out_str(&path);
            }

            // Script name (or argzero fallback) — port of
            // Src/prompt.c:554-556 `case 'N': promptpath(scriptname
            // ? scriptname : argzero, arg, 0)`. The `arg` selects N
            // trailing path components (0 = full path).
            'N' => {
                let name = self
                    .scriptname
                    .clone()
                    .unwrap_or_else(|| self.argzero.clone());
                let n = if arg <= 0 {
                    0
                } else {
                    arg.unsigned_abs() as usize
                };
                if n == 0 {
                    self.out_str(&name);
                } else {
                    let tail = self.trailing_path(&name, n, false);
                    self.out_str(&tail);
                }
            }
            // User/host
            'n' => {
                let u = self.user.clone();
                self.out_str(&u);
            }
            'M' => {
                let h = self.host.clone();
                self.out_str(&h);
            }
            'm' => {
                let n = if arg == 0 { 1 } else { arg };
                if n > 0 {
                    let parts: Vec<&str> = self.host.split('.').collect();
                    let take = (n as usize).min(parts.len());
                    self.out_str(&parts[..take].join("."));
                } else {
                    let parts: Vec<&str> = self.host.split('.').collect();
                    let skip = ((-n) as usize).min(parts.len());
                    self.out_str(&parts[skip..].join("."));
                }
            }

            // TTY
            'l' => {
                let tty = if self.tty.starts_with("/dev/tty") {
                    self.tty[8..].to_string()
                } else if self.tty.starts_with("/dev/") {
                    self.tty[5..].to_string()
                } else {
                    "()".to_string()
                };
                self.out_str(&tty);
            }
            'y' => {
                // zsh: `%y` is the tty short name (without `/dev/`).
                // When not connected to a tty (e.g. in `-c` mode or
                // a pipe), zsh outputs `()` matching the `%l` form.
                let tty = if self.tty.is_empty() {
                    "()".to_string()
                } else if self.tty.starts_with("/dev/") {
                    self.tty[5..].to_string()
                } else {
                    self.tty.clone()
                };
                self.out_str(&tty);
            }

            // Status
            '?' => self.out_str(&self.lastval.to_string()),
            '#' => self.out_char(if self.is_root { '#' } else { '%' }),

            // History
            'h' | '!' => self.out_str(&self.histnum.to_string()),

            // Jobs
            'j' => self.out_str(&self.num_jobs.to_string()),

            // Shell level
            'L' => self.out_str(&self.shlvl.to_string()),

            // Line number (`%i`) — Src/prompt.c:923-929 after optional `%I` block.
            'i' => self.out_str(&self.lineno.to_string()),

            // `%I` — Src/prompt.c:901-920: inside `funcstack` (not SOURCE,
            // not `IN_EVAL_TRAP`), file line is `lineno + funcstack->flineno`.
            // zshrs stores the addend as `func_line_base` (`first_body_line - 1`
            // at registration). `FS_EVAL` / trap nuances not wired yet.
            'I' => {
                let n = if let Some(base) = self.func_line_base {
                    self.lineno.saturating_add(base)
                } else {
                    self.lineno
                };
                self.out_str(&n.to_string());
            }

            // `%x` — Src/prompt.c:931-937: inside the same frames, use
            // `funcstack->filename` (here `funcstack_filename`); else
            // `scriptfilename ? scriptfilename : argzero`.
            'x' => {
                let n = if arg <= 0 {
                    0
                } else {
                    arg.unsigned_abs() as usize
                };
                if self.func_line_base.is_some() {
                    let path = self
                        .funcstack_filename
                        .clone()
                        .unwrap_or_default();
                    if n == 0 {
                        self.out_str(&path);
                    } else {
                        let tail = self.trailing_path(&path, n, false);
                        self.out_str(&tail);
                    }
                } else {
                    let name = self
                        .scriptfilename
                        .clone()
                        .or_else(|| self.scriptname.clone())
                        .unwrap_or_else(|| self.argzero.clone());
                    if n == 0 {
                        self.out_str(&name);
                    } else {
                        let tail = self.trailing_path(&name, n, false);
                        self.out_str(&tail);
                    }
                }
            }

            // Date/time (`%D{...}` — zsh strftime → chrono format)
            'D' => {
                let now = chrono::Local::now();
                if let Some(fmt) = self.parse_braced_arg() {
                    let mut chrono_fmt = String::new();
                    let mut chars = fmt.chars().peekable();
                    while let Some(c) = chars.next() {
                        if c == '%' {
                            match chars.next() {
                                Some('a') => chrono_fmt.push_str("%a"),
                                Some('A') => chrono_fmt.push_str("%A"),
                                Some('b') | Some('h') => chrono_fmt.push_str("%b"),
                                Some('B') => chrono_fmt.push_str("%B"),
                                Some('c') => chrono_fmt.push_str("%c"),
                                Some('C') => chrono_fmt.push_str("%y"),
                                Some('d') => chrono_fmt.push_str("%d"),
                                Some('D') => chrono_fmt.push_str("%m/%d/%y"),
                                Some('e') => chrono_fmt.push_str("%e"),
                                Some('f') => chrono_fmt.push_str("%e"),
                                Some('F') => chrono_fmt.push_str("%Y-%m-%d"),
                                Some('H') => chrono_fmt.push_str("%H"),
                                Some('I') => chrono_fmt.push_str("%I"),
                                Some('j') => chrono_fmt.push_str("%j"),
                                Some('k') => chrono_fmt.push_str("%k"),
                                Some('K') => chrono_fmt.push_str("%H"),
                                Some('l') => chrono_fmt.push_str("%l"),
                                Some('L') => chrono_fmt.push_str("%3f"),
                                Some('m') => chrono_fmt.push_str("%m"),
                                Some('M') => chrono_fmt.push_str("%M"),
                                Some('n') => chrono_fmt.push('\n'),
                                Some('N') => chrono_fmt.push_str("%9f"),
                                Some('p') => chrono_fmt.push_str("%p"),
                                Some('P') => chrono_fmt.push_str("%P"),
                                Some('r') => chrono_fmt.push_str("%r"),
                                Some('R') => chrono_fmt.push_str("%R"),
                                Some('s') => chrono_fmt.push_str("%s"),
                                Some('S') => chrono_fmt.push_str("%S"),
                                Some('t') => chrono_fmt.push('\t'),
                                Some('T') => chrono_fmt.push_str("%T"),
                                Some('u') => chrono_fmt.push_str("%u"),
                                Some('U') => chrono_fmt.push_str("%U"),
                                Some('V') => chrono_fmt.push_str("%V"),
                                Some('w') => chrono_fmt.push_str("%w"),
                                Some('W') => chrono_fmt.push_str("%W"),
                                Some('x') => chrono_fmt.push_str("%x"),
                                Some('X') => chrono_fmt.push_str("%X"),
                                Some('y') => chrono_fmt.push_str("%y"),
                                Some('Y') => chrono_fmt.push_str("%Y"),
                                Some('z') => chrono_fmt.push_str("%z"),
                                Some('Z') => chrono_fmt.push_str("%Z"),
                                Some('%') => chrono_fmt.push('%'),
                                Some(other) => {
                                    chrono_fmt.push('%');
                                    chrono_fmt.push(other);
                                }
                                None => chrono_fmt.push('%'),
                            }
                        } else {
                            chrono_fmt.push(c);
                        }
                    }
                    self.out_str(&now.format(&chrono_fmt).to_string());
                } else {
                    self.out_str(&now.format("%y-%m-%d").to_string());
                }
            }
            'T' => {
                // zsh prints %T with no zero-pad on the hour: 04:10 → 4:10.
                // chrono's %H always zero-pads; use %k (space-padded hour
                // 0-23) and trim the leading space. Without this, zshrs
                // emitted `04:10` while zsh emitted `4:10` for early
                // hours.
                let now = chrono::Local::now();
                let formatted = now.format("%k:%M").to_string();
                self.out_str(formatted.trim_start());
            }
            '*' => {
                let now = chrono::Local::now();
                let formatted = now.format("%k:%M:%S").to_string();
                self.out_str(formatted.trim_start());
            }
            't' | '@' => {
                let now = chrono::Local::now();
                self.out_str(&now.format("%l:%M%p").to_string());
            }
            'w' => {
                let now = chrono::Local::now();
                self.out_str(&now.format("%a %e").to_string());
            }
            'W' => {
                let now = chrono::Local::now();
                self.out_str(&now.format("%m/%d/%y").to_string());
            }

            // Text attributes — emit only the SGR for the newly
            // toggled attribute, not all currently-active ones.
            // zsh: `%B%S%U` → `\e[1m\e[3m\e[4m` (each is independent).
            // apply_attrs would re-emit all active attrs every call,
            // producing duplicate codes.
            'B' => {
                self.attrs |= TXTBOLDFACE; // c:zsh.h:2694
                self.start_escape();
                self.out_str("\x1b[1m");
                self.end_escape();
            }
            'b' => {
                // zsh's %b emits a full SGR reset `\e[0m` (matches the
                // raw bytes mainline zsh produces). The incremental
                // SGR-22 (bold off) would also work but zsh chose the
                // full reset.
                self.attrs &= !TXTBOLDFACE; // c:zsh.h:2694
                self.start_escape();
                self.out_str("\x1b[0m");
                self.end_escape();
            }
            'U' => {
                self.attrs |= TXTUNDERLINE; // c:zsh.h:2697
                self.start_escape();
                self.out_str("\x1b[4m");
                self.end_escape();
            }
            'u' => {
                self.attrs &= !TXTUNDERLINE; // c:zsh.h:2697
                self.start_escape();
                self.out_str("\x1b[24m");
                self.end_escape();
            }
            'S' => {
                self.attrs |= TXTSTANDOUT; // c:zsh.h:2696
                self.start_escape();
                // zsh emits italic (`3m`) for `%S` standout, not
                // reverse video (`7m`). Match zsh's actual output.
                self.out_str("\x1b[3m");
                self.end_escape();
            }
            's' => {
                self.attrs &= !TXTSTANDOUT; // c:zsh.h:2696
                self.start_escape();
                // zsh emits the italic-end (`23m`) for `%s` rather
                // than the reverse-end (`27m`). Match zsh's output
                // so terminal state agrees with what `%S` set.
                self.out_str("\x1b[23m");
                self.end_escape();
            }

            // Colors
            'F' => {
                let color: Option<Color> = if let Some(name) = self.parse_braced_arg() {
color_from_name(&name) // c:336 (match_colour)
                } else if arg > 0 {
                    Some(arg as Color) // c:622 (parsecolorchar numeric)
                } else {
                    None
                };
                if let Some(c) = color {
                    if let Some((r, g, b)) = color_get_rgb(c) {
                        self.attrs = zattr_set_fg_rgb(self.attrs, r, g, b); // c:2440
                    } else {
                        self.attrs = zattr_set_fg_palette(self.attrs, c as u8); // c:2440
                    }
                    // Emit ONLY the color code, not all active attrs.
                    // apply_attrs would re-emit bold/underline/standout
                    // each time `%F` runs, producing duplicate codes.
                    self.start_escape();
                    self.out_str(&color_to_ansi(c, true));
                    self.end_escape();
                }
            }
            'f' => {
                // zsh emits the default-foreground escape `\e[39m`
                // (not a full `\e[0m` reset) — preserves background
                // color and other attrs. Going through apply_attrs
                // would emit a full reset which over-clears.
                self.attrs &= !TXT_ATTR_FG_MASK; // c:zsh.h:2732
                self.start_escape();
                self.out_str("\x1b[39m");
                self.end_escape();
            }
            'K' => {
                let color: Option<Color> = if let Some(name) = self.parse_braced_arg() {
color_from_name(&name) // c:336
                } else if arg > 0 {
                    Some(arg as Color) // c:634
                } else {
                    None
                };
                if let Some(c) = color {
                    if let Some((r, g, b)) = color_get_rgb(c) {
                        self.attrs = zattr_set_bg_rgb(self.attrs, r, g, b); // c:2440
                    } else {
                        self.attrs = zattr_set_bg_palette(self.attrs, c as u8); // c:2440
                    }
                    self.start_escape();
                    self.out_str(&color_to_ansi(c, false));
                    self.end_escape();
                }
            }
            'k' => {
                // zsh's `%k` emits `\e[49m` (default bg only); zshrs
                // was going through apply_attrs which would re-emit
                // all active attrs.
                self.attrs &= !TXT_ATTR_BG_MASK; // c:zsh.h:2736
                self.start_escape();
                self.out_str("\x1b[49m");
                self.end_escape();
            }

            // Literal escape sequences
            '{' => self.start_escape(),
            '}' => self.end_escape(),

            // Glitch space
            'G' => {
                let n = if arg > 0 { arg as usize } else { 1 };
                for _ in 0..n {
                    self.out_char(' ');
                }
            }

            // psvar
            'v' => {
                let idx = if arg == 0 { 1 } else { arg };
                if idx > 0 && (idx as usize) <= self.psvar.len() {
                    let s = self.psvar[idx as usize - 1].clone();
                    self.out_str(&s);
                }
            }

            // Command stack — direct port of Src/prompt.c:855-880
            // case '_'. arg >= 0 prints the TOP `arg` elements
            // BOTTOM-UP (oldest first). arg < 0 prints the BOTTOM
            // `-arg` elements bottom-up. arg == 0 prints all.
            '_' => {
                let cmdsp = self.cmd_stack.len();
                if cmdsp > 0 {
                    let names: Vec<&str> = if arg >= 0 {
                        let mut n = if arg == 0 { cmdsp } else { arg as usize };
                        if n > cmdsp {
                            n = cmdsp;
                        }
                        // Walk forward from `cmdsp - n` to top.
                        // c:Src/prompt.c:835 — `cmdnames[cmdstack[t0]]`
                        self.cmd_stack
                            .iter()
                            .skip(cmdsp - n)
                            .filter_map(|b| CMDNAMES.get(*b as usize).copied())
                            .collect()
                    } else {
                        let mut n = (-arg) as usize;
                        if n > cmdsp {
                            n = cmdsp;
                        }
                        // Walk forward from 0 to `n`.
                        // c:Src/prompt.c:872 — `cmdnames[cmdstack[t0]]`
                        self.cmd_stack
                            .iter()
                            .take(n)
                            .filter_map(|b| CMDNAMES.get(*b as usize).copied())
                            .collect()
                    };
                    self.out_str(&names.join(" "));
                }
            }

            // Clear to end of line
            'E' => {
                self.start_escape();
                self.out_str("\x1b[K");
                self.end_escape();
            }

            // Literal characters
            '%' => self.out_char('%'),
            ')' => self.out_char(')'),
            '\0' => {}

            // Unknown - output literally
            _ => {
                self.out_char('%');
                self.out_char(c);
            }
        }
    }

    /// Expand the prompt (`promptexpand` → `putpromptchar(1,0)` in C).
    pub fn expand(mut self) -> String {
        self.run_putpromptchar(1, 0);
        self.finish_expanded_string(false)
    }
}

/// Match a `%F`/`%K` argument as a colour spec.
/// Port of `match_colour(const char **teststrp, int is_fg, int colour)` from Src/prompt.c:1957 — accepts
/// named, numeric, and `#RRGGBB` truecolor forms.
/// WARNING: param names don't match C — Rust=(spec, is_fg) vs C=(teststrp, is_fg, colour)
pub fn match_colour(spec: &str, is_fg: bool) -> Option<String> {
    // Try named colour
    if let Some(code) = match_named_colour(spec) {
        return Some(output_colour(code, is_fg));
    }
    // Try #RRGGBB
    if spec.starts_with('#') && spec.len() == 7 {
        let r = u8::from_str_radix(&spec[1..3], 16).ok()?;
        let g = u8::from_str_radix(&spec[3..5], 16).ok()?;
        let b = u8::from_str_radix(&spec[5..7], 16).ok()?;
        return Some(output_truecolor(r, g, b, is_fg));
    }
    // Try number
    if let Ok(n) = spec.parse::<u8>() {
        return Some(output_colour(n, is_fg));
    }
    None
}

/// Match a highlight specification, returning attrs + mask.
/// Port of `match_highlight(const char *teststr, zattr *on_var, zattr *setmask, int *layer)` from Src/prompt.c:2031 — the
/// mask records which fields were explicitly set so callers can
/// merge against a default. Both values are canonical `zattr`
/// bitfields (c:Src/zsh.h:2685); the mask carries the same
/// attribute / TXT*COLOUR bits as `attrs` but zeroes out the
/// actual colour indices so callers can detect "this bit was
/// set vs default" by mask-and against `TXT_ATTR_*_MASK`.
/// WARNING: param names don't match C — Rust=(spec) vs C=(teststr, on_var, setmask, layer)
pub fn match_highlight(spec: &str) -> (zattr, zattr) {
    let attrs = parsehighlight(spec);
    let mut mask: zattr = 0;
    mask |= attrs & (TXTBOLDFACE | TXTUNDERLINE | TXTSTANDOUT); // c:2031
    if attrs & TXTFGCOLOUR != 0 { mask |= TXTFGCOLOUR; } // c:2031
    if attrs & TXTBGCOLOUR != 0 { mask |= TXTBGCOLOUR; } // c:2031
    (attrs, mask)
}

/// Build an ANSI escape for an indexed colour.
/// Port of `output_colour(int colour, int fg_bg, int truecol, char *buf)` from Src/prompt.c:2136.
/// WARNING: param names don't match C — Rust=(colour, is_fg) vs C=(colour, fg_bg, truecol, buf)
pub fn output_colour(colour: u8, is_fg: bool) -> String {                    // c:2136
    let base = if is_fg { 30 } else { 40 };
    if colour < 8 {
        format!("\x1b[{}m", base + colour)
    } else if colour < 16 {
        format!("\x1b[{};1m", base + colour - 8)
    } else {
        let mode = if is_fg { 38 } else { 48 };
        format!("\x1b[{};5;{}m", mode, colour)
    }
}

/// Port of `output_highlight(zattr atr, char *buf)` from
/// Src/prompt.c:2179. Delegates to `apply_text_attributes` which
/// renders zattr to the comma-joined `bold,fg=red,...` form.
/// WARNING: param names don't match C — Rust=(attrs) vs C=(atr, mask, buf)
pub fn output_highlight(attrs: zattr) -> String {                            // c:2179
    apply_text_attributes(attrs)
}

/// Compute the default-colour reset sequences.
/// Port of `set_default_colour_sequences()` from Src/prompt.c:2341.
pub fn set_default_colour_sequences() -> (String, String) {
    // Default: use ANSI sequences
    ("\x1b[0m".to_string(), "\x1b[0m".to_string())
}

/// Build a colour escape string from a specification.
/// Port of `set_colour_code(char *str, char **var)` from Src/prompt.c:2353.
/// WARNING: param names don't match C — Rust=(spec) vs C=(str, var)
pub fn set_colour_code(spec: &str) -> Option<String> {
    match_colour(spec, true)
}

/// Port of `static struct colour_sequences { char *start; char *end;
/// char *def; }` from Src/prompt.c:2319. Holds the active terminal
/// escape-prefix/suffix/default-reset codes for FG and BG channels.
#[derive(Default, Clone)]
pub struct colour_sequences {                                                // c:2319
    pub start: String,                                                       // c:2320
    pub end: String,                                                         // c:2321
    pub def: String,                                                         // c:2322
}

// COL_SEQ_FG / COL_SEQ_BG live in zsh.h:2749-2750 — ported to
// `crate::ported::zsh_h::COL_SEQ_FG` and `::COL_SEQ_BG`. Header-defined
// constants belong in the header port per PORT.md Rule C.

/// Port of `static struct colour_sequences fg_bg_sequences[2]` from
/// `Src/prompt.c:2324`.
pub static fg_bg_sequences: std::sync::Mutex<[colour_sequences; 2]> =        // c:2324
    std::sync::Mutex::new([
        colour_sequences { start: String::new(), end: String::new(), def: String::new() },
        colour_sequences { start: String::new(), end: String::new(), def: String::new() },
    ]);

/// Port of `static char *colseq_buf` from `Src/prompt.c:2332`.
/// We need a buffer for colour sequence composition. It may
/// vary depending on the sequences set. However, it's inefficient
/// allocating it separately every time we send a colour sequence,
/// so do it once per refresh.
pub static colseq_buf: std::sync::Mutex<Vec<u8>> = std::sync::Mutex::new(Vec::new());  // c:2332

/// Port of `static int colseq_buf_allocs` from `Src/prompt.c:2337`.
/// Count how often this has been allocated, for recursive usage.
pub static colseq_buf_allocs: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:2337

/// Port of `mod_export void allocate_colour_buffer(void)` from
/// `Src/prompt.c:2367`. Allocates the per-refresh colour-sequence
/// composition buffer, populating `fg_bg_sequences` from
/// `$zle_highlight` overrides when present.
///
/// ```c
/// mod_export void
/// allocate_colour_buffer(void)
/// {
///     char **atrs;
///     int lenfg, lenbg, len;
///     if (colseq_buf_allocs++) return;
///     atrs = getaparam("zle_highlight");
///     if (atrs) {
///         for (; *atrs; atrs++) {
///             if (strpfx("fg_start_code:", *atrs)) {
///                 set_colour_code(*atrs + 14, &fg_bg_sequences[COL_SEQ_FG].start);
///             } else if (strpfx("fg_default_code:", *atrs)) {
///                 set_colour_code(*atrs + 16, &fg_bg_sequences[COL_SEQ_FG].def);
///             } else if (strpfx("fg_end_code:", *atrs)) {
///                 set_colour_code(*atrs + 12, &fg_bg_sequences[COL_SEQ_FG].end);
///             } else if (strpfx("bg_start_code:", *atrs)) {
///                 set_colour_code(*atrs + 14, &fg_bg_sequences[COL_SEQ_BG].start);
///             } else if (strpfx("bg_default_code:", *atrs)) {
///                 set_colour_code(*atrs + 16, &fg_bg_sequences[COL_SEQ_BG].def);
///             } else if (strpfx("bg_end_code:", *atrs)) {
///                 set_colour_code(*atrs + 12, &fg_bg_sequences[COL_SEQ_BG].end);
///             }
///         }
///     }
///     lenfg = strlen(fg_bg_sequences[COL_SEQ_FG].def);
///     if (lenfg < 1) lenfg = 1;
///     lenfg += strlen(fg_bg_sequences[COL_SEQ_FG].start) +
///         strlen(fg_bg_sequences[COL_SEQ_FG].end);
///     lenbg = strlen(fg_bg_sequences[COL_SEQ_BG].def);
///     if (lenbg < 1) lenbg = 1;
///     lenbg += strlen(fg_bg_sequences[COL_SEQ_BG].start) +
///         strlen(fg_bg_sequences[COL_SEQ_BG].end);
///     len = lenfg > lenbg ? lenfg : lenbg;
///     colseq_buf = (char *)zalloc(len+15);
/// }
/// ```
pub fn allocate_colour_buffer() {                                            // c:2367
    use std::sync::atomic::Ordering;

    // c:2372 — `if (colseq_buf_allocs++) return;`
    if colseq_buf_allocs.fetch_add(1, Ordering::SeqCst) != 0 {               // c:2372
        return;                                                              // c:2373
    }

    // c:2375 — `atrs = getaparam("zle_highlight");`
    // Rust getaparam takes &mut value, not name — use paramtab lookup
    // directly and pull arrgetfn off the param.
    let atrs: Option<Vec<String>> = {                                        // c:2375
        let tab = crate::ported::params::paramtab().read().ok();
        tab.and_then(|t| t.get("zle_highlight").map(|p| {
            crate::ported::params::arrgetfn(p)
        }))
    };

    if let Some(atrs) = atrs {                                               // c:2376
        let mut seqs = fg_bg_sequences.lock().unwrap();
        for atr in &atrs {                                                   // c:2377
            if crate::ported::utils::strpfx("fg_start_code:", atr) {         // c:2378
                if let Some(c) = set_colour_code(&atr[14..]) {               // c:2379
                    seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].start = c;
                }
            } else if crate::ported::utils::strpfx("fg_default_code:", atr) {// c:2380
                if let Some(c) = set_colour_code(&atr[16..]) {               // c:2381
                    seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].def = c;
                }
            } else if crate::ported::utils::strpfx("fg_end_code:", atr) {    // c:2382
                if let Some(c) = set_colour_code(&atr[12..]) {               // c:2383
                    seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].end = c;
                }
            } else if crate::ported::utils::strpfx("bg_start_code:", atr) {  // c:2384
                if let Some(c) = set_colour_code(&atr[14..]) {               // c:2385
                    seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].start = c;
                }
            } else if crate::ported::utils::strpfx("bg_default_code:", atr) {// c:2386
                if let Some(c) = set_colour_code(&atr[16..]) {               // c:2387
                    seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].def = c;
                }
            } else if crate::ported::utils::strpfx("bg_end_code:", atr) {    // c:2388
                if let Some(c) = set_colour_code(&atr[12..]) {               // c:2389
                    seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].end = c;
                }
            }
        }
    }

    let seqs = fg_bg_sequences.lock().unwrap();
    let mut lenfg: usize = seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].def.len();                       // c:2394
    if lenfg < 1 { lenfg = 1; }                                              // c:2396-2397
    lenfg += seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].start.len() + seqs[crate::ported::zsh_h::COL_SEQ_FG as usize].end.len();      // c:2398-2399

    let mut lenbg: usize = seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].def.len();                       // c:2401
    if lenbg < 1 { lenbg = 1; }                                              // c:2403-2404
    lenbg += seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].start.len() + seqs[crate::ported::zsh_h::COL_SEQ_BG as usize].end.len();      // c:2405-2406
    drop(seqs);

    let len = if lenfg > lenbg { lenfg } else { lenbg };                     // c:2408
    // c:2410 — `colseq_buf = (char *)zalloc(len+15);` (+1 NUL +14 truecolor)
    *colseq_buf.lock().unwrap() = vec![0u8; len + 15];                       // c:2410
}

/// Free the colour-buffer working space.
/// Port of `free_colour_buffer()` from Src/prompt.c:2417.
pub fn free_colour_buffer() {                                                // c:2417
    use std::sync::atomic::Ordering;
    // C body c:2420-2426: `if (--colseq_buf_allocs) return;
    //                      zfree(colseq_buf, ...); colseq_buf = NULL;`
    if colseq_buf_allocs.fetch_sub(1, Ordering::SeqCst) - 1 != 0 {           // c:2420
        return;                                                              // c:2421
    }
    colseq_buf.lock().unwrap().clear();                                      // c:2424
}

/// Port of `set_colour_attribute(zattr atr, int fg_bg, int flags)`
/// from Src/prompt.c:2440. Delegates to `color_to_ansi` which
/// produces the indexed/256-color/truecolor escape.
/// WARNING: param names don't match C — Rust=(color, is_fg) vs C=(atr, fg_bg, flags)
pub fn set_colour_attribute(color: Color, is_fg: bool) -> String {           // c:2440
    color_to_ansi(color, is_fg)
}

// `pub enum CmdState` + `impl CmdState { from_u8, name }` —
// DELETED per user directive ("CmdState fake"). Was a Rust-only
// typed wrapper around the canonical `CS_*` integer constants
// (`Src/zsh.h:2775-2806`, ported to `crate::ported::zsh_h::CS_*`).
// C source pushes raw `unsigned char` bytes onto `cmdstack` and
// indexes `cmdnames[CS_COUNT]` (`Src/prompt.c:62`) for the name.
// Now ported 1:1: callers use `CS_FOO as u8` directly and look up
// names through `cmdname()` below.

// parser states, for %_                                                    // c:60
/// Direct port of `cmdnames[CS_COUNT]` from `Src/prompt.c:62-71`.
/// Indexed by the `CS_*` constants in `zsh_h::CS_FOR..CS_ALWAYS`
/// (`Src/zsh.h:2775-2806`). Used by `%_` prompt expansion to print
/// the active compound-command keyword stack.
pub static CMDNAMES: [&str; crate::ported::zsh_h::CS_COUNT as usize] = [
    "for",      "while",     "repeat",    "select",    // c:63 (CS_FOR..CS_SELECT)
    "until",    "if",        "then",      "else",      // c:64 (CS_UNTIL..CS_ELSE)
    "elif",     "math",      "cond",      "cmdor",     // c:65 (CS_ELIF..CS_CMDOR)
    "cmdand",   "pipe",      "errpipe",   "foreach",   // c:66 (CS_CMDAND..CS_FOREACH)
    "case",     "function",  "subsh",     "cursh",     // c:67 (CS_CASE..CS_CURSH)
    "array",    "quote",     "dquote",    "bquote",    // c:68 (CS_ARRAY..CS_BQUOTE)
    "cmdsubst", "mathsubst", "elif-then", "heredoc",   // c:69 (CS_CMDSUBST..CS_HEREDOC)
    "heredocd", "brace",     "braceparam", "always",   // c:70 (CS_HEREDOCD..CS_ALWAYS)
];
// c:zsh.h:2685-2741

// `Color` is the colour slot lifted out of `zattr` so callers can
// pass a single integer around. Bit layout mirrors the C zattr
// colour bits exactly:
//   bit 31 (0x01000000): the local 24-bit flag — mirrors the
//     C `TXT_ATTR_FG_24BIT` / `TXT_ATTR_BG_24BIT` bit (Src/zsh.h:2727).
//     When set, the low 24 bits hold `0xRRGGBB`. When clear, the
//     low 8 bits hold a palette index 0..=255, where 8 is the
//     "default" sentinel per Src/prompt.c:1909.
// Not a new type — same encoding C packs into `TXT_ATTR_FG_COL_MASK`.
pub type Color = u32; // c:Src/zsh.h:2718 (colour slot)
pub const COLOR_24BIT: Color = 0x0100_0000; // c:zsh.h:2727 (TXT_ATTR_FG_24BIT)

// Sentinel "no colour set" — palette index that lives in
// TXT_ATTR_FG_COL_MASK when the colour is `default` (8 in
// Src/prompt.c:1909). Bits 16-39 are at most 24 bits, so any
// value 0..=255 fits comfortably for palette mode.
pub const COLOUR_DEFAULT: u8 = 8; // c:Src/prompt.c:1909

// Named-colour palette constants. Indexes match `colour_names[]`
// from `Src/prompt.c:1884-1887`. Used in place of the deleted
// `Color::Black`..`Color::White`/`Color::Default` enum variants.
pub const COLOR_BLACK:   Color = 0; // c:1885
pub const COLOR_RED:     Color = 1; // c:1885
pub const COLOR_GREEN:   Color = 2; // c:1885
pub const COLOR_YELLOW:  Color = 3; // c:1885
pub const COLOR_BLUE:    Color = 4; // c:1885
pub const COLOR_MAGENTA: Color = 5; // c:1885
pub const COLOR_CYAN:    Color = 6; // c:1885
pub const COLOR_WHITE:   Color = 7; // c:1885
pub const COLOR_DEFAULT: Color = COLOUR_DEFAULT as Color; // c:1909

// Defines standard ANSI colour names in index order                        // c:1883
/// Direct port of `colour_names[]` from `Src/prompt.c:1884-1887`.
/// Indexed 0-7 = basic ANSI, 8 = "default" sentinel (per
/// `Src/prompt.c:1909` comment "8 is the special value for
/// default"). Single canonical source — the second
/// `match_named_colour` further down this file consumed a
/// drifted local table with `default = 9` which mis-rendered
/// `%F{default}` output.
pub static COLOUR_NAMES: [&str; 9] = [
    "black", "red", "green", "yellow", // c:1885
    "blue", "magenta", "cyan", "white", // c:1885
    "default", // c:1886
];

// Colour / zattr helpers — C inlines these at each call site in Src/prompt.c.
fn color_rgb(r: u8, g: u8, b: u8) -> Color {
    COLOR_24BIT | ((r as Color) << 16) | ((g as Color) << 8) | (b as Color)
}

fn color_get_rgb(c: Color) -> Option<(u8, u8, u8)> {
    if c & COLOR_24BIT == 0 {
        None
    } else {
        Some((
            ((c >> 16) & 0xff) as u8,
            ((c >> 8) & 0xff) as u8,
            (c & 0xff) as u8,
        ))
    }
}

fn color_to_ansi(c: Color, is_fg: bool) -> String {
    if let Some((r, g, b)) = color_get_rgb(c) {
        let lead = if is_fg { 38 } else { 48 };
        format!("\x1b[{};2;{};{};{}m", lead, r, g, b)
    } else {
        output_colour(c as u8, is_fg)
    }
}

fn color_from_name(name: &str) -> Option<Color> {
    if let Some(rest) = name.strip_prefix('#') {
        if rest.len() == 6 {
            let r = u8::from_str_radix(&rest[0..2], 16).ok();
            let g = u8::from_str_radix(&rest[2..4], 16).ok();
            let b = u8::from_str_radix(&rest[4..6], 16).ok();
            match (r, g, b) {
                (Some(r), Some(g), Some(b)) => Some(color_rgb(r, g, b) as Color),
                _ => None,
            }
        } else {
            match_named_colour(name).map(|idx| idx as Color)
        }
    } else {
        match_named_colour(name).map(|idx| idx as Color)
    }
}

fn zattr_set_fg_palette(attrs: zattr, idx: u8) -> zattr {
    let cleared = attrs & !TXT_ATTR_FG_MASK;
    cleared | TXTFGCOLOUR | ((idx as zattr) << TXT_ATTR_FG_COL_SHIFT)
}

fn zattr_set_fg_rgb(attrs: zattr, r: u8, g: u8, b: u8) -> zattr {
    let cleared = attrs & !TXT_ATTR_FG_MASK;
    let rgb = ((r as zattr) << 16) | ((g as zattr) << 8) | (b as zattr);
    cleared | TXTFGCOLOUR | TXT_ATTR_FG_24BIT | (rgb << TXT_ATTR_FG_COL_SHIFT)
}

fn zattr_set_bg_palette(attrs: zattr, idx: u8) -> zattr {
    let cleared = attrs & !TXT_ATTR_BG_MASK;
    cleared | TXTBGCOLOUR | ((idx as zattr) << TXT_ATTR_BG_COL_SHIFT)
}

fn zattr_set_bg_rgb(attrs: zattr, r: u8, g: u8, b: u8) -> zattr {
    let cleared = attrs & !TXT_ATTR_BG_MASK;
    let rgb = ((r as zattr) << 16) | ((g as zattr) << 8) | (b as zattr);
    cleared | TXTBGCOLOUR | TXT_ATTR_BG_24BIT | (rgb << TXT_ATTR_BG_COL_SHIFT)
}

/// Expand a prompt string
pub fn expand_prompt(s: &str) -> String {
    prompt_tls::sync_from_globals();
    buf_vars::new(s).expand() // c:Src/prompt.c:214 (new_vars init)
}

/// Same as [`expand_prompt`] — C call sites that used implicit globals only.
pub fn expand_prompt_default(s: &str) -> String {
    expand_prompt(s)
}

/// Count the visible width of an expanded prompt (ignoring escape sequences)
pub fn prompt_width(s: &str) -> usize {
    let mut width = 0;
    let mut in_escape = false;
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        match c {
            '\x01' => in_escape = true,  // RL_PROMPT_START_IGNORE
            '\x02' => in_escape = false, // RL_PROMPT_END_IGNORE
            '\x1b' => {
                // ANSI escape - skip until 'm' or end
                while let Some(&next) = chars.peek() {
                    chars.next();
                    if next == 'm' {
                        break;
                    }
                }
            }
            _ if !in_escape => {
                width += unicode_width::UnicodeWidthChar::width(c).unwrap_or(1);
            }
            _ => {}
        }
    }

    width
}

/// Output true color (24-bit) escape sequence
pub fn output_truecolor(r: u8, g: u8, b: u8, is_fg: bool) -> String {
    let mode = if is_fg { 38 } else { 48 };
    format!("\x1b[{};2;{};{};{}m", mode, r, g, b)
}

/// Maximum cmdstack depth, mirroring C zsh's `CMDSTACKSZ`.
/// Used to bound `cmdpush`/`cmdpop` so the stack can't grow
/// unbounded under runaway recursion.
// the command stack for use with %_ in prompts                             // c:53
const CMDSTACKSZ: usize = 256;

// Port of file-static `cmdstack` from `Src/init.c` (declared as
// `extern unsigned char cmdstack[CMDSTACKSZ]` in `Src/zsh.h:2658`).
// Stack of parser-context tokens (`CS_*`) the parser pushes as it
// descends into nested compound commands (`if`/`for`/`while`/`{}`
// etc.). Read by the prompt expander for `%_` and `%^` to render
// which constructs are currently open.
//
// Bucket-1 per PORT_PLAN.md — file-static in C, per-evaluator in
// zshrs. Each worker thread parses independently; sharing the
// stack across threads would corrupt nesting state. `RefCell`
// for interior mutability since the contents are owned `Vec<u8>`.
// the command stack for use with %_ in prompts                             // c:53
thread_local! {
    static CMDSTACK: std::cell::RefCell<Vec<u8>> = const {                  // c:56
        std::cell::RefCell::new(Vec::new())
    };
}

/// Apply text attributes as a single ANSI SGR escape.
// functions for handling attributes                                        // c:1641
/// Port of `applytextattributes(int flags)` from Src/prompt.c:1645 —
/// builds one SGR sequence with all active codes joined.
pub fn apply_text_attributes(attrs: zattr) -> String {                   // c:1645
    let mut codes: Vec<String> = Vec::new();
    if attrs & TXTBOLDFACE != 0 { codes.push("1".to_string()); } // c:1645
    if attrs & TXTUNDERLINE != 0 { codes.push("4".to_string()); } // c:1645
    if attrs & TXTSTANDOUT != 0 { codes.push("7".to_string()); } // c:1645
    if attrs & TXTFGCOLOUR != 0 { // c:1645
        let raw = (attrs & TXT_ATTR_FG_COL_MASK) >> TXT_ATTR_FG_COL_SHIFT;
        let c = if attrs & TXT_ATTR_FG_24BIT != 0 {
            // 24-bit FG — re-pack raw RGB into a `Color` and emit.
            COLOR_24BIT | (raw as Color & 0x00ff_ffff)
        } else {
            raw as Color
        };
        codes.push(color_to_ansi(c, true).trim_start_matches("\x1b[")
            .trim_end_matches('m').to_string());
    }
    if attrs & TXTBGCOLOUR != 0 { // c:1645
        let raw = (attrs & TXT_ATTR_BG_COL_MASK) >> TXT_ATTR_BG_COL_SHIFT;
        let c = if attrs & TXT_ATTR_BG_24BIT != 0 {
            COLOR_24BIT | (raw as Color & 0x00ff_ffff)
        } else {
            raw as Color
        };
        codes.push(color_to_ansi(c, false).trim_start_matches("\x1b[")
            .trim_end_matches('m').to_string());
    }
    if codes.is_empty() {
        String::new()
    } else {
        format!("\x1b[{}m", codes.join(";"))
    }
}

/// Reset all text attributes
pub fn reset_text_attributes() -> &'static str {
    "\x1b[0m"
}

/// Right prompt handling - compute padding for RPROMPT
pub fn right_prompt_padding(
    left_width: usize,
    right_prompt: &str,
    term_width: usize,
    indent: usize,
) -> Option<String> {
    let right_width = prompt_width(right_prompt);
    let total = left_width + right_width + indent;
    if total >= term_width {
        return None; // No room for right prompt
    }
    let padding = term_width - total;
    Some(" ".repeat(padding))
}

/// Transient prompt - return empty string to clear prompt on accept-line
pub fn transient_prompt(_original: &str) -> String {
    String::new()
}

fn color_name(c: Color) -> String {
    if let Some((r, g, b)) = color_get_rgb(c) {
        return format!("#{:02x}{:02x}{:02x}", r, g, b);
    }
    let idx = (c & 0xff) as usize;
    if idx < COLOUR_NAMES.len() {
        return COLOUR_NAMES[idx].to_string();
    }
    idx.to_string()
}

// ===========================================================
// Methods moved verbatim from src/ported/exec.rs because their
// C counterpart's source file maps 1:1 to this Rust module.
// Phase: prompt
// ===========================================================

// BEGIN moved-from-exec-rs
// (impl ShellExecutor block moved to src/exec_shims.rs — see file marker)

// END moved-from-exec-rs

// ===========================================================
// Methods moved verbatim from src/ported/exec.rs because their
// C counterpart's source file maps 1:1 to this Rust module.
// Phase: drift
// ===========================================================

// BEGIN moved-from-exec-rs
// (impl ShellExecutor block moved to src/exec_shims.rs — see file marker)

// END moved-from-exec-rs

/// Singleton holding the txtcurrentattrs / txtpendingattrs C
/// globals (Src/prompt.c file-statics, around line 1640). Used
/// by [`applytextattributes`] to compute the SGR diff between
/// the last-flushed and the pending attribute state.
fn current_attrs_lock() -> &'static std::sync::Mutex<zattr> {
    static CUR: std::sync::OnceLock<std::sync::Mutex<zattr>> = std::sync::OnceLock::new();
    CUR.get_or_init(|| std::sync::Mutex::new(0 as zattr))
}

fn pending_attrs_lock() -> &'static std::sync::Mutex<zattr> {
    static PND: std::sync::OnceLock<std::sync::Mutex<zattr>> = std::sync::OnceLock::new();
    PND.get_or_init(|| std::sync::Mutex::new(0 as zattr))
}

/// Set the pending text-attributes that the next
/// [`applytextattributes`] call will diff against the current
/// state. Mirrors callers writing to C's `txtpendingattrs`.
pub fn set_pending_text_attrs(attrs: zattr) {
    *pending_attrs_lock()
        .lock()
        .expect("pending_attrs poisoned") = attrs;
}

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

    /// c:1935-1944 — `truecolor_terminal` returns true iff
    /// `.term.extensions` array contains an un-negated `truecolor`
    /// entry. The previous Rust port did COLORTERM/TERM heuristics
    /// (an entirely different decision rule). Regression target:
    /// a session with `.term.extensions=(truecolor)` MUST report
    /// truecolor; a session with `.term.extensions=(-truecolor)` MUST
    /// report disabled regardless of COLORTERM/TERM env.
    #[test]
    fn truecolor_terminal_routes_through_term_extensions_array() {
        let saved = crate::ported::params::getaparam(".term.extensions");

        // Empty / unset → false (c:1944).
        let _ = crate::ported::params::setaparam(
            ".term.extensions", vec![]);
        assert!(!super::truecolor_terminal(),
                "empty .term.extensions must report off");

        // truecolor present → true (c:1940-1942 with result=1).
        let _ = crate::ported::params::setaparam(
            ".term.extensions", vec!["truecolor".to_string()]);
        assert!(super::truecolor_terminal(),
                ".term.extensions=(truecolor) must report on");

        // -truecolor → explicitly disabled (c:1940 with result=0).
        let _ = crate::ported::params::setaparam(
            ".term.extensions", vec!["-truecolor".to_string()]);
        assert!(!super::truecolor_terminal(),
                ".term.extensions=(-truecolor) must report off");

        // Restore.
        let _ = crate::ported::params::setaparam(
            ".term.extensions", saved.unwrap_or_default());
    }

    /// c:134 — when `home` is a prefix of `path` AND tilde=true,
    /// promptpath MUST substitute. Catches a regression where the
    /// prefix-match falls back to the unchanged absolute path silently.
    #[test]
    fn promptpath_substitutes_home_prefix_with_tilde() {
        let r = promptpath("/home/user/project", 0, true, "/home/user");
        assert!(r.starts_with('~'), "home-prefix must collapse to ~ (got {r:?})");
    }

    /// c:134 — npath>0 truncates from the right, keeping the last N
    /// path components. Used by `%c` / `%~` for theme depth-limits;
    /// regressions silently render full paths in cramped prompts.
    #[test]
    fn promptpath_npath_one_keeps_only_last_component() {
        let r = promptpath("/a/b/c/d", 1, false, "");
        assert!(!r.contains("a/b") && r.ends_with("d"), "got {r:?}");
    }

    /// c:285 — `parsehighlight("bold")` MUST set the TXTBOLDFACE bit.
    /// Regression that drops the bit would silently mis-render every
    /// bold escape in user's `zle_highlight=(...)` array.
    #[test]
    fn parsehighlight_bold_sets_bold_bit() {
        assert_ne!(parsehighlight("bold") & TXTBOLDFACE, 0);
    }

    /// `match_named_colour` MUST resolve all 8 ANSI base names plus
    /// "default" — the user-facing color identifiers in `zle_highlight`
    /// + `bindkey -A`. Skipping any name breaks the by-name color path
    /// users rely on every keystroke.
    #[test]
    fn match_named_colour_covers_full_ansi_palette_and_default() {
        for &name in &["black", "red", "green", "yellow",
                       "blue", "magenta", "cyan", "white", "default"] {
            assert!(match_named_colour(name).is_some(), "{name:?} must resolve");
        }
    }

    /// Unknown colour names MUST return None — silent fallback would
    /// mask theme typos that users would otherwise see immediately.
    #[test]
    fn match_named_colour_returns_none_for_unknown() {
        assert!(match_named_colour("definitely_not_a_color_zshrs").is_none());
    }

    /// Pin: `countprompt` recognises `Inpar` (0x88) / `Outpar` (0x8a)
    /// / `Nularg` (0xa1) as the THREE special tokens per
    /// `Src/prompt.c:1179-1185`. The previous Rust port used
    /// '\x01' / '\x02' / '\x03' — the WRONG byte values.
    ///
    /// `Inpar..Outpar` regions are `%{...%}` non-printing escapes
    /// (zero visible width); `Nularg` is a glitch-space placeholder
    /// (1 visible column).
    #[test]
    fn countprompt_recognises_canonical_inpar_outpar_nularg_bytes() {
        use crate::ported::zsh_h::{Inpar, Outpar, Nularg};
        let mut w = 0i32;
        let mut h = 0i32;
        // `abc%{...%}def` shape: `abc` (3 cols), Inpar+escape+Outpar
        // (zero cols since non-printing), `def` (3 cols).
        let probe = format!("abc{}ESC{}def", Inpar, Outpar);
        countprompt(&probe, &mut w, &mut h, 0);
        assert_eq!(w, 6,
            "c:1179-1182 — Inpar..Outpar region must be zero-width; \
             got w={w} for 3+0+3-col prompt");

        // Nularg alone is 1 visible column.
        let mut w = 0i32;
        let mut h = 0i32;
        let probe = format!("{}", Nularg);
        countprompt(&probe, &mut w, &mut h, 0);
        assert_eq!(w, 1,
            "c:1183-1184 — Nularg counts as 1 visible column; got w={w}");
    }

    /// c:134 — `promptpath` with `tilde=false` MUST NOT substitute ~
    /// even when `home` is a prefix. Pin the inverse branch so a
    /// regen that hardcodes tilde-substitution silently breaks
    /// `%/` literal-path renders.
    #[test]
    fn promptpath_without_tilde_keeps_absolute_path() {
        let r = promptpath("/home/user/project", 0, /*tilde=*/false, "/home/user");
        assert!(r.starts_with("/home/user"),
            "tilde=false must NOT collapse to ~; got {r:?}");
        assert!(!r.starts_with('~'),
            "tilde=false output must not start with ~");
    }

    /// c:134 — Path equal to home (no remainder). `tilde=true` →
    /// just `~`. Edge case the prefix-collapse logic must handle.
    #[test]
    fn promptpath_path_exactly_home_renders_as_tilde_only() {
        let r = promptpath("/home/user", 0, true, "/home/user");
        assert_eq!(r, "~",
            "path == home must render as plain '~'; got {r:?}");
    }

    /// c:134 — Home not a prefix of path: leave path unchanged
    /// regardless of tilde flag.
    #[test]
    fn promptpath_unrelated_path_unchanged() {
        let r = promptpath("/etc/zshrc", 0, true, "/home/user");
        assert_eq!(r, "/etc/zshrc",
            "non-home path must pass through unchanged");
    }

    /// c:134 — npath=0 means "no truncation": the full path renders.
    #[test]
    fn promptpath_npath_zero_means_no_truncation() {
        let r = promptpath("/a/b/c/d/e", 0, false, "");
        assert_eq!(r, "/a/b/c/d/e", "npath=0 must keep full path");
    }

    /// c:134 — npath=2 keeps the LAST two components only. Pin
    /// the off-by-one because the C source does `for (i = npath; i > 0; --i)`
    /// — a regen that does `>= 0` would keep one extra.
    #[test]
    fn promptpath_npath_two_keeps_last_two_components() {
        let r = promptpath("/a/b/c/d", 2, false, "");
        assert!(r.contains("c") && r.contains("d"),
            "npath=2 must include last 2 components; got {r:?}");
        assert!(!r.contains("/a/"),
            "npath=2 must NOT include first 2 components");
    }

    /// c:285 — `parsehighlight` for `none` returns 0 (no attrs set).
    /// Pin the keyword that explicitly clears all attribute bits.
    #[test]
    fn parsehighlight_none_returns_zero() {
        let r = parsehighlight("none");
        assert_eq!(r, 0, "'none' must yield zero attrs; got {:#x}", r);
    }

    /// c:285 — `parsehighlight("underline")` sets the UNDERLINE bit.
    /// Test the other attribute keywords separately from `bold`.
    #[test]
    fn parsehighlight_underline_sets_underline_bit() {
        let r = parsehighlight("underline");
        assert_ne!(r, 0, "underline must set at least one bit");
    }

    /// c:285 — Unknown highlight keyword returns 0 (silent ignore).
    /// Pin the failure mode because zle_highlight users add custom
    /// keywords; the C source skips unknowns rather than erroring.
    #[test]
    fn parsehighlight_unknown_keyword_returns_zero() {
        let r = parsehighlight("definitely_not_a_real_attr");
        assert_eq!(r, 0, "unknown attr must be silently ignored");
    }

    /// c:1915 — `match_named_colour` is case-sensitive: "RED" must
    /// NOT match "red". Pin lower-case enforcement; a regen that
    /// adds `.to_lowercase()` would silently accept uppercase color
    /// names that the C source rejects.
    #[test]
    fn match_named_colour_is_case_sensitive() {
        assert!(match_named_colour("red").is_some());
        assert!(match_named_colour("RED").is_none(),
            "uppercase color must NOT resolve per C source's strcmp");
        assert!(match_named_colour("Red").is_none());
    }

    /// c:1915 — Empty string returns None. Defensive boundary.
    #[test]
    fn match_named_colour_empty_returns_none() {
        assert!(match_named_colour("").is_none());
    }

    /// c:1276 — `cmdpush`/`cmdpop` round-trip. Pin the LIFO balance.
    #[test]
    fn cmdpush_cmdpop_round_trip_does_not_panic() {
        // Just verifies safe push/pop balance for several tokens.
        cmdpush(0);
        cmdpush(1);
        cmdpush(2);
        cmdpop();
        cmdpop();
        cmdpop();
        // Extra pops must be safe (no underflow panic)
        cmdpop();
    }

    /// c:976 — `pputc` appends a single ASCII char to the buffer.
    /// Pin the no-buffering / immediate-append contract.
    #[test]
    fn pputc_appends_char_to_buffer() {
        let mut buf = String::new();
        pputc(&mut buf, 'X');
        assert_eq!(buf, "X");
        pputc(&mut buf, 'Y');
        assert_eq!(buf, "XY");
    }

    /// c:1016 — `stradd` appends a string slice to the buffer.
    #[test]
    fn stradd_appends_string_to_buffer() {
        let mut buf = String::from("pre/");
        stradd(&mut buf, "post");
        assert_eq!(buf, "pre/post");
        stradd(&mut buf, "");
        assert_eq!(buf, "pre/post", "empty append leaves buffer unchanged");
    }
}