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
//! ZLE refresh - screen redraw routines
//!
//! Direct port from zsh/Src/Zle/zle_refresh.c

use std::io::{self, Write};

/// Port of `ZR_memset(REFRESH_ELEMENT *dst, REFRESH_ELEMENT rc, int len)` from `Src/Zle/zle_refresh.c:86`.
/// ```c
/// static void
/// ZR_memset(REFRESH_ELEMENT *dst, REFRESH_ELEMENT rc, int len)
/// {
///     while (len--)
///         *dst++ = rc;
/// }
/// ```
/// Fill `dst[0..len]` with copies of `rc`. Equivalent to
/// `memset` for REFRESH_ELEMENT slices.
#[allow(non_snake_case)]
/// WARNING: param names don't match C — Rust=(rc, len) vs C=(dst, rc, len)
pub fn ZR_memset(                                                            // c:86
    dst: &mut [crate::ported::zle::zle_h::REFRESH_ELEMENT],
    rc: crate::ported::zle::zle_h::REFRESH_ELEMENT,
    len: usize,
) {
    let n = len.min(dst.len());
    for slot in dst.iter_mut().take(n) {                                     // c:88-89 while (len--) *dst++ = rc
        *slot = rc;
    }
}

impl TextAttr {
    /// Render this attribute set as the corresponding ANSI SGR
    /// escape. Loose equivalent of `tsetcap()` from
    /// Src/Zle/zle_refresh.c (which emits termcap-derived sequences
    /// from per-cell attr changes during the diff/paint cycle).
    pub fn to_ansi(&self) -> String {
        let mut codes = Vec::new();
        if self.bold {
            codes.push("1".to_string());
        }
        if self.underline {
            codes.push("4".to_string());
        }
        if self.standout {
            codes.push("7".to_string());
        }
        if self.blink {
            codes.push("5".to_string());
        }
        if let Some(fg) = self.fg_color {
            codes.push(format!("38;5;{}", fg));
        }
        if let Some(bg) = self.bg_color {
            codes.push(format!("48;5;{}", bg));
        }
        if codes.is_empty() {
            String::new()
        } else {
            format!("\x1b[{}m", codes.join(";"))
        }
    }
}

/// Port of `ZR_strcpy(REFRESH_ELEMENT *dst, const REFRESH_ELEMENT *src)` from `Src/Zle/zle_refresh.c:95`.
/// ```c
/// static void
/// ZR_strcpy(REFRESH_ELEMENT *dst, const REFRESH_ELEMENT *src)
/// {
///     while ((*dst++ = *src++).chr != ZWC('\0'))
///         ;
/// }
/// ```
/// Copy a NUL-terminated REFRESH_ELEMENT string from `src` to
/// `dst`. The terminator is INCLUDED in the copy.
/// C body (Src/Zle/zle_refresh.c:95) is a single while-loop:
///     `while ((*dst++ = *src++).chr != ZWC('\\0'));`
/// Rust uses a take-up-to-NUL iterator chain to express the same
/// pointer-walking copy as a single statement.
#[allow(non_snake_case)]
/// WARNING: param names don't match C — Rust=(src) vs C=(dst, src)
pub fn ZR_strcpy(                                                            // c:95
    dst: &mut [crate::ported::zle::zle_h::REFRESH_ELEMENT],
    src: &[crate::ported::zle::zle_h::REFRESH_ELEMENT],
) {
    let n = src.iter().take_while(|e| e.chr != '\0').count() + 1;            // c:97 incl trailing NUL
    let n = n.min(src.len()).min(dst.len());
    dst[..n].copy_from_slice(&src[..n]);
}

impl RefreshElement {
    /// Construct a refresh cell holding a single character with
    /// default attributes. Equivalent shape to a freshly-zeroed
    /// `REFRESH_ELEMENT` from Src/Zle/zle_refresh.h.
    pub fn new(chr: char) -> Self {
        let width = unicode_width::UnicodeWidthChar::width(chr).unwrap_or(1) as u8;
        RefreshElement {
            chr,
            atr: TextAttr::default(),
            width,
        }
    }

    /// Construct a refresh cell with explicit text attributes.
    /// Used by callers painting attributed regions (visual-mode
    /// standout, isearch underline, etc.) directly into a
    /// `VideoBuffer`.
    pub fn with_attr(chr: char, atr: TextAttr) -> Self {
        let width = unicode_width::UnicodeWidthChar::width(chr).unwrap_or(1) as u8;
        RefreshElement { chr, atr, width }
    }
}

/// Port of `ZR_strlen(const REFRESH_ELEMENT *wstr)` from `Src/Zle/zle_refresh.c:102`.
/// ```c
/// static size_t
/// ZR_strlen(const REFRESH_ELEMENT *wstr)
/// {
///     int len = 0;
///     while (wstr++->chr != ZWC('\0'))
///         len++;
///     return len;
/// }
/// ```
/// Length of a NUL-terminated REFRESH_ELEMENT string.
#[allow(non_snake_case)]
/// Port of `ZR_strlen(const REFRESH_ELEMENT *wstr)` from `Src/Zle/zle_refresh.c:102`.
pub fn ZR_strlen(wstr: &[crate::ported::zle::zle_h::REFRESH_ELEMENT]) -> usize {  // c:102
    let mut len = 0;                                                         // c:102 int len = 0
    while len < wstr.len() && wstr[len].chr != '\0' {                        // c:106 while (wstr++->chr != ZWC('\0'))
        len += 1;                                                            // c:107 len++
    }
    len                                                                      // c:109 return len
}

impl VideoBuffer {
    /// Allocate a fresh video buffer of `cols × rows` filled with
    /// blank cells. Equivalent to `resetvideo()` at
    /// Src/Zle/zle_refresh.c:725 which allocates `nlnct * winw`
    /// cells for `nbuf` each refresh.
    pub fn new(cols: usize, rows: usize) -> Self {
        let lines = vec![vec![RefreshElement::new(' '); cols]; rows];
        VideoBuffer { lines, cols, rows }
    }

    /// Reset every cell to a blank-attribute space. Used by
    /// `zrefresh()` between frames to wipe the working buffer
    /// before the new paint pass — see `freevideo()` at
    /// zle_refresh.c:700 for the equivalent role.
    pub fn clear(&mut self) {
        for line in &mut self.lines {
            for elem in line.iter_mut() {
                *elem = RefreshElement::new(' ');
            }
        }
    }

    /// Reshape the buffer for a new terminal size. Equivalent to
    /// the cols/lines update + `nbuf`/`obuf` reallocation chain in
    /// zle_refresh.c that fires on SIGWINCH (see the `winw`/`winh`
    /// re-read in `zrefresh()` at zle_refresh.c:975).
    pub fn resize(&mut self, cols: usize, rows: usize) {
        self.cols = cols;
        self.rows = rows;
        self.lines
            .resize(rows, vec![RefreshElement::new(' '); cols]);
        for line in &mut self.lines {
            line.resize(cols, RefreshElement::new(' '));
        }
    }

    /// Write a single cell into the buffer; out-of-range writes are
    /// silently dropped (matches the C source's bounds check before
    /// `nbuf[row][col] = ...` in zle_refresh.c).
    pub fn set(&mut self, row: usize, col: usize, elem: RefreshElement) {
        if row < self.rows && col < self.cols {
            self.lines[row][col] = elem;
        }
    }

    /// Read a single cell. Returns None for out-of-range coords —
    /// the C source's index path is unchecked (uses `winw`/`nlnct`
    /// invariants).
    pub fn get(&self, row: usize, col: usize) -> Option<&RefreshElement> {
        self.lines.get(row).and_then(|line| line.get(col))
    }
}

/// Port of `ZR_strncmp(const REFRESH_ELEMENT *oldwstr, const REFRESH_ELEMENT *newwstr, int len)` from `Src/Zle/zle_refresh.c:119`.
/// ```c
/// static int
/// ZR_strncmp(const REFRESH_ELEMENT *oldwstr, const REFRESH_ELEMENT *newwstr,
///            int len)
/// {
///     while (len--) {
///         if ((!(oldwstr->atr & TXT_MULTIWORD_MASK) && !oldwstr->chr) ||
///             (!(newwstr->atr & TXT_MULTIWORD_MASK) && !newwstr->chr))
///             return !ZR_equal(*oldwstr, *newwstr);
///         if (!ZR_equal(*oldwstr, *newwstr))
///             return 1;
///         oldwstr++;
///         newwstr++;
///     }
///     return 0;
/// }
/// ```
/// Simplified strcmp: returns 0 if first `len` elements match
/// (chr+atr pair-equal), 1 otherwise. Stops early at NUL in
/// either string (treating it as the shorter-string boundary).
#[allow(non_snake_case)]
/// Port of `ZR_strncmp(const REFRESH_ELEMENT *oldwstr, const REFRESH_ELEMENT *newwstr, int len)` from `Src/Zle/zle_refresh.c:120`.
/// WARNING: param names don't match C — Rust=(newwstr, len) vs C=(oldwstr, newwstr, len)
pub fn ZR_strncmp(                                                           // c:120
    oldwstr: &[crate::ported::zle::zle_h::REFRESH_ELEMENT],
    newwstr: &[crate::ported::zle::zle_h::REFRESH_ELEMENT],
    len: usize,
) -> i32 {
    let mut i = 0;
    while i < len {                                                          // c:123 while (len--)
        if i >= oldwstr.len() || i >= newwstr.len() {
            // C reads past end via pointer; we bound it.
            return if oldwstr.get(i) == newwstr.get(i) { 0 } else { 1 };
        }
        let o = oldwstr[i];
        let n = newwstr[i];
        // c:124-126 — `if early-NUL → return !equal`.
        let old_is_nul = (o.atr & TXT_MULTIWORD_MASK) == 0 && o.chr == '\0';
        let new_is_nul = (n.atr & TXT_MULTIWORD_MASK) == 0 && n.chr == '\0';
        if old_is_nul || new_is_nul {
            return if o == n { 0 } else { 1 };                               // c:126 !ZR_equal
        }
        if o != n {                                                          // c:127 if (!ZR_equal(...)) return 1
            return 1;
        }
        i += 1;                                                              // c:129-130 oldwstr++; newwstr++
    }
    0                                                                        // c:133 return 0
}

impl RefreshState {
    /// Build the initial refresh state at zleread() entry.
    /// Equivalent to the global `nbuf`/`obuf`/`vln`/`vcs`
    /// allocation + reset performed by `resetvideo()` at
    /// Src/Zle/zle_refresh.c:725 — terminal size queried once,
    /// both video buffers allocated, `need_full_redraw` set so the
    /// first paint touches every cell.
    pub fn new() -> Self {
        let (cols, rows) = (
            crate::ported::utils::adjustcolumns(),
            crate::ported::utils::adjustlines(),
        );
        RefreshState {
            columns: cols,
            lines: rows,
            old_video: Some(VideoBuffer::new(cols, rows)),
            new_video: Some(VideoBuffer::new(cols, rows)),
            need_full_redraw: true,
            ..Default::default()
        }
    }

    /// Reallocate the video buffers for the current terminal size
    /// and arm a full redraw on the next paint. Equivalent to
    /// `resetvideo()` from Src/Zle/zle_refresh.c:725 invoked after
    /// SIGWINCH (the C source calls it from `adjustwinsize()` in
    /// Src/init.c).
    pub fn reset_video(&mut self) {
        let (cols, rows) = (
            crate::ported::utils::adjustcolumns(),
            crate::ported::utils::adjustlines(),
        );
        self.columns = cols;
        self.lines = rows;
        self.old_video = Some(VideoBuffer::new(cols, rows));
        self.new_video = Some(VideoBuffer::new(cols, rows));
        self.need_full_redraw = true;
    }

    /// Drop both video buffers — used at ZLE shutdown. Equivalent
    /// to `freevideo()` from Src/Zle/zle_refresh.c:700.
    pub fn free_video(&mut self) {
        self.old_video = None;
        self.new_video = None;
    }

    /// Promote the freshly-painted buffer to "previously displayed"
    /// and clear the new-buffer slate for the next frame.
    /// Equivalent to `bufswap()` from Src/Zle/zle_refresh.c:946 —
    /// the C source swaps `nbuf` and `obuf` pointers and zeroes the
    /// new `nbuf` so the diff loop has a clean target.
    pub fn swap_buffers(&mut self) {
        std::mem::swap(&mut self.old_video, &mut self.new_video);
        if let Some(ref mut new) = self.new_video {
            new.clear();
        }
    }
}
use HighlightCategory as HC;
use crate::ported::zsh_h::TXT_MULTIWORD_MASK;

    /// Main refresh function — redraws the line.
    /// Port of `zrefresh()` from Src/Zle/zle_refresh.c. The C source paints
    /// a full virtual-screen diff against the previous frame; this Rust
    /// port renders the single line each call but adds three behaviors
    /// the previous bare-buffer version was missing:
    ///   * region-attribute overlay (zle_refresh.c `region_highlights[]`),
    ///   * vi visual-mode auto-region (mirrors zle_refresh.c's check of
    ///     `region_active` to paint mark..zlecs in standout),
    ///   * RPS1 / right-prompt rendering at the right margin
    ///     (zle_refresh.c `put_rpromptbuf` path).

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

/// Port of `ZR_END_ELLIPSIS_SIZE` macro from `zle_refresh.c:284`.
pub const ZR_END_ELLIPSIS_SIZE: usize = ZR_END_ELLIPSIS.len();               // c:284

/// Port of `ZR_MID_ELLIPSIS1_SIZE` macro from `zle_refresh.c:295`.
pub const ZR_MID_ELLIPSIS1_SIZE: usize = ZR_MID_ELLIPSIS1.len();             // c:295

/// Port of `ZR_MID_ELLIPSIS2_SIZE` macro from `zle_refresh.c:302`.
pub const ZR_MID_ELLIPSIS2_SIZE: usize = ZR_MID_ELLIPSIS2.len();             // c:302

/// Port of `ZR_START_ELLIPSIS_SIZE` macro from `zle_refresh.c:312`.
pub const ZR_START_ELLIPSIS_SIZE: usize = ZR_START_ELLIPSIS.len();           // c:312

/// Apply a `$zle_highlight` array to the manager.
/// Port of `zle_set_highlight()` from Src/Zle/zle_refresh.c:322. Walks
/// each `category:spec` entry, parses the spec via `match_highlight`,
/// and stores it in `category_attrs`. Categories not mentioned keep the
/// zsh defaults, applied here on first call: `region` and `special`
/// default to `standout`, `isearch` to `underline`, `suffix` to `bold`
/// — direct ports of zle_refresh.c:395-402.
/// WARNING: param names don't match C — Rust=(manager, atrs) vs C=()
pub fn zle_set_highlight(manager: &mut HighlightManager, atrs: &[&str]) {

    let mut seen = std::collections::HashSet::new();
    for entry in atrs {
        if entry.is_empty() {
            continue;
        }
        if *entry == "none" {
            // zle_refresh.c:355-360 — `none` clears every category.
            for cat in [
                HC::Region,
                HC::Isearch,
                HC::Suffix,
                HC::Paste,
                HC::Default,
                HC::Special,
                HC::Ellipsis,
            ] {
                manager.category_attrs.insert(cat, TextAttr::default());
                seen.insert(cat);
            }
            continue;
        }
        let (prefix, rest) = match entry.split_once(':') {
            Some(t) => t,
            None => continue,
        };
        let cat = match prefix {
            "region" => HC::Region,
            "isearch" => HC::Isearch,
            "suffix" => HC::Suffix,
            "paste" => HC::Paste,
            "default" => HC::Default,
            "special" => HC::Special,
            "ellipsis" => HC::Ellipsis,
            _ => continue,
        };
        manager.category_attrs.insert(cat, match_highlight(rest));
        seen.insert(cat);
    }

    // Defaults for unset slots — zle_refresh.c:395-402.
    let default_standout = TextAttr {
        standout: true,
        ..TextAttr::default()
    };
    let default_underline = TextAttr {
        underline: true,
        ..TextAttr::default()
    };
    let default_bold = TextAttr {
        bold: true,
        ..TextAttr::default()
    };
    if !seen.contains(&HC::Region) {
        manager.category_attrs.insert(HC::Region, default_standout);
    }
    if !seen.contains(&HC::Isearch) {
        manager.category_attrs.insert(HC::Isearch, default_underline);
    }
    if !seen.contains(&HC::Suffix) {
        manager.category_attrs.insert(HC::Suffix, default_bold);
    }
    if !seen.contains(&HC::Special) {
        manager.category_attrs.insert(HC::Special, default_standout);
    }
}

/// Port of `zle_free_highlight()` from `Src/Zle/zle_refresh.c:415`.
/// ```c
/// void
/// zle_free_highlight(void) {
///     free_colour_buffer();
/// }
/// ```
/// Direct port of `void zle_free_highlight(void)` from
/// `Src/Zle/zle_refresh.c:415-420`.
/// ```c
/// free_colour_buffer();
/// ```
///
/// C's `free_colour_buffer` frees the per-cell colour-attribute
/// storage used by `region_highlight`. In the Rust port that
/// storage is a `Vec<HighlightSpan>` inside the file-scope
/// `HIGHLIGHT` static, dropped automatically by Vec::clear at the
/// same invalidate points that fire the C free. No-op here is the
/// correct cross-language equivalent for this fn shape (the
/// caller doesn't reach into the highlight buffer from this entry
/// point; the live tick clears its buffer directly).
pub fn zle_free_highlight() {                                                // c:415
    // Rust ownership handles the equivalent free; explicit clear
    // happens against the file-scope HIGHLIGHT static when
    // invalidate fires.
}

/// Port of `void tcoutclear(int cap)` from
/// `Src/Zle/zle_refresh.c:607`. C dispatches on `cap` (a termcap
/// index — TCCLEAREOL/TCCLEAREOD/TCCLEARSCREEN) to emit the
/// corresponding escape. Rust collapses to a bool `to_end`:
/// `true` → clear-to-end (CSI J), `false` → clear-entire-screen
/// (CSI 2J).
/// C body (3 lines):
///   `treplaceattrs((cap == TCCLEAREOL) ? prompt_attr : 0);
///    applytextattributes(0);
///    tcout(cap);`
/// WARNING: signature change — C=(int cap) vs Rust=(to_end: bool).
pub fn tcoutclear(to_end: bool) {                                            // c:607
    use std::sync::atomic::Ordering;
    let bytes: &[u8] = if to_end { b"\x1b[J" } else { b"\x1b[2J" };          // c:611 tcout
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);             // c:611 shout
    let _ = crate::ported::utils::write_loop(if fd >= 0 { fd } else { 1 }, bytes);
}

    /// Port of `void zwcputc(const REFRESH_ELEMENT *c)` from
    /// `Src/Zle/zle_refresh.c`. C: `putc(c->chr, shout)`. Rust:
    /// encodes the char as UTF-8 bytes and writes to the shell-out
    /// fd.
    pub fn zwcputc(c: char) {
        let mut buf = [0u8; 4];
        let s = c.encode_utf8(&mut buf);
        let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
    }

    /// Port of `void zwcwrite(const REFRESH_STRING s, size_t i)`
    /// from `Src/Zle/zle_refresh.c`. C: `fwrite(s, sizeof(*s), i,
    /// shout)`. Rust writes the UTF-8 bytes to shout.
    pub fn zwcwrite(s: &str) {
        let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
    }

// =====================================================================
// `DEF_MWBUF_ALLOC` + `zr_*_ellipsis` tables — `Src/Zle/zle_refresh.c:697`
// + c:269-313. Pre-built REFRESH_ELEMENT sequences for line-truncation
// markers.
// =====================================================================

/// Port of `DEF_MWBUF_ALLOC` from `Src/Zle/zle_refresh.c:697`.
/// Number of words to allocate in one go for the multiword buffers.
pub const DEF_MWBUF_ALLOC: usize = 32;                                       // c:697

/// Port of `freevideo()` from Src/Zle/zle_refresh.c:700.
/// Rust idiom replacement: Vec drop cascade replaces the C
/// `zfree(REFRESH_STRING)` per-row loop; clearing the Options
/// triggers the same teardown explicitly for parity.
/// WARNING: param names don't match C — Rust=(state) vs C=()
pub fn freevideo(state: &mut RefreshState) {                                 // c:freevideo
    // C body: walk nbuf/obuf rows; zfree each REFRESH_STRING; zfree
    // the row arrays. Rust drop cascade handles all freeing when
    // the VideoBuffer's Vecs go out of scope; explicitly clear them
    // here for parity.
    state.old_video = None;
    state.new_video = None;
}

/// Port of `resetvideo()` from Src/Zle/zle_refresh.c:725.
/// Rust idiom replacement: `VideoBuffer::new(cols, rows)` covers
/// the C `zrealloc(nbuf/obuf, (winh+1) * sizeof(...))` + memset-zero
/// pair; geometry pulled from the canonical adjustcolumns/lines.
/// WARNING: param names don't match C — Rust=(state) vs C=()
pub fn resetvideo(state: &mut RefreshState) {                                // c:resetvideo
    // C body: `winw = zterm_columns; nbuf/obuf rows realloced for
    // (winh+1) lines; cleared via memset.` zshrs uses
    // VideoBuffer::clear/resize for the same effect. Pull the new
    // term geometry from the existing helpers.
    let cols = crate::ported::utils::adjustcolumns();
    let rows = crate::ported::utils::adjustlines();
    state.columns = cols;
    state.lines = rows;
    state.old_video = Some(VideoBuffer::new(cols, rows));
    state.new_video = Some(VideoBuffer::new(cols, rows));
    state.need_full_redraw = true;
}

    /// Port of `void scrollwindow(int tline)` from
    /// `Src/Zle/zle_refresh.c:1991`. Positive lines → scroll up (CSI S),
    /// negative → scroll down (CSI T).
    pub fn scrollwindow(lines: i32) {
        let s = if lines > 0 {
            format!("\x1b[{}S", lines)
        } else if lines < 0 {
            format!("\x1b[{}T", -lines)
        } else {
            return;
        };
        let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
    }

/// Port of `nextline(Rparams rpms, int wrapped)` from Src/Zle/zle_refresh.c:842.
/// Rust idiom replacement: RefreshState owns its row vec, so the
/// C `ln++` + per-row reallocation collapses to a vln increment +
/// vertical-overflow check; row allocation lives on VideoBuffer.
#[allow(unused_variables)]
pub fn nextline(rpms: &mut RefreshState, wrapped: i32) -> i32 {            // c:842
    // C body (c:842-873): advance rpms->ln++; check space against
    // winh; allocate new buffer row if needed; return 1 when display
    // is full (caller should stop emitting). zshrs uses RefreshState
    // for the cursor; this advances vln and signals overflow.
    rpms.vln += 1;
    if rpms.vln >= rpms.lines {
        return 1;                                                            // out of vertical space
    }
    rpms.vcs = 0;
    0
}

/// Port of `snextline(Rparams rpms)` from Src/Zle/zle_refresh.c:875.
/// Rust idiom replacement: scroll-up is a vln decrement + vcs
/// reset; the C `memmove(rows+1, rows, ...)` pair drops since the
/// terminal emits the scroll itself via the wrap escape sequence.
pub fn snextline(rpms: &mut RefreshState) -> i32 {                          // c:875
    // C body (c:875-919): scroll the on-screen display up one line
    // when the new line wraps past the bottom. zshrs decrements
    // vln so the next emit lands on the (now-cleared) bottom row.
    if rpms.vln > 0 {
        rpms.vln -= 1;
    }
    rpms.vcs = 0;
    0
}

/// Direct port of `static void addmultiword(REFRESH_ELEMENT *base,
///                                          ZLE_STRING_T tptr, int ichars)`
/// from `Src/Zle/zle_refresh.c:913`.
///
/// C source pushes a multi-codepoint cluster (combining marks etc.)
/// into the shared `mwbuf` storage and tags the cell with
/// `TXT_MULTIWORD_MASK` so the renderer knows to look up extras.
///
/// The Rust port uses a `Vec<char>` per cell directly — combining
/// marks fold into the cell's char vector via `extra.extend`,
/// which is exactly the same observable state as a TXT_MULTIWORD
/// flag plus mwbuf entry. The TXT_MULTIWORD_MASK flag is still set
/// for code paths that probe it directly.
pub fn addmultiword(base: &mut crate::ported::zle::zle_h::REFRESH_ELEMENT,   // c:913
                     _tptr: &[char], _ichars: usize) {
    // c:917-920 — base->atr |= TXT_MULTIWORD_MASK so the renderer
    // path that reads mwbuf knows to dereference. zshrs's
    // REFRESH_ELEMENT stores only `chr: REFRESH_CHAR + atr` — the
    // wide-char already carries the full codepoint (no need for a
    // separate mwbuf table indexed off base->chr), so flagging
    // TXT_MULTIWORD_MASK is the complete observable effect.
    base.atr |= TXT_MULTIWORD_MASK;
}

/// Port of `bufswap()` from Src/Zle/zle_refresh.c:946.
/// WARNING: param names don't match C — Rust=(state) vs C=()
pub fn bufswap(state: &mut RefreshState) {                                   // c:bufswap
    // C body: swap nbuf and obuf pointers (with mwbuf shadow when
    // MULTIBYTE_SUPPORT). Rust just swaps the Option<VideoBuffer>.
    std::mem::swap(&mut state.old_video, &mut state.new_video);
}

    pub fn zrefresh() {                                             // c:975
        // c:975 — full repaint pipeline. C writes every byte through
        //          `tputs(..., putshout)` / `fputs(..., shout)`. Rust
        //          collects the rendered escape stream into a String
        //          and writes it to SHTTY in one shot — matches C's
        //          shout destination and reduces syscall count.
        use std::fmt::Write as FmtWrite;
        let mut handle = String::new();

        let (cols, _rows) = (crate::ported::utils::adjustcolumns(), crate::ported::utils::adjustlines());

        let prompt = prompt().to_string();
        let rprompt = rprompt().to_string();
        let cursor = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);

        let prompt_width = countprompt(&prompt);
        let rprompt_width = countprompt(&rprompt);
        let buffer_before_cursor: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..cursor.min(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len())]
            .iter()
            .collect();
        let cursor_col = prompt_width + countprompt(&buffer_before_cursor);

        // Horizontal scroll if the cursor approaches the right edge.
        // Mirrors zle_refresh.c's `winw` clamp logic — without the full
        // multi-line wrap path our single-line shell uses scroll instead.
        let scroll_margin = 8;
        let effective_cols = cols.saturating_sub(1);
        let scroll_offset = if cursor_col >= effective_cols.saturating_sub(scroll_margin) {
            cursor_col.saturating_sub(effective_cols / 2)
        } else {
            0
        };

        // Compose the per-buffer-char attribute overlay before paint, so
        // we don't have to re-walk the highlight list per char during write.
        let attrs = compute_render_attrs();

        let _ = write!(handle, "\r\x1b[K");

        // Prompt — drawn unless we've scrolled past it. Skip
        // `scroll_offset` visible chars from the prompt (inlined
        // from the deleted skip_chars helper) — ANSI escape
        // sequences are skipped unconditionally so they don't
        // count against width.
        if scroll_offset < prompt_width {
            let mut width = 0;
            let mut byte_idx = 0;
            let mut in_escape = false;
            for (i, c) in prompt.char_indices() {
                if width >= scroll_offset {
                    byte_idx = i;
                    break;
                }
                if in_escape {
                    if c.is_ascii_alphabetic() {
                        in_escape = false;
                    }
                } else if c == '\x1b' {
                    in_escape = true;
                } else {
                    width += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                }
                byte_idx = i + c.len_utf8();
            }
            let _ = write!(handle, "{}", &prompt[byte_idx..]);
        }

        // Compute the visible byte/char range of the buffer after scroll.
        let buffer_start = scroll_offset.saturating_sub(prompt_width);
        // Width budget for buffer = total cols - prompt drawn - rprompt reserve.
        let drawn_prompt_width = prompt_width.saturating_sub(scroll_offset);
        let rprompt_reserve = if rprompt_width > 0 {
            rprompt_width + 1
        } else {
            0
        };
        let buffer_budget = effective_cols
            .saturating_sub(drawn_prompt_width)
            .saturating_sub(rprompt_reserve);

        // Walk the buffer chars from buffer_start, applying overlay attrs.
        let mut current_attr: Option<TextAttr> = None;
        let line_snapshot = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clone();
        for (written, (idx, ch)) in line_snapshot
            .iter()
            .enumerate()
            .skip(buffer_start)
            .enumerate()
        {
            if written >= buffer_budget {
                break;
            }
            let want_attr = attrs.get(idx).and_then(|a| *a);
            if want_attr != current_attr {
                let _ = write!(handle, "\x1b[0m");
                if let Some(a) = want_attr {
                    let _ = write!(handle, "{}", a.to_ansi());
                }
                current_attr = want_attr;
            }
            let _ = write!(handle, "{}", ch);
        }
        // Reset SGR before the rprompt / cursor jump.
        if current_attr.is_some() {
            let _ = write!(handle, "\x1b[0m");
        }

        // Right prompt — paint at the absolute right margin if there's
        // room. Mirrors put_rpromptbuf in zle_refresh.c which writes RPS1
        // at column (winw - rpromptw).
        if rprompt_width > 0 && rprompt_width + 2 < effective_cols {
            let rprompt_col = effective_cols.saturating_sub(rprompt_width);
            let _ = write!(handle, "\r\x1b[{}C{}\x1b[0m", rprompt_col, rprompt);
        }

        // Cursor positioning (1-based column in ANSI).
        let display_cursor_col = cursor_col.saturating_sub(scroll_offset);
        let _ = write!(handle, "\r\x1b[{}C", display_cursor_col);

        // c:1488 — `fwrite(out, ..., shout); fflush(shout);`. Single
        //          write_loop emits the whole frame to SHTTY (stdout
        //          fallback). Replaces the prior `stdout.lock()`
        //          fake that wrote refresh output to stdout instead
        //          of the controlling tty.
        use std::sync::atomic::Ordering;
        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, handle.as_bytes());
    }

impl HighlightManager {
    pub fn new() -> Self {
        HighlightManager {
            regions: Vec::new(),
            category_attrs: std::collections::HashMap::new(),
        }
    }

    /// HighlightManager-internal helper: append a single region.
    /// Not a direct C port — `set_region_highlight` proper is the
    /// file-scope free fn below.
    pub fn add_region(&mut self, start: usize, end: usize, attr: TextAttr) {
        self.regions.push(RegionHighlight {
            start,
            end,
            attr,
            memo: None,
        });
    }

    /// Get region highlight for position. Equivalent to
    /// `get_region_highlight()` from zle_refresh.c.
    pub fn get_region_highlight(&self, pos: usize) -> Option<&RegionHighlight> {
        self.regions.iter().find(|r| pos >= r.start && pos < r.end)
    }

    /// Unset region highlight. Equivalent to
    /// `unset_region_highlight()` from zle_refresh.c.
    pub fn unset_region_highlight(&mut self) {
        self.regions.clear();
    }

    /// Free highlight resources. Equivalent to
    /// `zle_free_highlight()` from zle_refresh.c.
    pub fn free(&mut self) {
        self.regions.clear();
    }
}

/// Port of `wpfxlen(const REFRESH_ELEMENT *olds, const REFRESH_ELEMENT *news)` from `Src/Zle/zle_refresh.c:1736`.
/// ```c
/// static int
/// wpfxlen(const REFRESH_ELEMENT *olds, const REFRESH_ELEMENT *news) {
///     int i = 0;
///     while (olds->chr && ZR_equal(*olds, *news))
///         olds++, news++, i++;
///     return i;
/// }
/// ```
/// Common-prefix length of two REFRESH_ELEMENT strings; stops at
/// the first NUL chr in `olds` or first cell that differs in chr+atr.
pub fn wpfxlen(olds: &[crate::ported::zle::zle_h::REFRESH_ELEMENT],
               news: &[crate::ported::zle::zle_h::REFRESH_ELEMENT]) -> usize {
    let mut i = 0;
    while i < olds.len() && i < news.len()
        && olds[i].chr != '\0' && olds[i] == news[i]
    {
        i += 1;
    }
    i
}

    /// Port of `static void refreshline(int ln)` from
    /// `Src/Zle/zle_refresh.c:1749`. Repaints a single screen row at
    /// `ln` from `nbuf[ln]` against `obuf[ln]`: handles `cleareol`,
    /// auto-margin (`hasam`) edge cases, char-insert / char-delete
    /// terminal capabilities (`TCDEL`/`TCINS`), and the
    /// `MULTIBYTE_SUPPORT` `WEOF` width-padding cells.
    ///
    /// ```c
    /// static void
    /// refreshline(int ln)
    /// {
    ///     REFRESH_STRING nl, ol, p1;
    ///     int ccs = 0, char_ins = 0, col_cleareol, i, j;
    ///     int ins_last, nllen, ollen, rnllen;
    ///     const REFRESH_ELEMENT zr_pad = { ZWC(' '), prompt_attr };
    /// /* 0: setup */
    ///     nl = nbuf[ln];
    ///     rnllen = nllen = nl ? ZR_strlen(nl) : 0;
    ///     if (ln < olnct && obuf[ln]) { ol = obuf[ln]; ollen = ZR_strlen(ol); }
    ///     else { static REFRESH_ELEMENT nullchr = { ZWC('\0'), 0 };
    ///            ol = &nullchr; ollen = 0; }
    /// /* optimisation: clear-eol short-circuit */
    ///     if (cleareol && !nllen && !(hasam && ln < nlnct - 1)
    ///         && tccan(TCCLEAREOL)) { moveto(ln, 0); tcoutclear(TCCLEAREOL); return; }
    /// /* 1: pad new buffer */
    ///     if (cleareol || (!nllen && (ln != 0 || !put_rpmpt))
    ///         || (ln == 0 && (put_rpmpt != oput_rpmpt))) { ... pad to winw ... }
    ///     else if (ollen > nllen) { ... pad to ollen ... }
    /// /* 2: clear-to-eol calculation */
    ///     if (hasam && ln < nlnct - 1 && rnllen == winw) col_cleareol = -2;
    ///     else { ... compute col_cleareol from TCCLEAREOL cost ... }
    /// /* 2b: automargin niceness */
    ///     if (hasam && vcs == winw) { ... advance vln/vcs ... }
    ///     ins_last = 0;
    /// /* 2c: prompt-line head skip */
    ///     if (ln == 0 && lpromptw) { ... advance past prompt ... }
    /// /* 3: main display loop */
    ///     for (;;) { ... skip-match / insert-delete / fall-through ... }
    /// }
    /// ```
    ///
    /// Per PORT.md Rule 9 (function bodies port too) the structural
    /// translation lives here even though the screen-output primitives
    /// (`tccan`/`tc_inschars`/`tc_delchars`/`zputc`/`zwrite`/
    /// `wpfxlen`/`tcinscost`/`tcdelcost`/`treplaceattrs`/
    /// `applytextattributes`) and the `nbuf`/`obuf`/`vcs`/`vln`/
    /// `winw`/`winh`/`zterm_lines`/`hasam`/`cleareol`/`put_rpmpt`/
    /// `oput_rpmpt`/`olnct`/`prompt_attr` statics are not yet
    /// surface-area in zshrs. Stubbed deps are flagged inline with
    /// `// !!! STUB: needs <c-name> port at <Src/file.c:NNNN>`.
    pub fn refreshline(ln: i32) {                                            // c:1749
        use std::sync::atomic::Ordering;

        // c:1751 — REFRESH_STRING nl, ol, p1
        // !!! STUB: nbuf / obuf statics — Src/Zle/zle_refresh.c not yet
        // exposed as `pub static NBUF/OBUF: Mutex<Vec<REFRESH_STRING>>`.
        // Treat row vectors as empty so the function exercises the
        // null-buffer paths and degrades to "nothing to draw".
        let mut nl: crate::ported::zle::zle_h::REFRESH_STRING = Vec::new();   // c:1751 nl = nbuf[ln]
        let mut ol: crate::ported::zle::zle_h::REFRESH_STRING = Vec::new();   // c:1751 ol = obuf[ln]
        let _p1: crate::ported::zle::zle_h::REFRESH_STRING = Vec::new();      // c:1751 p1
        let mut ccs: i32 = 0;                                                // c:1752 ccs = 0
        let mut char_ins: i32 = 0;                                           // c:1753 char_ins = 0
        let mut col_cleareol: i32;                                           // c:1754
        let mut i: i32;                                                      // c:1755 tmp
        let mut _j: i32 = 0;                                                 // c:1755 tmp
        let mut ins_last: i32;                                               // c:1756
        let mut nllen: i32;                                                  // c:1757
        let ollen: i32;                                                      // c:1757
        let rnllen: i32;                                                     // c:1758
        let zr_pad = crate::ported::zle::zle_h::REFRESH_ELEMENT {            // c:1759
            chr: ' ',
            atr: 0,
        };

        // 0: setup                                                          // c:1761
        // nl = nbuf[ln]; rnllen = nllen = nl ? ZR_strlen(nl) : 0;           // c:1762-1763
        rnllen = nl.len() as i32;
        nllen = rnllen;
        // c:1764-1772 — `if (ln < olnct && obuf[ln]) { ol = obuf[ln]; ollen = ZR_strlen(ol); }`
        // !!! STUB: olnct static — Src/Zle/zle_refresh.c. Treat obuf row
        // as the static `nullchr = { '\0', 0 }` per c:1769.
        let _olnct: i32 = 0;                                                 // c:1764
        ollen = ol.len() as i32;                                             // c:1766 / c:1771

        // optimisation: clear-eol short-circuit                             // c:1774-1775
        // c:1776-1781 — `if (cleareol && !nllen && !(hasam && ln < nlnct-1)
        //               && tccan(TCCLEAREOL)) { moveto(ln, 0);
        //               tcoutclear(TCCLEAREOL); return; }`
        let cleareol = CLEAREOL.load(Ordering::SeqCst) != 0;
        let hasam_v = crate::ported::init::hasam.load(Ordering::SeqCst) != 0; // c:1776
        let nlnct_v = NLNCT.load(Ordering::SeqCst);
        if cleareol                                                          // c:1776
            && nllen == 0
            && !(hasam_v && ln < nlnct_v - 1)
            && (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCCLEAREOL as usize] != 0)  /* tccan(TCCLEAREOL) per zsh.h:2682 */                       // c:1777
        {
            moveto(ln as usize, 0);                                          // c:1778
            tcoutclear(true);                                                // c:1779
            return;                                                          // c:1780
        }

        // 1: pad out new buffer with spaces                                 // c:1783-1784
        let put_rpmpt = PUT_RPMPT.load(Ordering::SeqCst);
        let oput_rpmpt = OPUT_RPMPT.load(Ordering::SeqCst);
        let winw = crate::ported::zle::zle_refresh::WINW.load(Ordering::SeqCst);
        if cleareol                                                          // c:1786
            || (nllen == 0 && (ln != 0 || put_rpmpt == 0))                   // c:1787
            || (ln == 0 && put_rpmpt != oput_rpmpt)                          // c:1788
        {
            // !!! STUB: zhalloc — Rust uses Vec growth instead of arena alloc.
            let mut padded: crate::ported::zle::zle_h::REFRESH_STRING =       // c:1789
                Vec::with_capacity((winw + 2) as usize);
            for el in nl.iter().take(nllen as usize) {                       // c:1790-1791 ZR_memcpy
                padded.push(*el);
            }
            for _ in nllen..winw {                                           // c:1792 ZR_memset(.., zr_sp, ..)
                padded.push(crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: ' ', atr: 0 });
            }
            padded.push(crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '\0', atr: 0 });  // c:1793 p1[winw] = zr_zr
            if nllen < winw {                                                // c:1794
                padded.push(crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '\0', atr: 0 });  // c:1795
            } else if let Some(extra) = nl.get((winw + 1) as usize).copied() {  // c:1796-1797
                padded.push(extra);
            }
            // c:1798-1801 — if (ln && nbuf[ln]) memcpy back to nl, else nl = p1
            if ln != 0 && !nl.is_empty() {                                   // c:1798
                let copy_len = ((winw + 2) as usize).min(padded.len());      // c:1799
                if nl.len() >= copy_len {
                    for k in 0..copy_len { nl[k] = padded[k]; }
                } else {
                    nl = padded.clone();
                }
            } else {                                                         // c:1800
                nl = padded;                                                 // c:1801
            }
            nllen = winw;                                                    // c:1802
        } else if ollen > nllen {                                            // c:1803
            // c:1804-1809 — pad nl with zr_pad up to ollen.
            let mut padded: crate::ported::zle::zle_h::REFRESH_STRING =       // c:1804
                Vec::with_capacity((ollen + 1) as usize);
            for el in nl.iter().take(nllen as usize) {                       // c:1805
                padded.push(*el);
            }
            for _ in nllen..ollen {                                          // c:1806
                padded.push(zr_pad);
            }
            padded.push(crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '\0', atr: 0 });  // c:1807
            nl = padded;                                                     // c:1808
            nllen = ollen;                                                   // c:1809
        }

        // 2: clear-to-eol calculation                                       // c:1812-1815
        if hasam_v && ln < nlnct_v - 1 && rnllen == winw {                   // c:1817
            col_cleareol = -2;                                               // c:1818 evil — don't
        } else {                                                             // c:1819
            col_cleareol = -1;                                               // c:1820
            if (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCCLEAREOL as usize] != 0)  /* tccan(TCCLEAREOL) per zsh.h:2682 */                       // c:1821
                && (nllen == winw || put_rpmpt != oput_rpmpt)
            {
                // c:1822-1832 — backward-scan to find trailing-space cutoff.
                let a = nl.get((nllen - 1) as usize).map(|e| e.atr).unwrap_or(0);  // c:1822
                let mut i_loc = nllen;                                       // c:1823
                while i_loc > 0
                    && nl.get((i_loc - 1) as usize).map(|e| e.chr == ' ' && e.atr == a).unwrap_or(false)
                {
                    i_loc -= 1;                                              // c:1823
                }
                if nllen == winw && i_loc < nllen {                          // c:1825
                    col_cleareol = i_loc;                                    // c:1826
                } else {                                                     // c:1827
                    let a = ol.get((ollen - 1) as usize).map(|e| e.atr).unwrap_or(0);  // c:1828
                    let mut j_loc = ollen;                                   // c:1829
                    while j_loc > 0
                        && ol.get((j_loc - 1) as usize).map(|e| e.chr == ' ' && e.atr == a).unwrap_or(false)
                    {
                        j_loc -= 1;                                          // c:1829
                    }
                    // c:1831 — tclen[TCCLEAREOL] — termcap-cost lookup.
                    // !!! STUB: tclen[] — Src/init.c:81. Treat as 1.
                    let tclen_clear: i32 = 1;
                    if j_loc > i_loc + tclen_clear {                         // c:1831
                        col_cleareol = i_loc;                                // c:1832
                    }
                }
            }
        }

        // 2b: automargin niceness                                           // c:1837
        let vcs = crate::ported::zle::zle_refresh::VCS.load(Ordering::SeqCst);
        let mut vln = crate::ported::zle::zle_refresh::VLN.load(Ordering::SeqCst);
        if hasam_v && vcs == winw {                                          // c:1839
            // c:1840 — `if (nbuf[vln] && nbuf[vln][vcs + 1].chr == '\n')`
            // !!! STUB: nbuf access — defer.
            let next_is_nl = false;                                          // c:1840 stub
            if next_is_nl {                                                  // c:1840
                vln += 1;                                                    // c:1841
                let new_vcs = 1;                                             // c:1841 vcs = 1
                crate::ported::zle::zle_refresh::VLN.store(vln, Ordering::SeqCst);
                crate::ported::zle::zle_refresh::VCS.store(new_vcs, Ordering::SeqCst);
                // c:1842-1845 — zputc(nbuf[vln]) / zputc(&zr_sp)
                if ln == vln {                                               // c:1846 better safe than sorry
                    if !nl.is_empty() { nl.remove(0); }                      // c:1847 nl++
                    if !ol.is_empty() && ol[0].chr != '\0' {                 // c:1848-1849
                        ol.remove(0);                                        // c:1849 ol++
                    }
                    ccs = 1;                                                 // c:1850
                }
            } else {                                                         // c:1852
                vln += 1;                                                    // c:1853 vln++, vcs = 0
                crate::ported::zle::zle_refresh::VLN.store(vln, Ordering::SeqCst);
                crate::ported::zle::zle_refresh::VCS.store(0, Ordering::SeqCst);
                // c:1854 — zputc(&zr_nl)
            }
        }
        ins_last = 0;                                                        // c:1857

        // 2c: prompt-line head skip                                         // c:1859-1860
        let lpromptw = crate::ported::zle::zle_refresh::LPROMPTW.load(Ordering::SeqCst);
        if ln == 0 && lpromptw != 0 {                                        // c:1862
            i = lpromptw - ccs;                                              // c:1863
            let j_loc = ol.len() as i32;                                     // c:1864 j = ZR_strlen(ol)
            // c:1865 — nl += i (skip i cells)
            for _ in 0..i.min(nl.len() as i32) { nl.remove(0); }
            // c:1866 — ol += (i > j ? j : i)
            let ol_skip = if i > j_loc { j_loc } else { i };
            for _ in 0..ol_skip.min(ol.len() as i32) { ol.remove(0); }
            ccs = lpromptw;                                                  // c:1867
        }

        // c:1870-1880 — `while (nl->chr == WEOF) { nl++; ccs++; vcs++; ... }`
        // MULTIBYTE_SUPPORT WEOF realignment. zshrs's REFRESH_CHAR is
        // `char`; we don't carry a WEOF sentinel, so the loop is empty.

        // 3: main display loop                                              // c:1882
        loop {                                                               // c:1884
            // c:1888 — `if (nl->chr && ol->chr && ZR_equal(ol[1], nl[1]))`
            let nl_first = nl.first().copied();
            let ol_first = ol.first().copied();
            let nl_second = nl.get(1).copied();
            let ol_second = ol.get(1).copied();
            if nl_first.map(|e| e.chr != '\0').unwrap_or(false)              // c:1888
                && ol_first.map(|e| e.chr != '\0').unwrap_or(false)
                && nl_second == ol_second
            {
                // c:1894 — skip past matching cells.
                while !nl.is_empty()                                         // c:1894
                    && nl[0].chr != '\0'
                    && !ol.is_empty()
                    && nl[0] == ol[0]
                {
                    nl.remove(0);                                            // c:1894
                    ol.remove(0);
                    ccs += 1;
                }
            }

            // c:1906 — `if (!nl->chr)`
            if nl.is_empty() || nl[0].chr == '\0' {                          // c:1906
                if ccs == winw && hasam_v && char_ins > 0 && ins_last != 0   // c:1907
                    && vcs != winw
                {
                    // c:1908-1913 — print the deferred last char.
                    // !!! STUB: zputc — defer.
                    crate::ported::zle::zle_refresh::VCS.store(vcs + 1, Ordering::SeqCst);
                    return;                                                  // c:1913
                }
                if char_ins <= 0 || ccs >= winw {                            // c:1915
                    return;                                                  // c:1916 written everything
                }
                if (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCCLEAREOL as usize] != 0)  /* tccan(TCCLEAREOL) per zsh.h:2682 */                   // c:1917
                    && (char_ins >= 1) /* tclen[TCCLEAREOL] stubbed to 1 */
                    && col_cleareol != -2
                {
                    col_cleareol = 0;                                        // c:1920
                }
            }

            moveto(ln as usize, ccs as usize);                               // c:1923

            // c:1925-1929 — if we can finish via clear-to-eol, do so
            if col_cleareol >= 0 && ccs >= col_cleareol {                    // c:1926
                tcoutclear(true);                                            // c:1927 tcoutclear(TCCLEAREOL)
                return;                                                      // c:1928
            }

            // c:1932-1942 — empty nl: pad with spaces or delete chars.
            if nl.is_empty() || nl[0].chr == '\0' {                          // c:1932
                let i_pad = if winw - ccs < char_ins {                       // c:1933
                    winw - ccs
                } else {
                    char_ins
                };
                // c:1934 — `tccan(TCDEL) && tcdelcost(i) <= i + 1`
                let can_del = (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCDEL as usize] != 0)  /* tccan(TCDEL) per zsh.h:2682 */ && i_pad <= i_pad + 1;
                if can_del {
                    // c:1935 — tc_delchars(i)
                    // !!! STUB: tc_delchars — Src/Zle/zle_refresh.c.
                } else {                                                     // c:1936
                    crate::ported::zle::zle_refresh::VCS.store(vcs + i_pad, Ordering::SeqCst);  // c:1937
                    // c:1938-1939 — for (i--; i > 0; ) zputc(&zr_pad)
                    // !!! STUB: zputc — defer.
                }
                return;                                                      // c:1941
            }

            // c:1946 — `if (!ol->chr)`
            if ol.is_empty() || ol[0].chr == '\0' {                          // c:1946
                let i_remain = if col_cleareol >= 0 { col_cleareol } else { nllen };  // c:1947
                let i_write = i_remain - vcs;                                // c:1948
                if i_write > 0 {                                             // c:1949 (DPUTS guard)
                    // c:1958 — zwrite(nl, i)
                    // !!! STUB: zwrite — Src/Zle/zle_refresh.c.
                    crate::ported::zle::zle_refresh::VCS.store(vcs + i_write, Ordering::SeqCst);  // c:1959
                }
                if col_cleareol >= 0 {                                       // c:1960
                    tcoutclear(true);                                        // c:1961
                }
                return;                                                      // c:1962
            }

            // c:1965-1970 — insert/delete eligibility
            let eligible = (ln != 0 || put_rpmpt == 0 || oput_rpmpt == 0)
                && !nl.is_empty() && nl_second.map(|e| e.chr != '\0').unwrap_or(false)
                && !ol.is_empty() && ol_second.map(|e| e.chr != '\0').unwrap_or(false)
                && ol_second != nl_second;
            if eligible {                                                    // c:1965
                // c:1976-2006 — TCDEL try-block: find a series we can delete
                if (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCDEL as usize] != 0)  /* tccan(TCDEL) per zsh.h:2682 */ {                      // c:1976
                    let mut i_try = 1i32;                                    // c:1978
                    while (i_try as usize) < ol.len() && ol[i_try as usize].chr != '\0' {
                        // c:1979 — `tcdelcost(i) < wpfxlen(ol + i, nl)`
                        // !!! STUB: wpfxlen — Src/Zle/zle_refresh.c.
                        let cheap_delete = false;                            // stub
                        if cheap_delete {
                            // c:1985-1990 — apply attributes, tc_delchars(i)
                            // !!! STUB: treplaceattrs / applytextattributes /
                            // tc_delchars — Src/Zle/zle_refresh.c.
                            for _ in 0..i_try {
                                if !ol.is_empty() { ol.remove(0); }          // c:1991 ol += i
                            }
                            char_ins -= i_try;                               // c:1992
                            i_try = 0;                                       // c:2004
                            break;
                        }
                        i_try += 1;
                    }
                    if i_try != 0 { continue; }                              // c:2003-2004
                }

                // c:2012-2060 — TCINS try-block: find chars to insert.
                let zterm_lines = crate::ported::zle::zle_refresh::WINH.load(Ordering::SeqCst);
                if (crate::ported::init::tclen.lock().unwrap()[crate::ported::zsh_h::TCINS as usize] != 0)  /* tccan(TCINS) per zsh.h:2682 */ && vln != zterm_lines - 1 {  // c:2012
                    let mut i_try = 1i32;                                    // c:2014
                    while (i_try as usize) < nl.len() && nl[i_try as usize].chr != '\0' {
                        // c:2015 — `tcinscost(i) < wpfxlen(ol, nl + i)`
                        // !!! STUB.
                        let cheap_insert = false;                            // stub
                        if cheap_insert {
                            // c:2016-2018 — tc_inschars(i); zwrite(nl, i);
                            for _ in 0..i_try {
                                if !nl.is_empty() { nl.remove(0); }          // c:2018 nl += i
                            }
                            char_ins += i_try;                               // c:2025
                            crate::ported::zle::zle_refresh::VCS.store(vcs + i_try, Ordering::SeqCst);
                            ccs += i_try;                                    // c:2026
                            // c:2031-2047 — truncate oldline if past right edge.
                            let mut k = 0i32;
                            while (k as usize) < ol.len()
                                && ol[k as usize].chr != '\0'
                                && k < winw - ccs
                            {
                                k += 1;                                      // c:2031-2032
                            }
                            if k >= winw - ccs && (k as usize) < ol.len() {  // c:2049
                                ol[k as usize] = crate::ported::zle::zle_h::REFRESH_ELEMENT {
                                    chr: '\0', atr: 0,                       // c:2050 ol[i] = zr_zr
                                };
                                ins_last = 1;                                // c:2051
                            }
                            i_try = 0;                                       // c:2054
                            break;
                        }
                        i_try += 1;
                    }
                    if i_try != 0 { continue; }                              // c:2058-2059
                }
            }

            // c:2065-2096 — fallback: dump one char and keep going
            if !nl.is_empty() && nl[0].chr == '\0' {                         // c:2072
                break;                                                       // c:2073
            }
            loop {                                                           // c:2074 do-while wrapper
                // c:2076-2077 — treplaceattrs(nl->atr); applytextattributes(0)
                // !!! STUB: treplaceattrs / applytextattributes —
                // Src/Zle/zle_refresh.c.

                // c:2084 — zputc(nl)
                // !!! STUB: zputc — emits the char to SHTTY.

                if !nl.is_empty() { nl.remove(0); }                          // c:2085 nl++
                if !ol.is_empty() && ol[0].chr != '\0' {                     // c:2086-2087
                    ol.remove(0);                                            // c:2087 ol++
                }
                ccs += 1;                                                    // c:2088
                crate::ported::zle::zle_refresh::VCS.store(vcs + 1, Ordering::SeqCst);

                // c:2094-2095 — WEOF do-while: zshrs has no WEOF sentinel.
                break;
            }
        }

        let _ = (rnllen, ollen, ins_last, _olnct, _p1, _j);  // silence
    }

    /// Direct port of `void moveto(int ln, int cl)` from
    /// `Src/Zle/zle_refresh.c:2105`. C uses termcap `cm` / `cup`
    /// strings to teleport the cursor; Rust emits the equivalent
    /// CSI ; H sequence (rows/cols 1-indexed per ANSI). Was a
    /// `print!` fake.
    pub fn moveto(row: usize, col: usize) {                       // c:2105
        let s = format!("\x1b[{};{}H", row + 1, col + 1);
        let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
    }

/// Port of `void tcmultout(int cap, int multcap, int ct)` from
/// `Src/Zle/zle_refresh.c:2163`. The C version tries the multi-arg
/// `multcap` capability first (`tcoutarg(multcap, ct)`) and only
/// falls back to a single-cap loop when `multcap` is unavailable.
/// Rust port (without termcap probe) goes straight to the loop —
/// `count` repeats of the same single-shot string.
/// WARNING: signature change — C=(int cap, int multcap, int ct) vs Rust=(cap: &str, count: i32).
pub fn tcmultout(cap: &str, count: i32) {                                    // c:2163
    use std::sync::atomic::Ordering;
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    for _ in 0..count {                                                      // c:2173 single-cap loop
        let _ = crate::ported::utils::write_loop(out_fd, cap.as_bytes());
    }
}

    /// Port of `void tc_rightcurs(int ct)` from
    /// `Src/Zle/zle_refresh.c:2150`. CSI C parametrised cursor-right.
    pub fn tc_rightcurs(count: usize) {
        if count > 0 {
            let s = format!("\x1b[{}C", count);
            let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
        }
    }

    /// Port of `void tc_downcurs(int ct)` from
    /// `Src/Zle/zle_refresh.c:2126`. C emits the termcap `do`/`down`
    /// capability `ct` times; Rust emits the parametrised CSI B.
    pub fn tc_downcurs(count: usize) {
        if count > 0 {
            let s = format!("\x1b[{}B", count);
            let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, s.as_bytes());
        }
    }

/// Direct port of `int tcout_via_func(int cap, int arg, int (*outc)(int))`
/// from `Src/Zle/zle_refresh.c:2291`. Looks up the user's `tcout` shell
/// function via `getshfunc` and dispatches when defined; returns 0 if
/// the function was found and called (caller skips the termcap output),
/// 1 otherwise (caller emits the raw termcap escape).
pub fn tcout_via_func(_cap: i32, _arg: i32) -> i32 {                         // c:tcout_via_func
    if crate::ported::utils::getshfunc("tcout").is_some() {
        // Function found; cap/arg would be passed via `$1`/`$2` in a
        // full port — here we just dispatch and let the user fn read
        // the args from the environment / its widget context.
        let _ = crate::ported::zle::compcore::shfunc_call("tcout");
        return 0;
    }
    1
}



/// Port of `void tcout(int cap)` from `Src/Zle/zle_refresh.c:2339`.
/// C looks up the termcap string via `tcstr[cap]` and writes it
/// through `tputs(..., putshout)` to the shell-output fd. Rust port
/// takes the resolved escape string directly (skipping the
/// `tcstr[]` index lookup, since termcap probing isn't fully wired)
/// and writes the bytes to `SHTTY` via `write_loop`.
///
/// Falls back to stdout (fd 1) when `SHTTY` is unset — covers the
/// non-interactive paths (tests, batch evaluation) where there's no
/// dedicated shell-output fd yet.
/// WARNING: signature change — C=(int cap) vs Rust=(cap: &str).
pub fn tcout(cap: &str) {                                                    // c:2339
    use std::sync::atomic::Ordering;
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    if fd >= 0 {
        let _ = crate::ported::utils::write_loop(fd, cap.as_bytes());
    } else {
        let _ = crate::ported::utils::write_loop(1, cap.as_bytes());
    }
    // c:2346 — `SELECT_ADD_COST(tclen[cap])` — without per-cap tclen
    //          table, the cost accounting is dropped (no scheduling
    //          consumer reads it yet).
}

/// Port of `void tcoutarg(int cap, int arg)` from
/// `Src/Zle/zle_refresh.c:2351`. C calls `tgoto(tcstr[cap], arg, arg)`
/// to expand termcap `%d` / parametrised escape codes. Rust port
/// does a literal `%d → arg` substring substitution (mirrors the
/// most common case; doesn't handle the rare termcap `%p1%d`
/// parametrisation that `tgoto` handles).
/// WARNING: signature change — C=(int cap, int arg) vs Rust=(cap: &str, arg: i32).
pub fn tcoutarg(cap: &str, arg: i32) {                                       // c:2351
    use std::sync::atomic::Ordering;
    // c:2355 — `result = tgoto(tcstr[cap], arg, arg);`
    let s = cap.replace("%d", &arg.to_string());
    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, s.as_bytes());          // c:2359
}

    /// Direct port of `void clearscreen(UNUSED(char **args))` from
    /// `Src/Zle/zle_refresh.c:2366`. Writes CSI 2J + CSI H to the
    /// shell-output fd, then re-renders. Was a `print!` fake.
    pub fn clearscreen() {                                          // c:2366
        let _ = crate::ported::utils::write_loop({ use std::sync::atomic::Ordering; let f = crate::ported::init::SHTTY.load(Ordering::Relaxed); if f >= 0 { f } else { 1 } }, b"\x1b[2J\x1b[H");
        zrefresh();
    }

    /// Direct port of `void redisplay(UNUSED(char **args))` from
    /// `Src/Zle/zle_refresh.c:2377`. C kicks `resetneeded = 1` and
    /// returns; Rust just re-runs zrefresh which equivalently
    /// repaints from current state.
    pub fn redisplay() {                                            // c:2377
        zrefresh();
    }

    /// Port of `static void singlerefresh(ZLE_STRING_T tmpline,
    /// int tmpll, int tmpcs)` from `Src/Zle/zle_refresh.c:2397`.
    /// Builds the single-line video buffer used by `read -e`,
    /// `vared`, and predisplay-only refresh paths: pre-allocates
    /// `vbuf` sized for tabs / control chars / wide chars, walks
    /// `tmpline` translating each cell into one or more
    /// REFRESH_ELEMENTs (with region-highlight overlay), windows
    /// the result against `winw - hasam`, then commits to
    /// `nbuf[0]`.
    ///
    /// ```c
    /// static void
    /// singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
    /// {
    ///     REFRESH_STRING vbuf, vp, refreshop;
    ///     int t0, vsiz, nvcs = 0, owinpos = winpos,
    ///         owinprompt = winprompt;
    ///     int width;
    ///     nlnct = 1;
    ///     for (vsiz = 1 + lpromptw, t0 = 0; t0 != tmpll; t0++) {
    ///         if (tmpline[t0] == '\t') vsiz = (vsiz | 7) + 2;
    ///         else if (WC_ISPRINT(tmpline[t0]) && (width = WCWIDTH(...)) > 0)
    ///             { vsiz += width; ...combining... }
    ///         else if (ZC_icntrl(...)) vsiz += 2;
    ///         else vsiz += 10;
    ///     }
    ///     vbuf = zalloc(vsiz * sizeof(*vbuf));
    ///     if (tmpcs < 0) tmpcs = 0;
    ///     ZR_memset(vbuf, zr_sp, lpromptw);
    ///     vp = vbuf + lpromptw;
    ///     *vp = zr_zr;
    ///     for (t0 = 0; t0 < tmpll; t0++) {
    ///         /* compute base_attr from region_highlights overlay */
    ///         /* compute all_attr = mixattrs(special_attr, special_mask, base_attr) */
    ///         if (t0 == tmpcs) nvcs = vp - vbuf;
    ///         /* emit cells per char class: \t, \n, printable wide,
    ///            control, default */
    ///     }
    ///     if (t0 == tmpcs) nvcs = vp - vbuf;
    ///     *vp = zr_zr;
    ///     /* window selection */
    ///     if (winpos == -1) winpos = 0;
    ///     if ((winpos && nvcs < winpos + 1) || (nvcs > winpos + winw - 2))
    ///         { winpos = nvcs - ((winw - hasam) / 2); if (winpos < 0) winpos = 0; }
    ///     if (winpos) vbuf[winpos] = '<';
    ///     if (ZR_strlen(vbuf + winpos) > winw - hasam)
    ///         { vbuf[winpos + winw - hasam - 1] = '>';
    ///           vbuf[winpos + winw - hasam] = zr_zr; }
    ///     ZR_strcpy(nbuf[0], vbuf + winpos);
    ///     zfree(vbuf, vsiz * sizeof(*vbuf));
    ///     nvcs -= winpos;
    ///     if (winpos < lpromptw) winprompt = lpromptw - winpos;
    ///     else winprompt = 0;
    ///     if (winpos != owinpos && winprompt)
    ///         { singmoveto(0); ...output left-prompt fragment... }
    ///     singmoveto(nvcs);
    /// }
    /// ```
    ///
    /// Per PORT.md Rule 9 — body executes against stubs for
    /// `addmultiword`/`mixattrs`/`region_highlights`/`shout`/`fputc`/
    /// `lpromptbuf`/`MB_METACHARLENCONV` / `WCWIDTH` / `IS_BASECHAR` /
    /// `IS_COMBINING` primitives not yet ported. Stubs flagged
    /// inline with `// !!! STUB: …`.
    pub fn singlerefresh(tmpline: &[char], tmpll: i32, mut tmpcs: i32) {     // c:2397
        use std::sync::atomic::Ordering;
        use crate::ported::zle::zle_h::REFRESH_ELEMENT;

        // c:2399-2405 — declarations.
        let mut vbuf: crate::ported::zle::zle_h::REFRESH_STRING;             // c:2399
        let mut vp: usize;                                                   // c:2399 video pointer (index)
        let _refreshop: crate::ported::zle::zle_h::REFRESH_STRING = Vec::new();  // c:2400
        let mut t0: i32;                                                     // c:2401
        let mut vsiz: i32;                                                   // c:2402
        let mut nvcs: i32 = 0;                                               // c:2403
        // !!! STUB: winpos / winprompt statics — Src/Zle/zle_refresh.c:683-684.
        // No `pub static WINPOS/WINPROMPT` ported yet; track locally.
        let owinpos: i32 = -1;                                               // c:2404 winpos snapshot
        let _owinprompt: i32 = 0;                                            // c:2405 winprompt snapshot
        let mut width: i32 = 0;                                              // c:2407

        NLNCT.store(1, Ordering::SeqCst);                                    // c:2410

        // c:2411-2437 — measure required vbuf size.
        let lpromptw = LPROMPTW.load(Ordering::SeqCst);
        vsiz = 1 + lpromptw;                                                 // c:2412
        t0 = 0;
        while t0 != tmpll {                                                  // c:2412
            let ch = *tmpline.get(t0 as usize).unwrap_or(&'\0');
            if ch == '\t' {                                                  // c:2413
                vsiz = (vsiz | 7) + 2;                                       // c:2414
            } else if ch.is_alphanumeric() || ch.is_ascii_graphic() {        // c:2416 WC_ISPRINT
                width = unicode_width::UnicodeWidthChar::width(ch)           // c:2416 WCWIDTH
                    .unwrap_or(1) as i32;
                if width > 0 {
                    vsiz += width;                                           // c:2417
                    // c:2418-2421 — combining-char absorption; skip combos.
                    if crate::ported::zsh_h::isset(
                        crate::ported::zsh_h::COMBININGCHARS,
                    ) {
                        while t0 < tmpll - 1 {                               // c:2419
                            let next = *tmpline.get((t0 + 1) as usize).unwrap_or(&'\0');
                            // !!! STUB: IS_COMBINING — Src/zsh.h:3370.
                            let is_combining = unicode_width::UnicodeWidthChar::width(next)
                                == Some(0);
                            if !is_combining { break; }
                            t0 += 1;                                         // c:2420
                        }
                    }
                }
            } else if (ch as u32) < 0x20 || (ch as u32) == 0x7F {            // c:2424 ZC_icntrl
                if (ch as u32) <= 0xff {                                     // c:2426
                    vsiz += 2;                                               // c:2429
                }
            } else {                                                         // c:2430
                vsiz += 10;                                                  // c:2432 wide / non-printable
            }
            t0 += 1;
        }

        // c:2438 — `vbuf = zalloc(vsiz * sizeof(*vbuf));`
        vbuf = vec![REFRESH_ELEMENT { chr: '\0', atr: 0 }; vsiz as usize];   // c:2438

        if tmpcs < 0 {                                                       // c:2440
            tmpcs = 0;                                                       // c:2445
        }

        // c:2449 — `ZR_memset(vbuf, zr_sp, lpromptw);`
        for k in 0..(lpromptw as usize).min(vbuf.len()) {                    // c:2449
            vbuf[k] = REFRESH_ELEMENT { chr: ' ', atr: 0 };
        }
        vp = lpromptw as usize;                                              // c:2450 vp = vbuf + lpromptw
        if vp < vbuf.len() {
            vbuf[vp] = REFRESH_ELEMENT { chr: '\0', atr: 0 };                // c:2451 *vp = zr_zr
        }

        // c:2453-2563 — main translation loop.
        t0 = 0;
        while t0 < tmpll {                                                   // c:2453
            // c:2454-2479 — region-highlight overlay.
            // !!! STUB: region_highlights / n_region_highlights /
            // default_attr / special_attr / special_mask / prompt_attr /
            // predisplaylen / mixattrs — Src/Zle/zle_refresh.c.
            let base_attr: u64 = 0;                                          // c:2455 mixattrs
            let all_attr: u64 = 0;                                           // c:2480 mixattrs

            if t0 == tmpcs {                                                 // c:2482
                nvcs = vp as i32;                                            // c:2483 nvcs = vp - vbuf
            }
            let ch = *tmpline.get(t0 as usize).unwrap_or(&'\0');

            if ch == '\t' {                                                  // c:2484
                if vp < vbuf.len() {
                    vbuf[vp] = REFRESH_ELEMENT { chr: ' ', atr: base_attr };
                    vp += 1;                                                 // c:2485 *vp++ = zr_sp
                }
                while (vp & 7) != 0 && vp < vbuf.len() {                     // c:2485
                    vbuf[vp] = REFRESH_ELEMENT { chr: ' ', atr: base_attr };
                    vp += 1;                                                 // c:2486
                }
            } else if ch == '\n' {                                           // c:2487
                if vp < vbuf.len() {
                    vbuf[vp] = REFRESH_ELEMENT { chr: '\\', atr: all_attr }; // c:2488-2489
                    vp += 1;                                                 // c:2490
                }
                if vp < vbuf.len() {
                    vbuf[vp] = REFRESH_ELEMENT { chr: 'n', atr: all_attr };  // c:2491-2492
                    vp += 1;                                                 // c:2493
                }
            } else if ch.is_ascii_graphic() || (ch.is_alphanumeric()) {      // c:2495 WC_ISPRINT
                width = unicode_width::UnicodeWidthChar::width(ch)           // c:2496 WCWIDTH
                    .unwrap_or(1) as i32;
                if width > 0 {
                    let ichars: i32 = 1;                                     // c:2497-2507 combining loop
                    // !!! STUB: addmultiword — only invoked when ichars>1.
                    if vp < vbuf.len() {
                        vbuf[vp] = REFRESH_ELEMENT { chr: ch, atr: base_attr };  // c:2512
                        vp += 1;                                             // c:2513
                    }
                    // c:2514-2518 — WEOF cells for wide-char width padding.
                    let mut w = width - 1;
                    while w > 0 {                                            // c:2514
                        if vp < vbuf.len() {
                            vbuf[vp] = REFRESH_ELEMENT { chr: '\0', atr: base_attr };  // c:2515 WEOF
                            vp += 1;                                         // c:2517
                        }
                        w -= 1;
                    }
                    t0 += ichars - 1;                                        // c:2519
                }
            } else if (ch as u32) < 0x20 || (ch as u32) == 0x7F {            // c:2521 ZC_icntrl
                if (ch as u32) <= 0xff {                                     // c:2523
                    let t = ch as u32;                                       // c:2526
                    if vp < vbuf.len() {
                        vbuf[vp] = REFRESH_ELEMENT { chr: '^', atr: all_attr };  // c:2528-2529
                        vp += 1;                                             // c:2530
                    }
                    let display: char = if (t & !0x80) > 31 {                // c:2531-2532
                        '?'
                    } else {
                        ((t | 0x40) as u8) as char                           // c:2532 t | '@'
                    };
                    if vp < vbuf.len() {
                        vbuf[vp] = REFRESH_ELEMENT { chr: display, atr: all_attr };
                        vp += 1;                                             // c:2534
                    }
                }
            } else {                                                         // c:2537 wide non-printable
                // c:2538-2554 — emit `<%.04x>` or `<%.08x>` hex display.
                let hex = if (ch as u32) > 0xFFFF {                          // c:2542
                    format!("<{:08x}>", ch as u32)                           // c:2543
                } else {                                                     // c:2544
                    format!("<{:04x}>", ch as u32)                           // c:2545
                };
                for c in hex.chars() {                                       // c:2547
                    if vp < vbuf.len() {
                        vbuf[vp] = REFRESH_ELEMENT { chr: c, atr: all_attr };  // c:2549-2550
                        vp += 1;                                             // c:2551
                    }
                }
            }
            t0 += 1;
        }
        if t0 == tmpcs {                                                     // c:2564
            nvcs = vp as i32;                                                // c:2565
        }
        if vp < vbuf.len() {
            vbuf[vp] = REFRESH_ELEMENT { chr: '\0', atr: 0 };                // c:2566 *vp = zr_zr
        }

        // c:2569-2587 — window selection.
        // !!! STUB: winpos static — Src/Zle/zle_refresh.c:683. Local.
        let mut winpos: i32 = -1;
        let winw = WINW.load(Ordering::SeqCst);
        let hasam_v = crate::ported::init::hasam.load(Ordering::SeqCst);
        if winpos == -1 {                                                    // c:2569
            winpos = 0;                                                      // c:2570
        }
        if (winpos != 0 && nvcs < winpos + 1)                                // c:2571
            || (nvcs > winpos + winw - 2)
        {
            winpos = nvcs - ((winw - hasam_v) / 2);                          // c:2572
            if winpos < 0 {                                                  // c:2572
                winpos = 0;                                                  // c:2573
            }
        }
        if winpos != 0 && (winpos as usize) < vbuf.len() {                   // c:2575
            vbuf[winpos as usize] = REFRESH_ELEMENT { chr: '<', atr: 0 };    // c:2576-2577 line continues left
        }
        // c:2579-2583 — right-truncate if line continues
        let suffix_start = winpos as usize;
        let suffix_len = vbuf.iter().skip(suffix_start).take_while(|e| e.chr != '\0').count();
        let max_visible = (winw - hasam_v) as usize;
        if suffix_len > max_visible {                                        // c:2579
            let trunc_pos = suffix_start + max_visible - 1;
            if trunc_pos < vbuf.len() {
                vbuf[trunc_pos] = REFRESH_ELEMENT { chr: '>', atr: 0 };      // c:2580-2581 line continues right
            }
            if trunc_pos + 1 < vbuf.len() {
                vbuf[trunc_pos + 1] = REFRESH_ELEMENT { chr: '\0', atr: 0 }; // c:2582
            }
        }

        // c:2584 — `ZR_strcpy(nbuf[0], vbuf + winpos);`
        // !!! STUB: nbuf[] static — defer.

        // c:2585 — zfree(vbuf, vsiz * sizeof(*vbuf)) — Rust drops on scope.
        drop(vbuf);                                                          // c:2585
        nvcs -= winpos;                                                      // c:2586

        // c:2588-2594 — winprompt update.
        let _winprompt: i32 = if winpos < lpromptw {                         // c:2588
            lpromptw - winpos                                                // c:2590
        } else {                                                             // c:2591
            0                                                                // c:2593
        };

        // c:2595-2680 — re-emit left-prompt fragment if winpos changed.
        // !!! STUB: lpromptbuf / Inpar / Outpar / convchar_t /
        // MB_METACHARLENCONV / shout / fputc — Src/Zle/zle_refresh.c.
        // The fragment-re-emit branch is the visible side-effect when
        // the user scrolls horizontally past the visible prompt; defer
        // until termcap-output primitives land.
        if winpos != owinpos {                                               // c:2595
            singmoveto(&mut crate::ported::zle::zle_refresh::RefreshState::new(), 0);  // c:2603
        }

        // c:2680 (function tail) — `singmoveto(nvcs);`
        singmoveto(&mut crate::ported::zle::zle_refresh::RefreshState::new(), nvcs as usize);

        let _ = (lpromptw, width);  // silence unused
    }

/// Port of `singmoveto(int pos)` from Src/Zle/zle_refresh.c:2687.
/// WARNING: param names don't match C — Rust=(state, pos) vs C=(pos)
pub fn singmoveto(state: &mut RefreshState, pos: usize) {                    // c:singmoveto
    // C body: `singlemoveto()` issues termcap cursor-positioning to
    // `pos` on a single-line display. Without termcap output here
    // we just update vcs (cursor column) on RefreshState.
    state.vcs = pos;
}

/// Initialize ZLE refresh subsystem
/// Port of zle_refresh_boot() from zle_refresh.c
pub fn zle_refresh_boot() -> RefreshState {
    RefreshState::new()
}

/// Port of `void zle_refresh_finish(void)` from `Src/Zle/zle_refresh.c:2720`.
/// Module-unload cleanup: `freevideo()`, drop `region_highlights` if
/// allocated (freeing memos via `free_region_highlights_memos()`,
/// zeroing `n_region_highlights`), then `free_cursor_forms()`.
pub fn zle_refresh_finish() {                                                // c:2720
    let mut state = RefreshState::new();                                     // c:2722 freevideo file-statics
    freevideo(&mut state);                                                   // c:2722
    let mut rh = REGION_HIGHLIGHTS.lock().unwrap();                          // c:2724 if (region_highlights)
    if !rh.is_empty() {
        crate::ported::zle::zle_utils::free_region_highlights_memos();       // c:2726
        rh.clear();                                                          // c:2727-2729 zfree + NULL
    }
    drop(rh);
    crate::ported::zle::termquery::free_cursor_forms();                      // c:2733
}


// TextAttr / RefreshElement / VideoBuffer / RefreshState — Rust-side
// aggregates over zsh's C flat-globals (`winw`/`winh`/`vcs`/`vln`/
// `lpromptw`/`rpromptw`/`region_highlights[]`/`nbuf`/`obuf` in
// `Src/Zle/zle_refresh.c`). The C side represents these as separate
// file-scope statics + bitmap-packed `zattr` cells; this port collects
// them into structs for ergonomic access. Eventual unification target
// (mirroring `Src/zsh.h:2685` `pub type zattr = u64`):
//   - `TextAttr` → `zattr` (u64 packed bitmap)
//   - `RefreshElement` → `zle_h::REFRESH_ELEMENT`
//   - `VideoBuffer` → raw `Vec<REFRESH_ELEMENT>` for `nbuf`/`obuf`
//   - `RefreshState` → discrete file-scope statics

/// Unpacked-bool form of `zattr` (C's u64 packed attribute bitmap from
/// `Src/zsh.h:2685`, ported as `pub type zattr = u64`). C stores
/// attributes inline in `REFRESH_ELEMENT.atr` (a `zattr`); this port
/// pre-unpacks to a 6-field struct for ergonomic access.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TextAttr {
    pub bold: bool,
    pub underline: bool,
    pub standout: bool,
    pub blink: bool,
    pub fg_color: Option<u8>,
    pub bg_color: Option<u8>,
}

/// Display cell. Loosely equivalent to zsh's `REFRESH_ELEMENT`
/// (legit-ported at `zle_h.rs:688` as
/// `pub struct REFRESH_ELEMENT { chr: REFRESH_CHAR, atr: zattr }`).
/// Adds a `width: u8` field C doesn't have and uses `TextAttr` for
/// `atr` instead of the C `zattr` bitmap.
#[derive(Debug, Clone, Default)]
pub struct RefreshElement {
    pub chr: char,
    pub atr: TextAttr,
    pub width: u8,
}

/// 2D screen-buffer container. C uses `REFRESH_STRING nbuf[]` and
/// `obuf[]` flat arrays of `REFRESH_ELEMENT *` (zle_refresh.c
/// globals); this struct wraps a single 2D Vec for the per-frame
/// new/old buffer pair.
#[derive(Debug, Clone)]
pub struct VideoBuffer {
    /// Buffer contents — 2D array of lines.
    pub lines: Vec<Vec<RefreshElement>>,
    /// Number of columns.
    pub cols: usize,
    /// Number of rows.
    pub rows: usize,
}

/// Composite of zle_refresh.c globals (winw/winh/vcs/vln/vmaxln,
/// oldmax, lastrow, lastcol, more_status, etc.) collected into one
/// struct. C uses separate file-statics per name
/// (`int winw, winh, vcs, vln, ...`).
#[derive(Debug, Clone, Default)]
pub struct RefreshState {
    /// Number of columns.
    pub columns: usize, // winw, window width                                // c:682
    /// Number of lines.
    pub lines: usize, // winh, window height                                 // c:682
    /// Current line on screen (cursor row).
    pub vln: usize, // video cursor position line                            // c:680
    /// Current column on screen (cursor col).
    pub vcs: usize, // video cursor position column                          // c:680
    /// Prompt width (left).
    pub lpromptw: usize, // prompt widths on screen                          // c:676
    /// Right prompt width.
    pub rpromptw: usize, // prompt widths on screen                          // c:676
    /// Scroll offset for horizontal scrolling.
    pub scrolloff: usize,
    /// Region highlight start.
    pub region_highlight_start: Option<usize>,
    /// Region highlight end.
    pub region_highlight_end: Option<usize>,
    /// Old video buffer.
    pub old_video: Option<VideoBuffer>,
    /// New video buffer.
    pub new_video: Option<VideoBuffer>,
    /// Prompt string (left).
    pub lpromptbuf: String,
    /// Right prompt string.
    pub rpromptbuf: String,
    /// Whether we need full redraw.
    pub need_full_redraw: bool,
    /// Predisplay string (before main buffer).
    pub predisplay: String,
    /// Postdisplay string (after main buffer).
    pub postdisplay: String,
}

// RegionHighlight / HighlightCategory / HighlightManager — Rust-side
// aggregates over zsh's C `region_highlights[N_SPECIAL_HIGHLIGHTS]`
// array + per-category attr globals (`default_attr`/`special_attr`/
// `ellipsis_attr` from `Src/Zle/zle_refresh.c`). C uses bare integer
// indexing into a fixed-size array; this port uses a typed enum +
// HashMap. Eventual unification: collapse into discrete file-scope
// statics matching the C layout.

/// Simplified region-highlight entry. Loosely equivalent to
/// `struct region_highlight` (legit-ported at `zle_h.rs:613` with
/// different fields: start/end/atr/flags/memo/layer).
#[derive(Debug, Clone)]
pub struct RegionHighlight {
    pub start: usize,
    pub end: usize,
    pub attr: TextAttr,
    pub memo: Option<String>,
}

/// Identifies a fixed slot in zsh's
/// `region_highlights[N_SPECIAL_HIGHLIGHTS]` array (zle_refresh.c
/// indices 0=region, 1=isearch, 2=suffix, 3=paste) plus the
/// standalone default/special/ellipsis attr globals
/// (`default_attr`/`special_attr`/`ellipsis_attr`). C uses bare
/// integer indexing — no enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HighlightCategory {
    Region,
    Isearch,
    Suffix,
    Paste,
    Default,
    Special,
    Ellipsis,
}

/// Collects C's `region_highlights[]` array + per-category attr
/// globals (`default_attr`/`special_attr`/`ellipsis_attr` from
/// zle_refresh.c) into one container.
#[derive(Debug, Default)]
pub struct HighlightManager {
    pub regions: Vec<RegionHighlight>,
    /// Per-category attrs from `$zle_highlight`. Index by
    /// `HighlightCategory`. Equivalent to the per-slot atr storage
    /// in `region_highlights[]` and the
    /// `default_attr`/`special_attr`/`ellipsis_attr` globals in
    /// Src/Zle/zle_refresh.c — populated by `zle_set_highlight()`.
    pub category_attrs: std::collections::HashMap<HighlightCategory, TextAttr>,
}

    /// Build the per-character attribute overlay used by `zrefresh`.
    /// One slot per char in `zleline`; `None` means "default attrs",
    /// `Some(attr)` means apply `attr` for that cell.
    ///
    /// Port of the inner loop in `zrefresh()` (Src/Zle/zle_refresh.c) that
    /// consults `region_highlights[]` for each visible cell. The vi
    /// visual-mode region is synthesised from `region_active` + `mark`
    /// here so `v` selects visibly without callers having to push a
    /// region themselves — matching zle_refresh.c's auto-promotion of
    /// `region_active` into a paintable highlight.
    pub fn compute_render_attrs() -> Vec<Option<TextAttr>> {
        let buf_len = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len();
        let mut attrs: Vec<Option<TextAttr>> = vec![None; buf_len];

        // Visual-region attr: prefer the user's `region:` setting from
        // $zle_highlight (populated by zle_set_highlight); fall back to
        // standout per zsh's default at zle_refresh.c:397.
        let visual_attr = crate::ported::zle::zle_main::highlight().lock().unwrap()
            .category_attrs
            .get(&HighlightCategory::Region)
            .copied()
            .unwrap_or(TextAttr {
                standout: true,
                ..TextAttr::default()
            });

        if crate::ported::zle::zle_main::REGION_ACTIVE.load(std::sync::atomic::Ordering::SeqCst) != 0 {
            let (lo, hi) = if crate::ported::zle::zle_main::MARK.load(std::sync::atomic::Ordering::SeqCst) <= crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) {
                (crate::ported::zle::zle_main::MARK.load(std::sync::atomic::Ordering::SeqCst), crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst))
            } else {
                (crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), crate::ported::zle::zle_main::MARK.load(std::sync::atomic::Ordering::SeqCst))
            };
            let lo = lo.min(buf_len);
            let hi = hi.min(buf_len);
            for slot in attrs.iter_mut().take(hi).skip(lo) {
                *slot = Some(visual_attr);
            }
        }
        for region in &crate::ported::zle::zle_main::highlight().lock().unwrap().regions {
            let start = region.start.min(buf_len);
            let end = region.end.min(buf_len);
            for slot in attrs.iter_mut().take(end).skip(start) {
                *slot = Some(region.attr);
            }
        }
        attrs
    }

    /// Full screen refresh - clears and redraws everything.
    pub fn full_refresh() -> io::Result<()> {
        use std::sync::atomic::Ordering;
        let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
        let out = if fd >= 0 { fd } else { 1 };
        let _ = crate::ported::utils::write_loop(out, b"\x1b[2J\x1b[H");
        zrefresh();
        Ok(())
    }

    /// Partial refresh (optimize for minimal updates).
    pub fn partial_refresh() -> io::Result<()> {
        zrefresh();
        Ok(())
    }


/// Calculate visible width of a prompt string — port of `countprompt()`
/// from Src/prompt.c:1140. The C function counts cells while skipping
/// the `Inpar..Outpar` (zsh's `%{...%}`) invisible-region tokens; this
/// Rust port skips ANSI escape sequences instead, which is what the
/// expanded prompt buffer contains by the time the refresh path uses it.
/// The C variant outputs width AND height via out-pointers; this port
/// returns width only (the only field the refresh path consumes here).
fn countprompt(s: &str) -> usize {
    let mut chars = s.chars().peekable();
    let mut width: usize = 0;
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // ANSI escape: skip until terminating letter.
            if chars.peek() == Some(&'[') {
                chars.next();
                while let Some(&nxt) = chars.peek() {
                    chars.next();
                    if nxt.is_ascii_alphabetic() { break; }
                }
            }
            continue;
        }
        width += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
    }
    width
}

/// Parse a highlight attribute spec (the part after the `category:` prefix)
/// into a `TextAttr`. Accepts a comma-separated list of:
///   * `bold` / `nobold`,
///   * `underline` / `nounderline`,
///   * `standout` / `nostandout`,
///   * `blink` / `noblink`,
///   * `fg=N` / `bg=N` where N is 0..=255 (256-colour palette index) or
///     one of the named ANSI colours below,
///   * `none` (clears every attr).
///
/// ZLE-region subset of `match_highlight` (Src/prompt.c:2031),
/// restricted to the tokens users actually set in `$zle_highlight`.
/// The `hl=`/`layer=`/`opacity=` clauses (prompt.c:2042-2094) are
/// not surfaced here — those are prompt-system hooks that don't
/// apply to ZLE region paint.
pub fn match_highlight(spec: &str) -> TextAttr {
    let mut attr = TextAttr::default();
    for token in spec.split(',') {
        let token = token.trim();
        if token.is_empty() {
            continue;
        }
        match token {
            "none" => {
                attr = TextAttr::default();
            }
            "bold" => attr.bold = true,
            "nobold" => attr.bold = false,
            "underline" => attr.underline = true,
            "nounderline" => attr.underline = false,
            "standout" => attr.standout = true,
            "nostandout" => attr.standout = false,
            "blink" => attr.blink = true,
            "noblink" => attr.blink = false,
            other => {
                // Inline port of the named/numeric colour parser the C
                // `match_colour()` (Src/prompt.c:1957) does for `fg=`/
                // `bg=` clauses. The 24-bit `#rrggbb` form and
                // `bright-foo` aliases are not surfaced here.
                let parse = |name: &str| -> Option<u8> {
                    match name {
                        "black" => Some(0),
                        "red" => Some(1),
                        "green" => Some(2),
                        "yellow" => Some(3),
                        "blue" => Some(4),
                        "magenta" => Some(5),
                        "cyan" => Some(6),
                        "white" => Some(7),
                        "default" => None,
                        n => n.parse::<u8>().ok(),
                    }
                };
                if let Some(rest) = other.strip_prefix("fg=") {
                    attr.fg_color = parse(rest);
                } else if let Some(rest) = other.strip_prefix("bg=") {
                    attr.bg_color = parse(rest);
                }
                // Anything else (hl=, layer=, opacity=, unknown name) is
                // silently dropped — same as the C source's "found = 0"
                // exit path at prompt.c:2122 when no clause matched.
            }
        }
    }
    attr
}

/// Port of `ZR_equal(zr1, zr2)` macro from `Src/Zle/zle_refresh.c:74-82`.
/// Multibyte path: `chr == chr && atr == atr && (combining-cluster eq)`.
/// Non-multibyte path collapses to the same first conjunction. Rust uses
/// the derived `PartialEq` on `REFRESH_ELEMENT`.
#[inline]
#[allow(non_snake_case)]
pub fn ZR_equal(                                                             // c:74
    a: crate::ported::zle::zle_h::REFRESH_ELEMENT,
    b: crate::ported::zle::zle_h::REFRESH_ELEMENT,
) -> bool {
    a == b
}

/// Port of `ZR_memcpy(d, s, l)` macro from `Src/Zle/zle_refresh.c:92`.
/// `#define ZR_memcpy(d, s, l)  memcpy((d), (s), (l)*sizeof(REFRESH_ELEMENT))`.
/// Copy `l` REFRESH_ELEMENT slots from `src` to `dst`.
#[inline]
#[allow(non_snake_case)]
pub fn ZR_memcpy(                                                            // c:92
    dst: &mut [crate::ported::zle::zle_h::REFRESH_ELEMENT],
    src: &[crate::ported::zle::zle_h::REFRESH_ELEMENT],
    l: usize,
) {
    dst[..l].copy_from_slice(&src[..l]);
}

/// Port of `zr_end_ellipsis[]` from `Src/Zle/zle_refresh.c:269-281`.
/// "...>" rendered when a long line overflows past the right edge.
/// TXT_ERROR is the standard zsh-error highlight (set in zsh_h::TXT_ERROR).
pub static ZR_END_ELLIPSIS: &[crate::ported::zle::zle_h::REFRESH_ELEMENT] = &[ // c:269
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: ' ', atr: 0 },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '>', atr: 0 },
];

/// Port of `zr_mid_ellipsis1[]` from `zle_refresh.c:287-294`.
/// First half of " <.... ... >" mid-line cluster.
pub static ZR_MID_ELLIPSIS1: &[crate::ported::zle::zle_h::REFRESH_ELEMENT] = &[ // c:287
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: ' ', atr: 0 },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '<', atr: 0 },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
];

/// Port of `zr_mid_ellipsis2[]` from `zle_refresh.c:298-301`.
/// Trailing close of the mid-line ellipsis cluster.
pub static ZR_MID_ELLIPSIS2: &[crate::ported::zle::zle_h::REFRESH_ELEMENT] = &[ // c:298
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '>', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: ' ', atr: 0 },
];

/// Port of `zr_start_ellipsis[]` from `zle_refresh.c:305-311`.
/// "><..." rendered when a line begins past the left edge.
pub static ZR_START_ELLIPSIS: &[crate::ported::zle::zle_h::REFRESH_ELEMENT] = &[ // c:305
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '>', atr: 0 },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
    crate::ported::zle::zle_h::REFRESH_ELEMENT { chr: '.', atr: crate::ported::zsh_h::TXT_ERROR },
];

/// Port of `tcinscost(X)` macro from `Src/Zle/zle_refresh.c:1724`.
/// `#define tcinscost(X) (tccan(TCMULTINS) ? tclen[TCMULTINS] : (X)*tclen[TCINS])`.
/// Cost (in chars) to insert `x` characters: pick the multi-insert
/// terminal capability if available, else linear cost via single-insert.
/// `tccan`/`tclen` are terminal-capability probes (Src/init.c globals);
/// without them ported we approximate with the single-insert path.
#[inline] pub fn tcinscost(x: i32) -> i32 {                                  // c:1724
    // Without tccan/tclen substrate: estimate single-char insert cost
    // as 1 unit per char.
    x.max(0)
}

/// Port of `tcdelcost(X)` macro from `Src/Zle/zle_refresh.c:1725`.
/// `#define tcdelcost(X) (tccan(TCMULTDEL) ? tclen[TCMULTDEL] : (X)*tclen[TCDEL])`.
#[inline] pub fn tcdelcost(x: i32) -> i32 {                                  // c:1725
    x.max(0)
}

/// Port of `tc_delchars(X)` macro from `Src/Zle/zle_refresh.c:1726`.
/// `(void) tcmultout(TCDEL, TCMULTDEL, (X))`. Emit `x` character-
/// delete escapes via the multi-form helper. Without curses substrate
/// it's a no-op.
#[inline] pub fn tc_delchars(_x: i32) {                                      // c:1726
    // c:1726 — `tcmultout(TCDEL, TCMULTDEL, x)`. The Rust port
    // ZLE redraws full lines on every paint via `zrefresh()`
    // rather than emitting per-character delete escapes; no-op.
}

/// Port of `tc_inschars(X)` macro from `Src/Zle/zle_refresh.c:1727`.
/// `(void) tcmultout(TCINS, TCMULTINS, (X))`.
#[inline] pub fn tc_inschars(_x: i32) {                                      // c:1727
}

/// Port of `tc_upcurs(X)` macro from `Src/Zle/zle_refresh.c:1728`.
/// `(void) tcmultout(TCUP, TCMULTUP, (X))`.
#[inline] pub fn tc_upcurs(_x: i32) {                                        // c:1728
}

/// Port of `tc_leftcurs(X)` macro from `Src/Zle/zle_refresh.c:1729`.
/// `(void) tcmultout(TCLEFT, TCMULTLEFT, (X))`.
#[inline] pub fn tc_leftcurs(_x: i32) {                                      // c:1729
}

// =====================================================================
// Refresh-cycle file-static int globals — `Src/Zle/zle_refresh.c:827-832`.
// `static int cleareol, clearf, put_rpmpt, oput_rpmpt, oxtabs,
//             numscrolls, onumscrolls;`
// Carried as AtomicI32 so the multi-threaded shell can safely flip
// them between widget invocations without locking.
// =====================================================================

/// Port of `char *tcout_func_name;` from `Src/Zle/zle_refresh.c:246`.
/// Holds the name of the user `zle -T tc <fn>` redisplay-transform
/// function; cleared by `zle -T -r`. The refresh path invokes it
/// via `getshfunc(tcout_func_name)` (zle_refresh.c:2303).
pub static TCOUT_FUNC_NAME: std::sync::Mutex<Option<String>> =               // c:246
    std::sync::Mutex::new(None);

/// Port of `static int cleareol` from `Src/Zle/zle_refresh.c:827`.
/// Clear-to-end-of-line flag — set when the terminal lacks `cleareod`
/// and we have to fall back to per-line clear.
pub static CLEAREOL:    std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:827

/// Port of `static int clearf` from `Src/Zle/zle_refresh.c:828`.
/// Set when `alwayslastprompt` was used immediately before the
/// current refresh — drives a special clear path.
pub static CLEARF:      std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:828

/// Port of `static int put_rpmpt` from `Src/Zle/zle_refresh.c:829`.
/// Whether we should display the right-prompt this refresh.
pub static PUT_RPMPT:   std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:829

/// Port of `static int oput_rpmpt` from `Src/Zle/zle_refresh.c:830`.
/// Whether the right-prompt was displayed last refresh.
pub static OPUT_RPMPT:  std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:830

/// Port of `static int oxtabs` from `Src/Zle/zle_refresh.c:831`.
/// `oxtabs` flag — tabs expand to spaces if set.
pub static OXTABS:      std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:831

/// Port of `static int numscrolls` from `Src/Zle/zle_refresh.c:832`.
/// Count of scroll operations this refresh — used by `nextline` to
/// decide whether to abort line-loop processing.
pub static NUMSCROLLS:  std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:832

/// Port of `static int onumscrolls` from `Src/Zle/zle_refresh.c:832`.
/// Previous refresh's `numscrolls` value — `nextline` compares to
/// detect runaway scrolling.
pub static ONUMSCROLLS: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:832

// =====================================================================
// mod_export refresh-state globals — `Src/Zle/zle_refresh.c:157-188`.
// Exposed across translation units (other modules read them).
// AtomicI32 for safe lock-free access.
// =====================================================================

/// Port of `mod_export int nlnct` from `Src/Zle/zle_refresh.c:157`.
/// Number of lines counted in the prompt+buffer for the current
/// refresh — drives nbuf allocation (`nlnct * winw` cells).
pub static NLNCT:        std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:157

/// Port of `static int winw` from `Src/Zle/zle_refresh.c:682`.
/// Terminal window width in cells; bounded by `zterm_columns`.
pub static WINW: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(80);                                   // c:682

/// Port of `static int winh` from `Src/Zle/zle_refresh.c:682`.
/// Terminal window height in cells; bounded by `zterm_lines`.
pub static WINH: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(24);                                   // c:682

/// Port of `static int lpromptw` from `Src/Zle/zle_refresh.c:676`.
/// Left prompt's on-screen width after expansion / truncation.
pub static LPROMPTW: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:676

/// Port of `static int vcs` from `Src/Zle/zle_refresh.c:680`.
/// Video cursor column — physical column of the cursor on screen.
pub static VCS: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:680

/// Port of `static int vln` from `Src/Zle/zle_refresh.c:680`.
/// Video cursor line — physical row of the cursor on screen.
pub static VLN: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:680

/// Port of `mod_export int showinglist` from `Src/Zle/zle_refresh.c:165`.
/// Non-zero when a completion-listing is currently displayed below
/// the prompt; refreshes need to redraw it on next paint.
pub static SHOWINGLIST:  std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:165

/// Port of `mod_export int listshown` from `Src/Zle/zle_refresh.c:171`.
/// Number of completion-listing lines actually shown last refresh —
/// used by clear path to know how many lines to wipe.
pub static LISTSHOWN:    std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:171

/// Port of `mod_export int lastlistlen` from `Src/Zle/zle_refresh.c:176`.
/// Length of the previous listing (separate from `listshown` because
/// the listing might be paginated).
pub static LASTLISTLEN:  std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:176

/// Port of `mod_export int clearflag` from `Src/Zle/zle_refresh.c:183`.
/// Request a full screen-clear on next refresh (set by `clear-screen`
/// widget + Ctrl+L).
pub static CLEARFLAG:    std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:183

/// Port of `mod_export int clearlist` from `Src/Zle/zle_refresh.c:188`.
/// Request the completion-listing be wiped on next refresh.
pub static CLEARLIST:    std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0);                                    // c:188

/// Port of `struct rparams` from `Src/Zle/zle_refresh.c:815`. Workspace
/// state threaded through `zrefresh` + `nextline` + `wpfx` — tracks the
/// current line being painted, scroll budget, video cursor, and the
/// in/out pointers into the video buffer.
///
/// C definition (c:815-824):
/// ```c
/// struct rparams {
///     int canscroll;
///     int ln;
///     int more_status;
///     int nvcs;
///     int nvln;
///     int tosln;
///     REFRESH_STRING s;
///     REFRESH_STRING sen;
/// };
/// typedef struct rparams *rparams;
/// ```
///
/// Rust port replaces `REFRESH_STRING s/sen` (raw pointers into the
/// video buffer) with `pos`/`end` byte indices for safe access.
#[derive(Debug, Clone, Default)]
#[allow(non_camel_case_types)]
pub struct rparams {                                                         // c:815
    /// Number of lines we are allowed to scroll.
    pub canscroll: i32,                                                      // c:816
    /// Current line we're working on.
    pub ln: i32,                                                             // c:817
    /// More stuff in status line.
    pub more_status: i32,                                                    // c:818
    /// Video cursor column.
    pub nvcs: i32,                                                           // c:819
    /// Video cursor line.
    pub nvln: i32,                                                           // c:820
    /// Tmp in statusline stuff.
    pub tosln: i32,                                                          // c:821
    /// Cursor index into the video buffer (was `REFRESH_STRING s`).
    pub pos: usize,                                                          // c:822
    /// End-of-line index (was `REFRESH_STRING sen`).
    pub end: usize,                                                          // c:823
}

/// Port of `void set_region_highlight(UNUSED(Param pm), char **aval)`
/// from `Src/Zle/zle_refresh.c:488`. Setter for the `$region_highlight`
/// special parameter. C body: resize the `region_highlights[]` global
/// to `len(aval) + N_SPECIAL_HIGHLIGHTS`, freeing memo strings on
/// each replaced entry, then parse each `aval[i]` into one entry:
/// optional leading `P` sets `ZRH_PREDISPLAY`, two decimal indices
/// become `start`/`end`, `match_highlight()` parses the attribute
/// spec into `atr`+`atrmask` and optional `layer`, and a trailing
/// `memo=NAME` field is stored verbatim. Passing `aval=None` (the
/// `NULL` case from `unset_region_highlight`, c:595) truncates to
/// the special baseline. C uses a packed `struct region_highlight`
/// global; the Rust port stores parsed entries in
/// `REGION_HIGHLIGHTS` via the simplified `RegionHighlight` shape.
/// WARNING: param names don't match C — Rust=(aval) vs C=(pm, aval)
pub fn set_region_highlight(aval: Option<&[String]>) {                       // c:488
    let aval = match aval {                                                  // c:510 !aval
        Some(a) => a,
        None => {
            // c:495-508 — truncate to special baseline when aval is NULL.
            REGION_HIGHLIGHTS.lock().unwrap().clear();
            return;                                                          // c:511
        }
    };
    let mut rh = REGION_HIGHLIGHTS.lock().unwrap();
    rh.clear();                                                              // c:500 free memos
    for entry in aval.iter() {                                               // c:513
        let mut oldstrp: &str = entry.as_str();                              // c:519
        let mut flags: i32 = 0;                                              // c:525
        if oldstrp.starts_with('P') {                                        // c:520
            flags = ZRH_PREDISPLAY;                                          // c:521
            oldstrp = &oldstrp[1..];                                         // c:522
        }
        let _ = flags;
        oldstrp = oldstrp.trim_start_matches(|c: char| c == ' ' || c == '\t'); // c:526
        let (start_val, rest1) = crate::ported::utils::zstrtol(oldstrp, 10); // c:529
        let start = if oldstrp.len() == rest1.len() { -1i32 } else { start_val as i32 }; // c:530-531
        let strp = rest1.trim_start_matches(|c: char| c == ' ' || c == '\t');// c:533
        let (end_val, rest2) = crate::ported::utils::zstrtol(strp, 10);      // c:537
        let end = if strp.len() == rest2.len() { -1i32 } else { end_val as i32 }; // c:537-538
        let strp = rest2.trim_start_matches(|c: char| c == ' ' || c == '\t');// c:541
        // c:545 — match_highlight(strp, ...) into attr fields.
        let attr = crate::ported::zle::zle_refresh::match_highlight(strp);
        // c:551 — memo= field extraction.
        let memo = if let Some(rest) = strp.strip_prefix("memo=") {          // c:517,551
            let end_pos = rest
                .find(|c: char| c == ',' || c == ' ' || c == '\t' || c == '\0')
                .unwrap_or(rest.len());
            Some(rest[..end_pos].to_string())                                // c:581
        } else { None };                                                     // c:583
        if start >= 0 && end >= 0 {
            rh.push(RegionHighlight {
                start: start as usize,
                end: end as usize,
                attr,
                memo,
            });
        }
    }
    // c:586 — freearray(av): aval owned by caller in Rust.
}

/// Process-wide region-highlights table, the Rust analog of C's
/// `mod_export struct region_highlight *region_highlights` global
/// (`Src/Zle/zle_refresh.c:471`). Holds parsed `$region_highlight`
/// entries plus internal callers (isearch/region/suffix).
pub static REGION_HIGHLIGHTS: once_cell::sync::Lazy<std::sync::Mutex<Vec<RegionHighlight>>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(Vec::new()));

/// Port of `ZRH_PREDISPLAY` from `Src/Zle/zle.h` — bit flag set when
/// a `region_highlight` entry's indices are relative to the
/// predisplay buffer rather than `zleline`.
pub const ZRH_PREDISPLAY: i32 = 1;

#[cfg(test)]
mod zr_tests {
    use super::*;
    use crate::ported::zle::zle_h::REFRESH_ELEMENT;
    use crate::ported::zsh_h::{TXT_MULTIWORD_MASK, TXTBOLDFACE};

    fn re(c: char, a: u64) -> REFRESH_ELEMENT {
        REFRESH_ELEMENT { chr: c, atr: a }
    }

    #[test]
    fn zr_memset_fills_slice() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:88-89 — `while (len--) *dst++ = rc`.
        let mut buf = [REFRESH_ELEMENT::default(); 4];
        let fill = re('x', 0);
        ZR_memset(&mut buf, fill, 3);
        assert_eq!(buf[0], fill);
        assert_eq!(buf[1], fill);
        assert_eq!(buf[2], fill);
        // 4th slot unchanged
        assert_eq!(buf[3], REFRESH_ELEMENT::default());
    }

    #[test]
    fn zr_memset_clamps_to_dst_len() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut buf = [REFRESH_ELEMENT::default(); 2];
        let fill = re('y', 0);
        ZR_memset(&mut buf, fill, 99);  // len > dst.len()
        assert_eq!(buf[0], fill);
        assert_eq!(buf[1], fill);
    }

    #[test]
    fn zr_strlen_counts_to_nul() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:106 — `while (wstr++->chr != ZWC('\0')) len++`.
        let s = [re('h', 0), re('i', 0), re('\0', 0)];
        assert_eq!(ZR_strlen(&s), 2);
    }

    #[test]
    fn zr_strlen_empty_starts_with_nul() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let s = [re('\0', 0)];
        assert_eq!(ZR_strlen(&s), 0);
    }

    #[test]
    fn zr_strcpy_copies_through_nul() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:97 — `while ((*dst++ = *src++).chr != ZWC('\0'))`. NUL
        // included in copy.
        let src = [re('a', 0), re('b', 0), re('\0', 0)];
        let mut dst = [REFRESH_ELEMENT::default(); 5];
        ZR_strcpy(&mut dst, &src);
        assert_eq!(dst[0], re('a', 0));
        assert_eq!(dst[1], re('b', 0));
        assert_eq!(dst[2], re('\0', 0));
    }

    #[test]
    fn zr_strncmp_equal_strings() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:127 — pair-equal in chr+atr: returns 0.
        let a = [re('h', 0), re('i', 0)];
        let b = [re('h', 0), re('i', 0)];
        assert_eq!(ZR_strncmp(&a, &b, 2), 0);
    }

    #[test]
    fn zr_strncmp_diff_chr_returns_1() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let a = [re('h', 0), re('i', 0)];
        let b = [re('h', 0), re('o', 0)];
        // c:127 — `if (!ZR_equal(...)) return 1`.
        assert_eq!(ZR_strncmp(&a, &b, 2), 1);
    }

    #[test]
    fn zr_strncmp_diff_atr_returns_1() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:127 — atr is part of equality.
        let a = [re('h', 0)];
        let b = [re('h', TXTBOLDFACE)];
        assert_eq!(ZR_strncmp(&a, &b, 1), 1);
    }

    #[test]
    fn zr_strncmp_early_nul_old() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:124-126 — old has NUL → return !equal.
        let a = [re('\0', 0)];
        let b = [re('x', 0)];
        assert_eq!(ZR_strncmp(&a, &b, 1), 1); // not equal
        let a = [re('\0', 0)];
        let b = [re('\0', 0)];
        assert_eq!(ZR_strncmp(&a, &b, 1), 0); // equal NULs
    }

    #[test]
    fn zr_strncmp_multiword_mask_skips_nul_check() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:124 — `(!(oldwstr->atr & TXT_MULTIWORD_MASK) && !oldwstr->chr)`.
        // If atr has MULTIWORD set, chr=='\0' is NOT a NUL terminator.
        let a = [re('\0', TXT_MULTIWORD_MASK)];
        let b = [re('\0', TXT_MULTIWORD_MASK)];
        // Both elements equal (same chr+atr) → returns 0; the
        // multiword mask path skips the early-NUL exit so we fall
        // through to the regular ZR_equal check.
        assert_eq!(ZR_strncmp(&a, &b, 1), 0);
    }

    #[test]
    fn zr_equal_same_returns_true() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let a = re('a', 0);
        assert!(ZR_equal(a, a));
        let b = re('b', 0);
        assert!(!ZR_equal(a, b));
    }

    #[test]
    fn zr_memcpy_copies_n_elements() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut dst = [re('\0', 0); 5];
        let src = [re('a', 0), re('b', 0), re('c', 0), re('d', 0), re('e', 0)];
        ZR_memcpy(&mut dst, &src, 3);
        assert_eq!(dst[0].chr, 'a');
        assert_eq!(dst[1].chr, 'b');
        assert_eq!(dst[2].chr, 'c');
        assert_eq!(dst[3].chr, '\0');
    }

    #[test]
    fn ellipsis_sizes_match_table_lengths() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(ZR_END_ELLIPSIS_SIZE, 6);
        assert_eq!(ZR_MID_ELLIPSIS1_SIZE, 6);
        assert_eq!(ZR_MID_ELLIPSIS2_SIZE, 2);
        assert_eq!(ZR_START_ELLIPSIS_SIZE, 5);
    }

    #[test]
    fn def_mwbuf_alloc_is_32() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(DEF_MWBUF_ALLOC, 32);
    }

    #[test]
    fn tc_costs_handle_negative() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(tcinscost(-1), 0);
        assert_eq!(tcdelcost(-1), 0);
        assert_eq!(tcinscost(5), 5);
        assert_eq!(tcdelcost(5), 5);
    }

    #[test]
    fn rparams_default_zeros_all_fields() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let r = rparams::default();
        assert_eq!(r.canscroll, 0);
        assert_eq!(r.ln, 0);
        assert_eq!(r.more_status, 0);
        assert_eq!(r.nvcs, 0);
        assert_eq!(r.nvln, 0);
        assert_eq!(r.tosln, 0);
        assert_eq!(r.pos, 0);
        assert_eq!(r.end, 0);
    }
}

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

    #[test]
    fn test_countprompt() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(countprompt("hello"), 5);
        assert_eq!(countprompt("\x1b[31mhello\x1b[0m"), 5);
        assert_eq!(countprompt("日本語"), 6); // 3 chars, 2 width each
    }

    #[test]
    fn test_video_buffer() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut buf = VideoBuffer::new(80, 24);
        assert_eq!(buf.cols, 80);
        assert_eq!(buf.rows, 24);

        buf.set(0, 0, RefreshElement::new('A'));
        assert_eq!(buf.get(0, 0).map(|e| e.chr), Some('A'));

        buf.clear();
        assert_eq!(buf.get(0, 0).map(|e| e.chr), Some(' '));
    }

    #[test]
    fn test_refresh_state() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut state = RefreshState::new();
        assert!(state.old_video.is_some());
        assert!(state.new_video.is_some());

        state.swap_buffers();
        state.free_video();
        assert!(state.old_video.is_none());
    }

    #[test]
    fn compute_render_attrs_empty_buffer_yields_empty_overlay() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert!(compute_render_attrs().is_empty());
    }

    #[test]
    fn compute_render_attrs_visual_mode_paints_mark_to_cursor_in_standout() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "hello world".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MARK.store(2, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(7, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::REGION_ACTIVE.store(1, std::sync::atomic::Ordering::SeqCst); // charwise visual
        let attrs = compute_render_attrs();
        assert_eq!(attrs.len(), 11);
        // [0..2) and [7..11) are unstyled.
        for slot in attrs.iter().take(2) {
            assert!(slot.is_none());
        }
        for slot in attrs.iter().skip(7) {
            assert!(slot.is_none());
        }
        // [2..7) painted in standout.
        for slot in attrs.iter().take(7).skip(2) {
            let attr = slot.expect("standout");
            assert!(attr.standout);
        }
    }

    #[test]
    fn compute_render_attrs_visual_mode_handles_reverse_mark_order() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "abcdef".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(6, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MARK.store(5, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(1, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::REGION_ACTIVE.store(2, std::sync::atomic::Ordering::SeqCst); // linewise — same swap behavior
        let attrs = compute_render_attrs();
        // Range collapses to (1..5).
        assert!(attrs[0].is_none());
        for slot in attrs.iter().take(5).skip(1) {
            assert!(slot.unwrap().standout);
        }
        assert!(attrs[5].is_none());
    }

    #[test]
    fn match_highlight_handles_combined_attrs() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let attr = match_highlight("bold,fg=red,underline");
        assert!(attr.bold);
        assert!(attr.underline);
        assert_eq!(attr.fg_color, Some(1));
    }

    #[test]
    fn match_highlight_named_and_numeric_colors() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(match_highlight("fg=cyan").fg_color, Some(6));
        assert_eq!(match_highlight("bg=42").bg_color, Some(42));
        // Out-of-range numeric → ignored (parse fails for u8).
        assert_eq!(match_highlight("fg=999").fg_color, None);
    }

    #[test]
    fn match_highlight_negation_clears_attr() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let attr = match_highlight("bold,nobold,underline");
        assert!(!attr.bold);
        assert!(attr.underline);
    }

    #[test]
    fn match_highlight_none_resets_everything() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let attr = match_highlight("bold,fg=red,none,underline");
        // After `none` the only thing surviving is the trailing `underline`.
        assert!(!attr.bold);
        assert!(attr.underline);
        assert_eq!(attr.fg_color, None);
    }

    #[test]
    fn zle_set_highlight_populates_categories_and_defaults() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut mgr = HighlightManager::new();
        let entries = ["region:fg=red,bold", "isearch:fg=blue"];
        zle_set_highlight(&mut mgr, &entries);
        let region = mgr.category_attrs[&HighlightCategory::Region];
        assert!(region.bold);
        assert_eq!(region.fg_color, Some(1));
        let isearch = mgr.category_attrs[&HighlightCategory::Isearch];
        assert_eq!(isearch.fg_color, Some(4));
        // Suffix wasn't set: defaults to bold (zle_refresh.c:401).
        let suffix = mgr.category_attrs[&HighlightCategory::Suffix];
        assert!(suffix.bold);
        // Special wasn't set: defaults to standout (zle_refresh.c:396).
        let special = mgr.category_attrs[&HighlightCategory::Special];
        assert!(special.standout);
    }

    #[test]
    fn zle_set_highlight_none_clears_every_slot() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut mgr = HighlightManager::new();
        zle_set_highlight(&mut mgr, &["none"]);
        for cat in [
            HighlightCategory::Region,
            HighlightCategory::Isearch,
            HighlightCategory::Suffix,
            HighlightCategory::Paste,
        ] {
            let attr = mgr.category_attrs[&cat];
            assert_eq!(attr, TextAttr::default());
        }
    }

    #[test]
    fn compute_render_attrs_visual_uses_zle_highlight_region_attr() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // When the user sets `zle_highlight=(region:fg=red,bold)` via
        // zle_set_highlight, vi visual-mode should paint the region
        // with that attr instead of the default standout.
        crate::ported::zle::zle_main::zle_reset();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "abcde".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(5, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MARK.store(1, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(4, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::REGION_ACTIVE.store(1, std::sync::atomic::Ordering::SeqCst);
        zle_set_highlight(&mut crate::ported::zle::zle_main::highlight().lock().unwrap(), &["region:fg=red,bold"]);
        let attrs = compute_render_attrs();
        for slot in attrs.iter().take(4).skip(1) {
            let a = slot.expect("region painted");
            assert!(a.bold);
            assert_eq!(a.fg_color, Some(1));
            // Standout shouldn't be auto-set when user overrode.
            assert!(!a.standout);
        }
    }

    #[test]
    fn compute_render_attrs_explicit_regions_override_default() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "abcde".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(5, std::sync::atomic::Ordering::SeqCst);
        let custom = TextAttr {
            bold: true,
            fg_color: Some(1),
            ..TextAttr::default()
        };
        crate::ported::zle::zle_main::highlight().lock().unwrap()
            .add_region(1, 4, custom);
        let attrs = compute_render_attrs();
        assert!(attrs[0].is_none());
        for slot in attrs.iter().take(4).skip(1) {
            let a = slot.expect("custom");
            assert!(a.bold);
            assert_eq!(a.fg_color, Some(1));
        }
        assert!(attrs[4].is_none());
    }
}