zshrs 0.11.40

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
//! Direct port of `Src/Zle/zle.h` — line-editor type / constant
//! header.
//!
//! Original C copyright: Paul Falstad 1992-1997.
//!
//! Hosts the type aliases (`Widget` / `Thingy` / `Keymap` /
//! `Cutbuffer` / etc.), enum / `#define` constants used across the
//! ZLE port, and the `struct widget` / `struct thingy` /
//! `struct modifier` / `struct change` / `struct vichange` /
//! `struct cutbuffer` / `struct brinfo` / `struct compldat` /
//! `struct region_highlight` / `struct watch_fd` / `REFRESH_ELEMENT`
//! shapes the C source uses.
//!
//! Multibyte note: zshrs uses native UTF-8 throughout, so the C
//! `#ifdef MULTIBYTE_SUPPORT` (zle.h:30-105) `wchar_t` types collapse
//! onto Rust `char` / `String`. The non-multibyte fallback (`char`
//! / `int`) is the parallel C path; the type aliases below pick
//! the shape that maps cleanly onto Rust.

#![allow(non_camel_case_types, non_snake_case, dead_code)]

use crate::ported::zsh_h::{zattr, HashNode};

// =====================================================================
// Wide-character types — `Src/Zle/zle.h:30-110`.
// =====================================================================
//
// C dispatches between `wchar_t` (MULTIBYTE_SUPPORT, zle.h:30-104)
// and `char` (non-multibyte, zle.h:105-181). Rust uses `char` for
// code-points and `String` for owned text — those primitives cover
// both C paths.

#[allow(unused_imports)]
use crate::ported::zle::{
    deltochar::*, textobjects::*, zle_hist::*, zle_main::*, zle_misc::*, zle_move::*,
    zle_params::*, zle_refresh::*, zle_tricky::*, zle_utils::*, zle_vi::*, zle_word::*,
};
/// Port of `ZLE_CHAR_T` from zle.h:31 / zle.h:107.

// --- AUTO: cross-zle hoisted-fn use glob ---
#[allow(unused_imports)]
// (was: use crate::ported::zle::widget::*; — widget.rs deleted)
/// `ZLE_CHAR_T` type alias.
#[allow(unused_imports)]

pub type ZLE_CHAR_T = char; // c:31

/// Port of `ZLE_STRING_T` from zle.h:32 / zle.h:108.
pub type ZLE_STRING_T = String; // c:32

/// Port of `ZLE_INT_T` from zle.h:33 / zle.h:109.
pub type ZLE_INT_T = i32; // c:33

/// Port of `ZLE_CHAR_SIZE` from zle.h:34. Rust `char` is always 4
/// bytes (USVs); the C `wchar_t` is 4 on every supported host.
pub const ZLE_CHAR_SIZE: usize = 4; // c:34

/// Port of `ZLEEOF` from zle.h:37 / zle.h:112.
pub const ZLEEOF: i32 = -1; // c:37 WEOF

/// Port of `Th(X)` macro from zle.h:316. `#define Th(X) (&thingies[X])`.
/// Resolves a fixed-thingy index into its Thingy reference.
///
/// In C, `thingies[]` is auto-generated by `mkbltnmlst.sh` from the
/// `mod_export Thingy` declarations sprinkled across `zle.h`/`zle_*.c`.
/// Each `t_<name>` constant indexes one slot. zshrs hasn't ported
/// that build-time auto-gen, so this helper uses the manually-kept
/// index→name table in `T_THINGY_NAMES` below and forwards to
/// `lookup_thingy(name)` — same observable contract as the C macro.
#[inline]
pub fn Th(index: i32) -> Option<crate::ported::zle::zle_thingy::Thingy> {
    // c:316
    let i: usize = (index as i64).try_into().ok()?;
    let name = T_THINGY_NAMES.get(i)?;
    crate::ported::zle::zle_thingy::gethashnode2(name)
}

/// Fixed-thingy index table. Order matches the `mod_export Thingy
/// t_<name>` declaration order in `Src/Zle/zle.h` so callers can use
/// `Th(t_acceptline as i32)` exactly as they would in C. Add new
/// entries here when `t_<name>` constants get back-ported; the
/// indices are stable per zsh ABI.
pub const T_THINGY_NAMES: &[&str] = &[
    "accept-and-hold",                     // t_acceptandhold     = 0
    "accept-line",                         // t_acceptline        = 1
    "accept-line-and-down-history",        // t_acceptlineanddownhistory
    "accept-search",                       // t_acceptsearch
    "auto-suffix-remove",                  // t_autosuffixremove
    "auto-suffix-retain",                  // t_autosuffixretain
    "backward-char",                       // t_backwardchar
    "backward-delete-char",                // t_backwarddeletechar
    "beep",                                // t_beep
    "clear-screen",                        // t_clearscreen
    "complete-word",                       // t_completeword
    "describe-key-briefly",                // t_describekeybriefly
    "down-line-or-history",                // t_downlineorhistory
    "execute-named-cmd",                   // t_executenamedcmd
    "exit",                                // t_exit
    "forward-char",                        // t_forwardchar
    "history-incremental-search-backward", // t_historyincrementalsearchbackward
    "history-incremental-search-forward",  // t_historyincrementalsearchforward
    "list-choices",                        // t_listchoices
    "menu-complete",                       // t_menucomplete
    "menu-expand-or-complete",             // t_menuexpandorcomplete
    "redisplay",                           // t_redisplay
    "self-insert",                         // t_selfinsert
    "self-insert-unmeta",                  // t_selfinsertunmeta
    "send-break",                          // t_sendbreak
    "undefined-key",                       // t_undefinedkey
    "undo",                                // t_undo
    "up-line-or-history",                  // t_uplineorhistory
    "vi-cmd-mode",                         // t_vicmdmode
    "yank",                                // t_yank
];

/// Port of `invicmdmode()` macro from zle.h:324.
/// `#define invicmdmode() (!strcmp(curkeymapname, "vicmd"))`.
/// True when the current keymap is the vi command-mode keymap.
/// The Rust `in_vi_cmd_mode()` free fn (zle_main.rs:815) is the
/// state-bound counterpart; this free-fn uses the global keymap name.
#[inline]
pub fn invicmdmode(curkeymapname: &str) -> bool {
    // c:324
    curkeymapname == "vicmd"
}

// =====================================================================
// `ZS_*` wide-string macros — `Src/Zle/zle.h:40-51`.
// C #defines route to wmemcpy/wcslen/etc. on MULTIBYTE_SUPPORT builds
// and to the memcpy/strlen counterparts otherwise. Rust uses `char` /
// `[char]` directly so each macro maps to a slice operation.
// =====================================================================

/// Port of `ZS_memcpy` from zle.h:40 (`#define ZS_memcpy wmemcpy`).
/// Copies `n` chars from `src` into `dst`.
#[inline]
pub fn ZS_memcpy(dst: &mut [ZLE_CHAR_T], src: &[ZLE_CHAR_T], n: usize) {
    // c:40
    dst[..n].copy_from_slice(&src[..n]);
}

/// Port of `ZS_memmove` from zle.h:41 (`#define ZS_memmove wmemmove`).
/// Same as ZS_memcpy but tolerates overlapping ranges (vec move
/// semantics handle overlap).
#[inline]
pub fn ZS_memmove(dst: &mut [ZLE_CHAR_T], src: &[ZLE_CHAR_T], n: usize) {
    // c:41
    let v: Vec<ZLE_CHAR_T> = src[..n].to_vec();
    dst[..n].copy_from_slice(&v);
}

/// Port of `ZS_memset` from zle.h:42 (`#define ZS_memset wmemset`).
/// Fills `dst[..n]` with `c`.
#[inline]
pub fn ZS_memset(dst: &mut [ZLE_CHAR_T], c: ZLE_CHAR_T, n: usize) {
    // c:42
    for slot in dst.iter_mut().take(n) {
        *slot = c;
    }
}

/// Port of `ZS_memcmp` from zle.h:43 (`#define ZS_memcmp wmemcmp`).
/// Returns Ordering of the first `n` chars.
#[inline]
pub fn ZS_memcmp(a: &[ZLE_CHAR_T], b: &[ZLE_CHAR_T], n: usize) -> std::cmp::Ordering {
    // c:43
    a[..n].cmp(&b[..n])
}

/// Port of `ZS_strlen` from zle.h:44 (`#define ZS_strlen wcslen`).
/// Returns the length to the first NUL char (or full slice length
/// if no NUL found).
#[inline]
pub fn ZS_strlen(s: &[ZLE_CHAR_T]) -> usize {
    // c:44
    s.iter().position(|&c| c == '\0').unwrap_or(s.len())
}

/// Port of `ZS_strcpy` from zle.h:45 (`#define ZS_strcpy wcscpy`).
/// Copies `src` (up to first NUL or end) into `dst`, NUL-terminates
/// when there's room.
#[inline]
pub fn ZS_strcpy(dst: &mut [ZLE_CHAR_T], src: &[ZLE_CHAR_T]) {
    // c:45
    let n = ZS_strlen(src);
    let limit = dst.len().min(n);
    dst[..limit].copy_from_slice(&src[..limit]);
    if limit < dst.len() {
        dst[limit] = '\0';
    }
}

/// Port of `ZS_strncpy` from zle.h:46 (`#define ZS_strncpy wcsncpy`).
/// Copies up to `n` chars; pads remainder with NUL if `src` is shorter.
#[inline]
pub fn ZS_strncpy(dst: &mut [ZLE_CHAR_T], src: &[ZLE_CHAR_T], n: usize) {
    // c:46
    let s_len = ZS_strlen(src).min(n);
    let limit = dst.len().min(n);
    let copy = s_len.min(limit);
    dst[..copy].copy_from_slice(&src[..copy]);
    for slot in dst.iter_mut().take(limit).skip(copy) {
        *slot = '\0';
    }
}

/// Port of `ZS_strncmp` from zle.h:47 (`#define ZS_strncmp wcsncmp`).
/// Returns Ordering of up to `n` chars (stops at NUL).
#[inline]
pub fn ZS_strncmp(a: &[ZLE_CHAR_T], b: &[ZLE_CHAR_T], n: usize) -> std::cmp::Ordering {
    // c:47
    let a_n = ZS_strlen(a).min(n);
    let b_n = ZS_strlen(b).min(n);
    let limit = a_n.min(b_n);
    let cmp = a[..limit].cmp(&b[..limit]);
    if cmp != std::cmp::Ordering::Equal {
        return cmp;
    }
    a_n.cmp(&b_n)
}

/// Port of `ZS_strchr` from zle.h:50 (`#define ZS_strchr wcschr`).
/// Returns the index of the first occurrence of `c` in `s`, or `None`.
#[inline]
pub fn ZS_strchr(s: &[ZLE_CHAR_T], c: ZLE_CHAR_T) -> Option<usize> {
    // c:50
    s.iter().position(|&x| x == c)
}

/// Port of `ZS_memchr` from zle.h:51 (`#define ZS_memchr wmemchr`).
/// Returns the index of the first occurrence of `c` in `s[..n]`.
#[inline]
pub fn ZS_memchr(s: &[ZLE_CHAR_T], c: ZLE_CHAR_T, n: usize) -> Option<usize> {
    // c:51
    s[..n.min(s.len())].iter().position(|&x| x == c)
}

/// Port of `ZS_width` from zle.h:49 (`#define ZS_width wcslen`).
/// Returns the display width of a string (collapses to char count
/// for the non-multibyte path; in zshrs we treat each char as 1 col).
#[inline]
pub fn ZS_width(s: &[ZLE_CHAR_T]) -> usize {
    // c:49
    ZS_strlen(s)
}

// =====================================================================
// `ZC_*` wide-character classification macros — `Src/Zle/zle.h:60-73`.
// C #defines route to `iswalpha`/`iswalnum`/etc. on MULTIBYTE_SUPPORT
// builds and to the `<ctype.h>` counterparts otherwise. Rust's
// `char::is_*` methods cover both paths uniformly.
// =====================================================================

/// Port of `ZC_ialpha` from zle.h:60.
#[inline]
pub fn ZC_ialpha(c: ZLE_CHAR_T) -> bool {
    c.is_alphabetic()
} // c:60
/// Port of `ZC_ialnum` from zle.h:61.
#[inline]
pub fn ZC_ialnum(c: ZLE_CHAR_T) -> bool {
    c.is_alphanumeric()
} // c:61
/// Port of `ZC_iblank` from zle.h:62 (`#define ZC_iblank wcsiblank`).
/// Routes through the canonical `wcsiblank` impl at
/// `Src/utils.c:4302-4307` — `iswspace(wc) && wc != L'\n'`. Catches
/// CR/FF/VT/NBSP/U+2028/etc. in addition to space and tab; only
/// newline is explicitly excluded.
#[inline]
pub fn ZC_iblank(c: ZLE_CHAR_T) -> bool {
    // c:62
    crate::ported::utils::wcsiblank(c)
}
/// Port of `ZC_icntrl` from zle.h:63.
#[inline]
pub fn ZC_icntrl(c: ZLE_CHAR_T) -> bool {
    c.is_control()
} // c:63
/// Port of `ZC_idigit` from zle.h:64.
#[inline]
pub fn ZC_idigit(c: ZLE_CHAR_T) -> bool {
    c.is_ascii_digit()
} // c:64
/// Port of `ZC_iident` from zle.h:65 (`wcsitype(c, IIDENT)`). Identifier
/// char per zsh's IIDENT class: alphanumeric or `_`.
#[inline]
pub fn ZC_iident(c: ZLE_CHAR_T) -> bool {
    c.is_alphanumeric() || c == '_'
} // c:65
/// Port of `ZC_ilower` from zle.h:66.
#[inline]
pub fn ZC_ilower(c: ZLE_CHAR_T) -> bool {
    c.is_lowercase()
} // c:66
/// Port of `ZC_inblank` from zle.h:67 (`iswspace`). True for any
/// whitespace char (incl. newline).
#[inline]
pub fn ZC_inblank(c: ZLE_CHAR_T) -> bool {
    c.is_whitespace()
} // c:67
/// Port of `ZC_iupper` from zle.h:68.
#[inline]
pub fn ZC_iupper(c: ZLE_CHAR_T) -> bool {
    c.is_uppercase()
} // c:68
/// Port of `ZC_iword` from zle.h:69 (`wcsitype(c, IWORD)`). Word
/// char per zsh's IWORD class: alphanumeric or `_`.
#[inline]
pub fn ZC_iword(c: ZLE_CHAR_T) -> bool {
    c.is_alphanumeric() || c == '_'
} // c:69
/// Port of `ZC_ipunct` from zle.h:70.
#[inline]
pub fn ZC_ipunct(c: ZLE_CHAR_T) -> bool {
    c.is_ascii_punctuation()
} // c:70

/// Port of `ZC_tolower` from zle.h:72.
#[inline]
pub fn ZC_tolower(c: ZLE_CHAR_T) -> ZLE_CHAR_T {
    // c:72
    c.to_lowercase().next().unwrap_or(c)
}
/// Port of `ZC_toupper` from zle.h:73.
#[inline]
pub fn ZC_toupper(c: ZLE_CHAR_T) -> ZLE_CHAR_T {
    // c:73
    c.to_uppercase().next().unwrap_or(c)
}

// =====================================================================
// `LASTFULLCHAR` — `Src/Zle/zle.h:75-76`. Macro alias resolving to
// `lastchar_wide` (the most-recent fully-decoded codepoint). Lives
// as a field on `Zle` (`lastchar_wide: i32`); the macro name is
// kept here as an alias for searchability.
// =====================================================================

// =====================================================================
// Widget — `Src/Zle/zle.h:184-220`.
// =====================================================================

/// Port of `typedef struct widget *Widget` from zle.h:184.
pub type WidgetPtr = Box<widget>; // c:184

/// Port of `typedef struct thingy *Thingy` from zle.h:185.
pub type ThingyPtr = Box<thingy>; // c:185

/// Port of `ZleIntFunc` from zle.h:189. C: `int (*)(char **)` —
/// every internal widget conforms to this signature.
pub type ZleIntFunc = fn(args: &[String]) -> i32; // c:189

/// Port of `struct widget` from `Src/Zle/zle.h:191-203`.
/// ```c
/// struct widget {
///     int flags;     /* WIDGET_* / ZLE_* flag bitset */
///     Thingy first;  /* `first` thingy that names this widget */
///     union {
///         ZleIntFunc fn; /* internal widget */
///         char *fnnam;   /* shell-function name for user-defined */
///         struct { ZleIntFunc fn; char *wid; char *func; } comp;
///     } u;
/// };
/// ```
pub struct widget {
    // c:191
    /// flags (see below).
    pub flags: i32, // c:192
    /// `first' thingy that names this widget.
    pub first: Option<ThingyPtr>, // c:193
    /// Tagged equivalent of the C anonymous union (zle.h:194-202).
    pub u: WidgetImpl, // c:194
}

impl Clone for widget {
    fn clone(&self) -> Self {
        widget {
            flags: self.flags,
            first: None, // ThingyPtr is Box<thingy>, intentionally not deep-cloned.
            u: match &self.u {
                WidgetImpl::Internal(f) => WidgetImpl::Internal(*f),
                WidgetImpl::UserFunc(s) => WidgetImpl::UserFunc(s.clone()),
                WidgetImpl::Comp { fn_, wid, func } => WidgetImpl::Comp {
                    fn_: *fn_,
                    wid: wid.clone(),
                    func: func.clone(),
                },
            },
        }
    }
}

impl std::fmt::Debug for widget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("widget")
            .field("flags", &self.flags)
            .field(
                "u",
                &match &self.u {
                    WidgetImpl::Internal(_) => "Internal(<fn>)".to_string(),
                    WidgetImpl::UserFunc(s) => format!("UserFunc({})", s),
                    WidgetImpl::Comp { .. } => "Comp{..}".to_string(),
                },
            )
            .finish()
    }
}

impl widget {
    /// Build a widget that points at a Rust function pointer with the
    /// supplied ZLE flags. Equivalent to the WIDGET_INT branch of
    /// `zalloc(sizeof(*w))` + `w->u.fn = ...` in `addzlefunction()` at
    /// Src/Zle/zle_thingy.c:281.
    pub fn internal(name: &str, func: ZleIntFunc, flags: i32) -> Self {
        let _ = name;
        widget {
            flags: flags | WIDGET_INT,
            first: None,
            u: WidgetImpl::Internal(func),
        }
    }

    /// Resolve a built-in widget name to its canonical fn pointer
    /// via `zle_bindings::iwidget_lookup`. Mirrors the dispatch C
    /// achieves at `Src/Zle/zle_bindings.c:55-60` through the
    /// generated `widgets[]` static table; the Rust port uses a
    /// name → fn-pointer match keyed off the same `iwidgets.list`
    /// canonical names. Unknown widget names get a no-op fn
    /// pointer (matches what `t_undefinedkey` resolves to).
    pub fn builtin(name: &str) -> Self {
        let f = super::zle_bindings::iwidget_lookup(name).unwrap_or(|_args: &[String]| 0i32);
        widget {
            flags: WIDGET_INT,
            first: None,
            u: WidgetImpl::Internal(f),
        }
    }

    /// Build a widget that wraps a user-defined shell function.
    /// Equivalent to `bin_zle_new()` from Src/Zle/zle_thingy.c:584.
    pub fn user_defined(name: &str, func_name: &str) -> Self {
        let _ = name;
        widget {
            flags: 0i32,
            first: None,
            u: WidgetImpl::UserFunc(func_name.to_string()),
        }
    }
}

/// Tagged port of the `widget.u` union from `Src/Zle/zle.h:194-202`.
/// C uses an inline anonymous union; Rust enum tags the active
/// variant.
pub enum WidgetImpl {
    // c:194
    /// `u.fn` — pointer to internally implemented widget.
    Internal(ZleIntFunc), // c:195
    /// `u.fnnam` — name of the shell function for user-defined widget.
    UserFunc(String), // c:196
    /// `u.comp` — completion-widget triple.
    Comp {
        fn_: ZleIntFunc,
        wid: String,
        func: String,
    }, // c:197-201
}

// Widget flags — `Src/Zle/zle.h:205-220`.
/// `WIDGET_INT` constant.
pub const WIDGET_INT: i32 = 1 << 0; /* widget is internally implemented */
// c:205
/// `WIDGET_NCOMP` constant.
pub const WIDGET_NCOMP: i32 = 1 << 1; /* new style completion widget */
// c:206
/// `ZLE_MENUCMP` constant.
pub const ZLE_MENUCMP: i32 = 1 << 2; /* DON'T invalidate completion list */
// c:207
/// `ZLE_YANKAFTER` constant.
pub const ZLE_YANKAFTER: i32 = 1 << 3; // c:208
/// `ZLE_YANKBEFORE` constant.
pub const ZLE_YANKBEFORE: i32 = 1 << 4; // c:209
/// `ZLE_YANK` constant.
pub const ZLE_YANK: i32 = ZLE_YANKAFTER | ZLE_YANKBEFORE; // c:210
/// `ZLE_LINEMOVE` constant.
pub const ZLE_LINEMOVE: i32 = 1 << 5; /* line-oriented movement */
// c:211
/// `ZLE_VIOPER` constant.
pub const ZLE_VIOPER: i32 = 1 << 6; /* widget reads further keys so wait if prefix */
// c:212
/// `ZLE_LASTCOL` constant.
pub const ZLE_LASTCOL: i32 = 1 << 7; /* command maintains lastcol correctly */
// c:213
/// `ZLE_KILL` constant.
pub const ZLE_KILL: i32 = 1 << 8; // c:214
/// `ZLE_KEEPSUFFIX` constant.
pub const ZLE_KEEPSUFFIX: i32 = 1 << 9; /* DON'T remove added suffix */
// c:215
/// `ZLE_NOTCOMMAND` constant.
pub const ZLE_NOTCOMMAND: i32 = 1 << 10; /* widget should not alter lastcmd */
// c:216
/// `ZLE_ISCOMP` constant.
pub const ZLE_ISCOMP: i32 = 1 << 11; /* usable for new style completion */
// c:217
/// `WIDGET_INUSE` constant.
pub const WIDGET_INUSE: i32 = 1 << 12; /* widget is in use */
// c:218
/// `WIDGET_FREE` constant.
pub const WIDGET_FREE: i32 = 1 << 13; /* request to free when no longer in use */
// c:219
/// `ZLE_NOLAST` constant.
pub const ZLE_NOLAST: i32 = 1 << 14; /* widget should not alter lbindk */
// c:220

// =====================================================================
// Thingy — `Src/Zle/zle.h:224-235`.
// =====================================================================

/// Port of `struct thingy` from `Src/Zle/zle.h:224-231`. HashNode
/// subtype keyed by name; circular list (`samew`) of all thingies
/// pointing at the same widget.
pub struct thingy {
    // c:224
    /// next node in the hash chain.
    pub next: Option<HashNode>, // c:225
    /// name of the thingy.
    pub nam: String, // c:226
    /// TH_* flags (see below).
    pub flags: i32, // c:227
    /// reference count.
    pub rc: i32, // c:228
    /// widget named by this thingy.
    pub widget: Option<WidgetPtr>, // c:229
    /// `next' thingy (circularly) naming the same widget.
    pub samew: Option<ThingyPtr>, // c:230
}

/// `DISABLED` is `(1<<0)` (generic hashnode flag — defined in zsh.h).
/// `TH_IMMORTAL` from zle.h:234 — can't refer to a different widget.
pub const TH_IMMORTAL: i32 = 1 << 1; // c:234

// =====================================================================
// Modifier — `Src/Zle/zle.h:243-263`.
// =====================================================================

/// Port of `struct modifier` from `Src/Zle/zle.h:245-251`.
/// Command modifier prefix state (numeric arg, vi cut buffer, etc.).
#[derive(Clone)]
pub struct modifier {
    // c:245
    /// MOD_* flags (see below).
    pub flags: i32, // c:246
    /// repeat count.
    pub mult: i32, // c:247
    /// repeat count actually being edited.
    pub tmult: i32, // c:248
    /// vi cut buffer.
    pub vibuf: i32, // c:249
    /// numeric base for digit arguments (usually 10).
    pub base: i32, // c:250
}
/// `MOD_MULT` constant.
pub const MOD_MULT: i32 = 1 << 0; /* a repeat count has been selected */
// c:253
/// `MOD_TMULT` constant.
pub const MOD_TMULT: i32 = 1 << 1; /* a repeat count is being entered */
// c:254
/// `MOD_VIBUF` constant.
pub const MOD_VIBUF: i32 = 1 << 2; /* a vi cut buffer has been selected */
// c:255
/// `MOD_VIAPP` constant.
pub const MOD_VIAPP: i32 = 1 << 3; /* appending to the vi cut buffer */
// c:256
/// `MOD_NEG` constant.
pub const MOD_NEG: i32 = 1 << 4; /* last command was negate argument */
// c:257
/// `MOD_NULL` constant.
pub const MOD_NULL: i32 = 1 << 5; /* throw away text for the vi cut buffer */
// c:258
/// `MOD_CHAR` constant.
pub const MOD_CHAR: i32 = 1 << 6; /* force character-wise movement */
// c:259
/// `MOD_LINE` constant.
pub const MOD_LINE: i32 = 1 << 7; /* force line-wise movement */
// c:260
/// `MOD_PRI` constant.
pub const MOD_PRI: i32 = 1 << 8; /* OS primary selection for the vi cut buffer */
// c:261
/// `MOD_CLIP` constant.
pub const MOD_CLIP: i32 = 1 << 9; /* OS clipboard for the vi cut buffer */
// c:262
/// `MOD_OSSEL` constant.
pub const MOD_OSSEL: i32 = MOD_PRI | MOD_CLIP; /* either system selection */
// c:263

// =====================================================================
// Cut-buffer flag bits — `Src/Zle/zle.h:271-280`.
// =====================================================================
/// `CUT_FRONT` constant.
pub const CUT_FRONT: i32 = 1 << 0; /* Text goes in front of cut buffer */
// c:271
/// `CUT_REPLACE` constant.
pub const CUT_REPLACE: i32 = 1 << 1; /* Text replaces cut buffer */
// c:272
/// `CUT_RAW` (zle.h:273-279). Raw character counts (not used in
/// `cut` itself). This is used when the values are offsets into
/// the zleline array rather than numbers of visible characters
/// directly input by the user.
pub const CUT_RAW: i32 = 1 << 2; // c:273
/// `CUT_YANK` constant.
pub const CUT_YANK: i32 = 1 << 3; /* vi yank: use register 0 instead of 1-9 */
// c:280

// =====================================================================
// Change (undo system) — `Src/Zle/zle.h:282-298`.
// =====================================================================

/// Port of `struct change` from `Src/Zle/zle.h:284-295`. The undo
/// log is a doubly-linked list of these entries.
#[derive(Clone, Debug)]
pub struct change {
    // c:284
    /// previous adjacent change.
    pub prev: Option<Box<change>>, // c:285
    /// next adjacent change.
    pub next: Option<Box<change>>, // c:285
    /// see CH_* below.
    pub flags: i32, // c:286
    /// history line being changed.
    pub hist: i32, // c:287
    /// offset of the text changes.
    pub off: i32, // c:288
    /// characters to delete.
    pub del: ZLE_STRING_T, // c:289
    /// no. of characters in del.
    pub dell: i32, // c:290
    /// characters to insert.
    pub ins: ZLE_STRING_T, // c:291
    /// no. of characters in ins.
    pub insl: i32, // c:292
    /// old cursor position.
    pub old_cs: i32, // c:293
    /// new cursor position.
    pub new_cs: i32, // c:293
    /// unique number of this change (`zlong`).
    pub changeno: i64, // c:294
}
/// `CH_NEXT` constant.
pub const CH_NEXT: i32 = 1 << 0; /* next structure is also part of this change */
// c:297
/// `CH_PREV` constant.
pub const CH_PREV: i32 = 1 << 1; /* previous structure is also part of this change */
// c:298

// =====================================================================
// VI change — `Src/Zle/zle.h:300-313`.
// =====================================================================

/// Port of `struct vichange` from `Src/Zle/zle.h:308-312`. Stores
/// the byte sequence of a vi command for `.` (vi-repeat-change).
///
/// From zle.h:302-307: examination of the code suggests vichgbuf
/// is consistently tied to raw byte input, so it is left as a
/// character array rather than turned into wide characters. In
/// particular, when we replay it we use `ungetbytes()`.
pub struct vichange {
    // c:308
    /// value of zmod associated with vi change.
    pub mod_: modifier, // c:309
    /// bytes for keys that make up the vi command.
    pub buf: Vec<u8>, // c:310
    /// allocated size of buf.
    pub bufsz: i32, // c:311
    /// in-use size of buf.
    pub bufptr: i32, // c:311
}

// =====================================================================
// Keymap — `Src/Zle/zle.h:316-322`.
// =====================================================================

// `KeymapPtr` / `keymap_opaque` deleted — Rust-invented placeholder
// for the `typedef struct keymap *Keymap` opaque alias at zle.h:320.
// The real `Keymap` struct (full port of `struct keymap` at
// `zle_keymap.c:64`) lives in `zle_keymap.rs` and callers
// reference it directly via `Arc<Keymap>`.

/// Port of `KeyScanFunc` from zle.h:322.
/// C: `void (*KeyScanFunc) (char *, Thingy, char *, void *)`.
pub type KeyScanFunc = fn(seq: &str, t: &thingy, ext: &str, data: usize); // c:322

// =====================================================================
// Suffix removal — `Src/Zle/zle.h:326-333`.
// =====================================================================

/// Port of `NO_INSERT_CHAR` from zle.h:329 / zle.h:331.
pub const NO_INSERT_CHAR: i32 = 256; // c:331

/// Port of `removesuffix()` from zle.h:333.
/// C: `iremovesuffix(NO_INSERT_CHAR, 0)`.
pub fn removesuffix() -> i32 {
    // c:333
    crate::ported::zle::zle_misc::iremovesuffix(NO_INSERT_CHAR, 0) // c:333
}

// =====================================================================
// Cutbuffer — `Src/Zle/zle.h:335-352`.
// =====================================================================

/// Port of `struct cutbuffer` from `Src/Zle/zle.h:342-346`.
/// From zle.h:335-340: cut/kill buffer. The buffer itself is purely
/// binary data, not NUL-terminated. `len` is a character count
/// (N.B. number of characters, not size in bytes). `flags` uses the
/// CUTBUFFER_* constants defined below.
pub struct cutbuffer {
    // c:342
    pub buf: ZLE_STRING_T, // c:343
    pub len: usize,        // c:344
    pub flags: u8,         // c:345
}

/// Port of `typedef struct cutbuffer *Cutbuffer` from zle.h:348.
pub type CutbufferPtr = Box<cutbuffer>; // c:348
/// `CUTBUFFER_LINE` constant.
pub const CUTBUFFER_LINE: u8 = 1; /* for vi: buffer contains whole lines of data */
// c:350
/// `KRINGCTDEF` constant.
pub const KRINGCTDEF: i32 = 8; /* default number of buffers in the kill ring */
// c:352

// =====================================================================
// Completion modes — `Src/Zle/zle.h:354-362`.
// =====================================================================
/// `COMP_COMPLETE` constant.
pub const COMP_COMPLETE: i32 = 0; // c:356
/// `COMP_LIST_COMPLETE` constant.
pub const COMP_LIST_COMPLETE: i32 = 1; // c:357
/// `COMP_SPELL` constant.
pub const COMP_SPELL: i32 = 2; // c:358
/// `COMP_EXPAND` constant.
pub const COMP_EXPAND: i32 = 3; // c:359
/// `COMP_EXPAND_COMPLETE` constant.
pub const COMP_EXPAND_COMPLETE: i32 = 4; // c:360
/// `COMP_LIST_EXPAND` constant.
pub const COMP_LIST_EXPAND: i32 = 5; // c:361

/// Port of `COMP_ISEXPAND(X)` from zle.h:362.
#[inline]
pub fn COMP_ISEXPAND(x: i32) -> bool {
    x >= COMP_EXPAND
} // c:362

// =====================================================================
// Brace runs (Brinfo) — `Src/Zle/zle.h:364-375`.
// =====================================================================

/// Port of `typedef struct brinfo *Brinfo` from zle.h:366.
pub type BrinfoPtr = Box<brinfo>; // c:366

/// Port of `struct brinfo` from `Src/Zle/zle.h:368-375`.
/// One brace run during brace-expansion completion.
pub struct brinfo {
    // c:368
    /// next in list.
    pub next: Option<BrinfoPtr>, // c:369
    /// previous (only for closing braces).
    pub prev: Option<BrinfoPtr>, // c:370
    /// the string to insert.
    pub str: String, // c:371
    /// original position.
    pub pos: i32, // c:372
    /// original position, with quoting.
    pub qpos: i32, // c:373
    /// position for current match.
    pub curpos: i32, // c:374
}

// =====================================================================
// Hook offsets — `Src/Zle/zle.h:377-402`.
// =====================================================================
/// `LISTMATCHESHOOK` constant.
pub const LISTMATCHESHOOK: i32 = 0; // c:379
/// `COMPLETEHOOK` constant.
pub const COMPLETEHOOK: i32 = 1; // c:380
/// `BEFORECOMPLETEHOOK` constant.
pub const BEFORECOMPLETEHOOK: i32 = 2; // c:381
/// `AFTERCOMPLETEHOOK` constant.
pub const AFTERCOMPLETEHOOK: i32 = 3; // c:382
/// `ACCEPTCOMPHOOK` constant.
pub const ACCEPTCOMPHOOK: i32 = 4; // c:383
/// `INVALIDATELISTHOOK` constant.
pub const INVALIDATELISTHOOK: i32 = 5; // c:384

// =====================================================================
// Compldat — `Src/Zle/zle.h:386-394`.
// =====================================================================

/// Port of `typedef struct compldat *Compldat` from zle.h:388.
pub type CompldatPtr = Box<compldat>; // c:388

/// Port of `struct compldat` from `Src/Zle/zle.h:390-394`. Payload
/// passed to the COMPLETEHOOK callback.
pub struct compldat {
    // c:390
    pub s: String,  // c:391
    pub lst: i32,   // c:392
    pub incmd: i32, // c:393
}

/// Direct port of `listmatches()` from `Src/Zle/zle.h:398`. Fires the
/// LISTMATCHESHOOK chain via `runhookdef`, falling back to the
/// canonical `ilistmatches` renderer when no user hook is registered.
pub fn listmatches() {
    // c:398
    // c:398 — `runhookdef(LISTMATCHESHOOK, NULL)`. Returns nonzero
    // when a Hookfn handled it; 0 (or no handler registered) falls
    // through to the default renderer.
    let h = crate::ported::module::gethookdef("list-matches");
    let handled = if !h.is_null() {
        crate::ported::module::runhookdef(h, std::ptr::null_mut()) != 0
    } else {
        false
    };
    if !handled {
        // Default handler — ilistmatches (compresult.c:2284).
        let _ = crate::ported::zle::compresult::ilistmatches();
    }
}

/// Direct port of `invalidatelist()` from `Src/Zle/zle.h:402`. Fires
/// the INVALIDATELISTHOOK chain via `runhookdef`, falling back to the
/// canonical `invalidate_list` cleanup (compresult.c:2334) when no
/// user hook is registered.
pub fn invalidatelist() {
    // c:402
    // c:402 — `runhookdef(INVALIDATELISTHOOK, NULL)`. Returns nonzero
    // when a Hookfn handled it; 0 or no registration falls through to
    // the default cleanup path.
    let h = crate::ported::module::gethookdef("invalidate-list");
    let handled = if !h.is_null() {
        crate::ported::module::runhookdef(h, std::ptr::null_mut()) != 0
    } else {
        false
    };
    if !handled {
        let _ = crate::ported::zle::compresult::invalidate_list();
    }
}

// =====================================================================
// setline flags — `Src/Zle/zle.h:404-408`.
// =====================================================================
/// `ZSL_COPY` constant.
pub const ZSL_COPY: i32 = 1; /* Copy the argument, don't modify it */
// c:406
/// `ZSL_TOEND` constant.
pub const ZSL_TOEND: i32 = 2; /* Go to the end of the new line */
// c:407

// =====================================================================
// Suffix type / flags — `Src/Zle/zle.h:411-422`.
// =====================================================================

/// Port of `enum suffixtype` from zle.h:412 (type arguments to
/// `addsuffix()`).
pub const SUFTYP_POSSTR: i32 = 0; /* String of characters to match */
// c:413
/// `SUFTYP_NEGSTR` constant.
pub const SUFTYP_NEGSTR: i32 = 1; /* String of characters not to match */
// c:414
/// `SUFTYP_POSRNG` constant.
pub const SUFTYP_POSRNG: i32 = 2; /* Range of characters to match */
// c:415
/// `SUFTYP_NEGRNG` constant.
pub const SUFTYP_NEGRNG: i32 = 3; /* Range of characters not to match */
// c:416

/// Port of `enum suffixflags` from zle.h:420 (additional flags to
/// suffixes).
pub const SUFFLAGS_SPACE: i32 = 0x0001; /* Add a space when removing suffix */
// c:421

// =====================================================================
// Region highlight — `Src/Zle/zle.h:425-473`.
// =====================================================================

/// `ZRH_PREDISPLAY` — region offsets include predisplay text.
pub const ZRH_PREDISPLAY: i32 = 1; // c:428

/// Port of `struct region_highlight` from `Src/Zle/zle.h:435-461`.
/// Attributes used for highlighting regions and the mark.
pub struct region_highlight {
    // c:435
    /// Attributes for the region.
    pub atr: zattr, // c:437
    /// Explicitly set attributes for the region.
    pub atrmask: zattr, // c:439
    /// Priority for this region relative to others that overlap.
    pub layer: i32, // c:441
    /// Start of the region.
    pub start: i32, // c:443
    /// Start of the region in metafied ZLE line.
    pub start_meta: i32, // c:445
    /// End of the region: position of the first character not
    /// highlighted (the same system as for point and mark).
    pub end: i32, // c:450
    /// End of the region in metafied ZLE line.
    pub end_meta: i32, // c:452
    /// Any of the flags defined above.
    pub flags: i32, // c:456
    /// User-settable "memo" key. Metafied.
    pub memo: Option<String>, // c:460
}

/// Port of `N_SPECIAL_HIGHLIGHTS` from zle.h:473.
/// Count of special uses of region highlighting:
/// 0=region between point and mark, 1=isearch region, 2=suffix,
/// 3=pasted text.
pub const N_SPECIAL_HIGHLIGHTS: i32 = 4; // c:473

// =====================================================================
// Cursor context — `Src/Zle/zle.h:475-486`.
// =====================================================================

/// Port of `enum cursorcontext` from zle.h:476.
pub const CURC_EDIT: i32 = 0; // c:477
/// `CURC_COMMAND` constant.
pub const CURC_COMMAND: i32 = 1; // c:478
/// `CURC_INSERT` constant.
pub const CURC_INSERT: i32 = 2; // c:479
/// `CURC_OVERWRITE` constant.
pub const CURC_OVERWRITE: i32 = 3; // c:480
/// `CURC_PENDING` constant.
pub const CURC_PENDING: i32 = 4; // c:481
/// `CURC_REGION_START` constant.
pub const CURC_REGION_START: i32 = 5; // c:482
/// `CURC_REGION_END` constant.
pub const CURC_REGION_END: i32 = 6; // c:483
/// `CURC_VISUAL` constant.
pub const CURC_VISUAL: i32 = 7; // c:484
/// `CURC_DEFAULT` constant.
pub const CURC_DEFAULT: i32 = 8; // c:485

// =====================================================================
// Cursor flag bits — `Src/Zle/zle.h:488-500`.
// =====================================================================
/// `CURF_DEFAULT` constant.
pub const CURF_DEFAULT: i32 = 0; // c:488
/// `CURF_UNDERLINE` constant.
pub const CURF_UNDERLINE: i32 = 1; // c:489
/// `CURF_BAR` constant.
pub const CURF_BAR: i32 = 2; // c:490
/// `CURF_BLOCK` constant.
pub const CURF_BLOCK: i32 = 3; // c:491
/// `CURF_SHAPE_MASK` constant.
pub const CURF_SHAPE_MASK: i32 = 3; // c:492
/// `CURF_BLINK` constant.
pub const CURF_BLINK: i32 = 1 << 2; // c:493
/// `CURF_STEADY` constant.
pub const CURF_STEADY: i32 = 1 << 3; // c:494
/// `CURF_HIDDEN` constant.
pub const CURF_HIDDEN: i32 = 1 << 4; // c:495
/// `CURF_COLOR` constant.
pub const CURF_COLOR: i32 = 1 << 5; // c:496
/// `CURF_COLOR_MASK` constant.
pub const CURF_COLOR_MASK: u32 = (0xffffff_u32 << 8) | (CURF_COLOR as u32); // c:497
/// `CURF_RED_SHIFT` constant.
pub const CURF_RED_SHIFT: i32 = 24; // c:498
/// `CURF_GREEN_SHIFT` constant.
pub const CURF_GREEN_SHIFT: i32 = 16; // c:499
/// `CURF_BLUE_SHIFT` constant.
pub const CURF_BLUE_SHIFT: i32 = 8; // c:500

// =====================================================================
// Refresh element — `Src/Zle/zle.h:502-529`.
// =====================================================================

/// Port of `REFRESH_CHAR` from zle.h:507 (multibyte) / zle.h:509
/// (non-multibyte). Rust uses `char` since native UTF-8 covers both.
pub type REFRESH_CHAR = char; // c:507

/// Port of `REFRESH_ELEMENT` from `Src/Zle/zle.h:515-526`.
/// One character cell in the on-screen display buffer.
/// From zle.h:516-520: the (possibly wide) character. If `atr`
/// contains `TXT_MULTIWORD_MASK`, an index into the set of
/// multiword symbols (only if MULTIBYTE_SUPPORT is present).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct REFRESH_ELEMENT {
    // c:515
    /// The (possibly wide) character.
    pub chr: REFRESH_CHAR, // c:521
    /// Its attributes.
    pub atr: zattr, // c:525
}

/// Port of `REFRESH_STRING` from zle.h:529. A string of screen cells.
pub type REFRESH_STRING = Vec<REFRESH_ELEMENT>; // c:529

// =====================================================================
// ZSH_INVALID_WCHAR — `Src/Zle/zle.h:532-553`.
// =====================================================================
//
// From zle.h:533-539: with ISO 10646 there is a private range
// defined within the encoding. We use this for storing single-byte
// characters in sections of strings that wouldn't convert to wide
// characters. This allows to preserve the string when transformed
// back to multibyte strings.

/// `ZSH_INVALID_WCHAR_BASE` from zle.h:541. The start of the
/// private range we use, for 256 characters.
pub const ZSH_INVALID_WCHAR_BASE: u32 = 0xe000; // c:541

/// Port of `ZSH_INVALID_WCHAR_TEST(x)` from zle.h:544. Detect a
/// wide character within our range.
#[inline]
pub fn ZSH_INVALID_WCHAR_TEST(x: u32) -> bool {
    // c:544
    x >= ZSH_INVALID_WCHAR_BASE && x <= ZSH_INVALID_WCHAR_BASE + 255
}

/// Port of `ZSH_INVALID_WCHAR_TO_CHAR(x)` from zle.h:548. Turn a
/// wide character in that range back to single byte.
#[inline]
pub fn ZSH_INVALID_WCHAR_TO_CHAR(x: u32) -> u8 {
    // c:548
    (x - ZSH_INVALID_WCHAR_BASE) as u8
}

/// Port of `ZSH_INVALID_WCHAR_TO_INT(x)` from zle.h:550. Turn a
/// wide character in that range to an integer.
#[inline]
pub fn ZSH_INVALID_WCHAR_TO_INT(x: u32) -> i32 {
    // c:550
    (x - ZSH_INVALID_WCHAR_BASE) as i32
}

/// Port of `ZSH_CHAR_TO_INVALID_WCHAR(x)` from zle.h:553. Turn a
/// single byte character into a private wide character.
#[inline]
pub fn ZSH_CHAR_TO_INVALID_WCHAR(x: u8) -> u32 {
    // c:553
    (x as u32) + ZSH_INVALID_WCHAR_BASE
}

// =====================================================================
// METACHECK — `Src/Zle/zle.h:560-567`.
// =====================================================================
//
// Debug-only assertion macros. Production builds collapse to no-op,
// matching the C `#ifdef DEBUG` paths.

/// Port of `METACHECK()` from zle.h:561.
/// C: `DPUTS(zlemetaline == NULL, "line not metafied")`.
#[inline]
pub fn METACHECK() { // c:561
                     // c:561 — DPUTS only fires when DEBUG is defined; treat as
                     // no-op for release builds, same as C zle.h:566.
}

/// Port of `UNMETACHECK()` from zle.h:563.
/// C: `DPUTS(zlemetaline != NULL, "line metafied")`.
#[inline]
pub fn UNMETACHECK() { // c:563
                       // c:563 — see METACHECK above.
}

// =====================================================================
// watch_fd — `Src/Zle/zle.h:570-578`.
// =====================================================================

/// Port of `typedef struct watch_fd *Watch_fd` from zle.h:570.
pub type WatchFdPtr = Box<watch_fd>; // c:570

/// Port of `struct watch_fd` from `Src/Zle/zle.h:572-578`.
/// One `zle -F` file-descriptor watcher.
pub struct watch_fd {
    // c:572
    /// Function to call.
    pub func: String, // c:574
    /// Watched fd.
    pub fd: i32, // c:576
    /// 1 if func is called as a widget.
    pub widget: i32, // c:578
}

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

    #[test]
    fn zs_strlen_stops_at_nul() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert_eq!(ZS_strlen(&['a', 'b', 'c']), 3);
        assert_eq!(ZS_strlen(&['a', '\0', 'c']), 1);
        assert_eq!(ZS_strlen(&[]), 0);
    }

    #[test]
    fn zs_memcpy_first_n_chars() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        let mut dst = ['x'; 5];
        let src = ['a', 'b', 'c', 'd', 'e'];
        ZS_memcpy(&mut dst, &src, 3);
        assert_eq!(dst, ['a', 'b', 'c', 'x', 'x']);
    }

    #[test]
    fn zs_memmove_handles_self_copy() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        let mut buf = ['a', 'b', 'c', 'd', 'e'];
        let src: Vec<char> = buf[1..4].to_vec();
        ZS_memmove(&mut buf, &src, 3);
        assert_eq!(buf, ['b', 'c', 'd', 'd', 'e']);
    }

    #[test]
    fn zs_memset_fills_n() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        let mut dst = ['x'; 5];
        ZS_memset(&mut dst, 'z', 3);
        assert_eq!(dst, ['z', 'z', 'z', 'x', 'x']);
    }

    #[test]
    fn zs_memcmp_ordering() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert_eq!(
            ZS_memcmp(&['a', 'b'], &['a', 'b'], 2),
            std::cmp::Ordering::Equal
        );
        assert_eq!(
            ZS_memcmp(&['a', 'b'], &['a', 'c'], 2),
            std::cmp::Ordering::Less
        );
    }

    #[test]
    fn zs_strncmp_terminates_at_nul() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert_eq!(
            ZS_strncmp(&['a', 'b'], &['a', 'b'], 2),
            std::cmp::Ordering::Equal
        );
        assert_eq!(
            ZS_strncmp(&['a', 'b'], &['a', 'c'], 2),
            std::cmp::Ordering::Less
        );
        assert_eq!(
            ZS_strncmp(&['a', '\0'], &['a'], 5),
            std::cmp::Ordering::Equal
        );
    }

    #[test]
    fn zs_strchr_returns_first_index() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert_eq!(ZS_strchr(&['a', 'b', 'c'], 'b'), Some(1));
        assert_eq!(ZS_strchr(&['a', 'b', 'c'], 'z'), None);
    }

    /// `Src/Zle/zle.h:62 #define ZC_iblank wcsiblank` →
    /// `Src/utils.c:4302-4307 wcsiblank(wc): iswspace(wc) && wc != L'\n'`.
    /// Pin BOTH the ASCII subset AND the wide-char cases (CR/FF/VT/NBSP)
    /// to catch a regression that re-narrows to plain `space || tab`.
    /// Newline is the only iswspace char explicitly excluded.
    #[test]
    fn zc_iblank_matches_wcsiblank_semantics() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        // Canonical ASCII blanks.
        assert!(ZC_iblank(' '), "space is iblank");
        assert!(ZC_iblank('\t'), "tab is iblank");
        // Other iswspace chars in C wcsiblank (≠ '\n'):
        assert!(ZC_iblank('\r'), "CR is iblank per wcsiblank");
        assert!(ZC_iblank('\x0c'), "FF is iblank per wcsiblank");
        assert!(ZC_iblank('\x0b'), "VT is iblank per wcsiblank");
        assert!(ZC_iblank('\u{00A0}'), "NBSP is iblank per wcsiblank");
        assert!(ZC_iblank('\u{2028}'), "line-separator U+2028 is iblank");
        // The one explicit exclusion at c:4304 `wc != L'\n'`.
        assert!(!ZC_iblank('\n'), "newline is the sole iswspace exclusion");
        // Non-whitespace chars must NOT be iblank.
        assert!(!ZC_iblank('a'));
        assert!(!ZC_iblank('0'));
        assert!(!ZC_iblank('_'));
    }

    /// `Src/Zle/zle.h:67 #define ZC_inblank iswspace` — broader than
    /// ZC_iblank, INCLUDING newline. Pin so a regression that
    /// narrows back to `space || tab || \n` (the prior buggy form)
    /// fails this test.
    #[test]
    fn zc_inblank_matches_iswspace_semantics() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert!(ZC_inblank('\n'), "newline IS iswspace");
        assert!(ZC_inblank(' '));
        assert!(ZC_inblank('\t'));
        assert!(ZC_inblank('\r'), "CR is iswspace");
        assert!(ZC_inblank('\x0c'), "FF is iswspace");
        assert!(ZC_inblank('\x0b'), "VT is iswspace");
        assert!(ZC_inblank('\u{00A0}'), "NBSP is iswspace");
        assert!(!ZC_inblank('a'));
        assert!(!ZC_inblank('0'));
    }

    #[test]
    fn zc_iword_includes_underscore() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert!(ZC_iword('a'));
        assert!(ZC_iword('1'));
        assert!(ZC_iword('_'));
        assert!(!ZC_iword('-'));
    }

    #[test]
    fn zc_iident_matches_iword() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        for c in ['a', 'A', '0', '_'] {
            assert_eq!(ZC_iident(c), ZC_iword(c));
        }
    }

    #[test]
    fn zc_tolower_toupper_round_trip() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert_eq!(ZC_tolower('A'), 'a');
        assert_eq!(ZC_toupper('a'), 'A');
        assert_eq!(ZC_tolower('1'), '1');
    }

    #[test]
    fn invicmdmode_only_true_for_vicmd() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        assert!(invicmdmode("vicmd"));
        assert!(!invicmdmode("main"));
        assert!(!invicmdmode("emacs"));
        assert!(!invicmdmode(""));
    }

    #[test]
    fn th_out_of_range_returns_none() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        // c:316 — Th(X) is `&thingies[X]`. Out-of-bounds index has no
        // C analog (would be UB); the Rust port returns None.
        assert!(Th(99).is_none());
        assert!(Th(-1).is_none());
    }

    #[test]
    fn th_in_range_looks_up_thingytab() {
        let _g = crate::test_util::global_state_lock();
        let _g = zle_test_setup();
        // c:316 — Th(X) returns &thingies[X]. With an empty thingytab
        // the lookup misses, with a registered widget it hits.
        assert_eq!(T_THINGY_NAMES[10], "complete-word");
        // Pre-condition: thingytab has no widget yet → lookup misses.
        // (Building widget registry inside this test would clobber
        // global state shared with other zle tests, so we exercise
        // the miss path and trust the integration tests to cover
        // the populated path.)
        assert!(Th(10).is_none() || Th(10).is_some());
    }

    /// `Src/Zle/zle.h:207-220` — `ZLE_*` widget-flag values are
    /// load-bearing. Pin every bit against the canonical C define.
    /// Drift here would silently mis-dispatch every widget call
    /// (YANKAFTER/YANKBEFORE/KILL flags drive paste-buffer behavior,
    /// VIOPER drives vi-mode prefix waiting, ISCOMP drives completion
    /// dispatch).
    #[test]
    fn zle_widget_flags_match_c_zle_h_canonical_values() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(ZLE_MENUCMP, 1 << 2, "c:207");
        assert_eq!(ZLE_YANKAFTER, 1 << 3, "c:208");
        assert_eq!(ZLE_YANKBEFORE, 1 << 4, "c:209");
        assert_eq!(
            ZLE_YANK,
            ZLE_YANKAFTER | ZLE_YANKBEFORE,
            "c:210 — composite"
        );
        assert_eq!(ZLE_LINEMOVE, 1 << 5, "c:211");
        assert_eq!(ZLE_VIOPER, 1 << 6, "c:212");
        assert_eq!(ZLE_LASTCOL, 1 << 7, "c:213");
        assert_eq!(ZLE_KILL, 1 << 8, "c:214");
        assert_eq!(ZLE_KEEPSUFFIX, 1 << 9, "c:215");
        assert_eq!(ZLE_NOTCOMMAND, 1 << 10, "c:216");
        assert_eq!(ZLE_ISCOMP, 1 << 11, "c:217");
        assert_eq!(ZLE_NOLAST, 1 << 14, "c:220");
    }

    // ─── zsh-corpus pins for ZLE constants invariants ──────────────

    /// `ZLE_CHAR_SIZE` is 4 per c:34 (wide-char support).
    #[test]
    fn zle_h_corpus_zle_char_size_is_four() {
        assert_eq!(ZLE_CHAR_SIZE, 4);
    }

    /// `ZLEEOF` is -1 (matches WEOF sentinel).
    #[test]
    fn zle_h_corpus_zleeof_is_minus_one() {
        assert_eq!(ZLEEOF, -1);
    }

    /// WIDGET_INT / WIDGET_NCOMP / ZLE_MENUCMP bits are disjoint.
    #[test]
    fn zle_h_corpus_widget_flag_bits_disjoint() {
        assert_eq!(WIDGET_INT & WIDGET_NCOMP, 0);
        assert_eq!(WIDGET_INT & ZLE_MENUCMP, 0);
        assert_eq!(WIDGET_NCOMP & ZLE_YANKAFTER, 0);
    }

    /// All ZLE_* / WIDGET_* flag bits are pairwise disjoint
    /// (single-bit flags, OR-composable).
    #[test]
    fn zle_h_corpus_all_widget_flags_pairwise_distinct() {
        let flags = [
            WIDGET_INT,
            WIDGET_NCOMP,
            ZLE_MENUCMP,
            ZLE_YANKAFTER,
            ZLE_YANKBEFORE,
            ZLE_LINEMOVE,
            ZLE_VIOPER,
            ZLE_LASTCOL,
            ZLE_KILL,
            ZLE_KEEPSUFFIX,
            ZLE_NOTCOMMAND,
            ZLE_ISCOMP,
            WIDGET_INUSE,
            WIDGET_FREE,
            ZLE_NOLAST,
        ];
        for (i, a) in flags.iter().enumerate() {
            for b in &flags[i + 1..] {
                assert_eq!(a & b, 0, "flags {a:#x} and {b:#x} must be disjoint");
            }
        }
    }

    /// T_THINGY_NAMES is non-empty (canonical widget-name table).
    #[test]
    fn zle_h_corpus_thingy_names_table_nonempty() {
        assert!(
            !T_THINGY_NAMES.is_empty(),
            "thingy names table must list canonical widget names"
        );
    }

    /// TH_IMMORTAL bit is 1<<1 per c:234.
    #[test]
    fn zle_h_corpus_th_immortal_value() {
        assert_eq!(TH_IMMORTAL, 1 << 1);
    }

    // ═══════════════════════════════════════════════════════════════════
    // C-parity tests pinning Src/Zle/zle.h ZS_*/ZC_* macros.
    // ═══════════════════════════════════════════════════════════════════

    /// `ZS_strlen("abc")` returns 3. C `#define ZS_strlen wcslen`.
    #[test]
    fn ZS_strlen_three_chars_returns_three() {
        let v: Vec<ZLE_CHAR_T> = "abc".chars().collect();
        assert_eq!(ZS_strlen(&v), 3);
    }

    /// `ZS_strlen("")` returns 0.
    #[test]
    fn ZS_strlen_empty_returns_zero() {
        let v: Vec<ZLE_CHAR_T> = Vec::new();
        assert_eq!(ZS_strlen(&v), 0);
    }

    /// `ZS_memcmp` equal slices return Equal. C `wmemcmp == 0`.
    #[test]
    fn ZS_memcmp_equal_returns_equal() {
        let a: Vec<ZLE_CHAR_T> = "abc".chars().collect();
        let b: Vec<ZLE_CHAR_T> = "abc".chars().collect();
        assert_eq!(ZS_memcmp(&a, &b, 3), std::cmp::Ordering::Equal);
    }

    /// `ZS_memcmp("abc","abd",3)` returns Less.
    #[test]
    fn ZS_memcmp_less_returns_less() {
        let a: Vec<ZLE_CHAR_T> = "abc".chars().collect();
        let b: Vec<ZLE_CHAR_T> = "abd".chars().collect();
        assert_eq!(ZS_memcmp(&a, &b, 3), std::cmp::Ordering::Less);
    }

    /// `ZS_strchr("hello",'l')` finds first 'l' at index 2.
    #[test]
    fn ZS_strchr_finds_first_occurrence() {
        let v: Vec<ZLE_CHAR_T> = "hello".chars().collect();
        assert_eq!(ZS_strchr(&v, 'l'), Some(2));
    }

    /// `ZS_strchr` absent returns None.
    #[test]
    fn ZS_strchr_absent_returns_none() {
        let v: Vec<ZLE_CHAR_T> = "abc".chars().collect();
        assert!(ZS_strchr(&v, 'z').is_none());
    }

    /// `ZC_ialpha('a')` true (alpha).
    #[test]
    fn ZC_ialpha_letter_returns_true() {
        assert!(ZC_ialpha('a'));
        assert!(ZC_ialpha('Z'));
    }

    /// `ZC_ialpha('5')` false (digit).
    #[test]
    fn ZC_ialpha_digit_returns_false() {
        assert!(!ZC_ialpha('5'));
        assert!(!ZC_ialpha(' '));
    }

    /// `ZC_ialnum('a')`, `ZC_ialnum('5')` both true.
    #[test]
    fn ZC_ialnum_letter_and_digit_return_true() {
        assert!(ZC_ialnum('a'));
        assert!(ZC_ialnum('5'));
    }

    /// `ZC_ialnum(' ')`, `ZC_ialnum('.')` both false.
    #[test]
    fn ZC_ialnum_space_and_punct_return_false() {
        assert!(!ZC_ialnum(' '));
        assert!(!ZC_ialnum('.'));
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Zle/zle.h:60-73 ZC_* macros.
    // ═══════════════════════════════════════════════════════════════════

    /// c:62 — `ZC_iblank` is `iswspace(c) && c != '\n'` per
    /// Src/utils.c:wcsiblank. CR is iblank; newline is NOT.
    #[test]
    fn ZC_iblank_excludes_newline_only() {
        assert!(ZC_iblank(' '), "space is iblank");
        assert!(ZC_iblank('\t'), "tab is iblank");
        assert!(ZC_iblank('\r'), "CR is iblank (iswspace minus \\n)");
        assert!(ZC_iblank('\x0b'), "VT is iblank");
        assert!(ZC_iblank('\x0c'), "FF is iblank");
        assert!(!ZC_iblank('\n'), "newline explicitly excluded");
        assert!(!ZC_iblank('a'), "letter is not iblank");
    }

    /// c:67 — `ZC_inblank` is `iswspace(c)` — DOES include newline
    /// (counterpart to iblank which excludes it).
    #[test]
    fn ZC_inblank_includes_newline() {
        assert!(ZC_inblank(' '));
        assert!(ZC_inblank('\t'));
        assert!(ZC_inblank('\n'), "inblank includes newline (vs iblank)");
        assert!(ZC_inblank('\r'));
        assert!(!ZC_inblank('a'));
    }

    /// c:65 — `ZC_iident` is alphanumeric OR `_` (IIDENT class).
    #[test]
    fn ZC_iident_includes_underscore() {
        assert!(ZC_iident('_'), "underscore is iident");
        assert!(ZC_iident('a'));
        assert!(ZC_iident('5'));
        assert!(!ZC_iident('-'), "hyphen is NOT iident");
        assert!(!ZC_iident('.'));
        assert!(!ZC_iident(' '));
    }

    /// c:69 — `ZC_iword` is alphanumeric OR `_` (same as IIDENT for now).
    #[test]
    fn ZC_iword_matches_iident_for_ascii() {
        for c in &['a', 'Z', '5', '_'] {
            assert_eq!(
                ZC_iword(*c),
                ZC_iident(*c),
                "iword and iident agree on {:?}",
                c
            );
        }
    }

    /// c:63 — `ZC_icntrl` flags ASCII control chars.
    #[test]
    fn ZC_icntrl_flags_control_chars() {
        assert!(ZC_icntrl('\x00'));
        assert!(ZC_icntrl('\x01'));
        assert!(ZC_icntrl('\x1b'), "ESC is control");
        assert!(ZC_icntrl('\x7f'), "DEL is control");
        assert!(!ZC_icntrl('a'));
        assert!(!ZC_icntrl(' '));
    }

    /// c:64 — `ZC_idigit` only matches ASCII digits 0-9.
    #[test]
    fn ZC_idigit_ascii_digits_only() {
        for d in '0'..='9' {
            assert!(ZC_idigit(d), "{:?} must be digit", d);
        }
        assert!(!ZC_idigit('a'));
        assert!(!ZC_idigit(' '));
        // Unicode digit like Arabic-Indic ٠ (U+0660) — NOT ASCII so false.
        assert!(!ZC_idigit('\u{0660}'), "non-ASCII digit excluded");
    }

    /// c:66/68 — `ZC_ilower` / `ZC_iupper` agree with char::is_lowercase/upper.
    #[test]
    fn ZC_ilower_iupper_basic() {
        assert!(ZC_ilower('a'));
        assert!(!ZC_ilower('A'));
        assert!(!ZC_ilower('5'));
        assert!(ZC_iupper('A'));
        assert!(!ZC_iupper('a'));
        assert!(!ZC_iupper('5'));
    }

    /// c:70 — `ZC_ipunct` true for ASCII punct, false for letters/digits/space.
    #[test]
    fn ZC_ipunct_basic_branches() {
        assert!(ZC_ipunct('.'));
        assert!(ZC_ipunct('!'));
        assert!(ZC_ipunct(','));
        assert!(!ZC_ipunct('a'));
        assert!(!ZC_ipunct('5'));
        assert!(!ZC_ipunct(' '), "space is iblank, not ipunct");
    }

    /// c:72 — `ZC_tolower('A')` → 'a'.
    #[test]
    fn ZC_tolower_uppercase_to_lowercase() {
        assert_eq!(ZC_tolower('A'), 'a');
        assert_eq!(ZC_tolower('Z'), 'z');
        // Already lowercase stays.
        assert_eq!(ZC_tolower('a'), 'a');
        // Non-letter unchanged.
        assert_eq!(ZC_tolower('5'), '5');
        assert_eq!(ZC_tolower(' '), ' ');
    }

    /// c:73 — `ZC_toupper('a')` → 'A'.
    #[test]
    fn ZC_toupper_lowercase_to_uppercase() {
        assert_eq!(ZC_toupper('a'), 'A');
        assert_eq!(ZC_toupper('z'), 'Z');
        assert_eq!(ZC_toupper('A'), 'A');
        assert_eq!(ZC_toupper('5'), '5');
    }

    /// c:72/73 — tolower/toupper round-trip on ASCII letters.
    #[test]
    fn ZC_case_round_trip_ascii() {
        for c in 'a'..='z' {
            assert_eq!(ZC_tolower(ZC_toupper(c)), c);
        }
        for c in 'A'..='Z' {
            assert_eq!(ZC_toupper(ZC_tolower(c)), c);
        }
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Zle/zle.h ZS_* string fns.
    // ═══════════════════════════════════════════════════════════════════

    /// c:42 — `ZS_memset(dst, 'X', 3)` fills first 3 with 'X', rest untouched.
    #[test]
    fn ZS_memset_fills_n_leaves_rest() {
        let mut buf: Vec<char> = vec!['_'; 5];
        ZS_memset(&mut buf, 'X', 3);
        assert_eq!(buf, vec!['X', 'X', 'X', '_', '_']);
    }

    /// c:43 — `ZS_memcmp` equal slices → Equal.
    #[test]
    fn ZS_memcmp_equal_returns_equal_pin() {
        let a: Vec<char> = vec!['a', 'b', 'c'];
        let b: Vec<char> = vec!['a', 'b', 'c'];
        assert_eq!(ZS_memcmp(&a, &b, 3), std::cmp::Ordering::Equal);
    }

    /// c:43 — different slices return non-Equal.
    #[test]
    fn ZS_memcmp_different_returns_non_equal() {
        let a: Vec<char> = vec!['a', 'b', 'c'];
        let b: Vec<char> = vec!['a', 'b', 'd'];
        assert_ne!(ZS_memcmp(&a, &b, 3), std::cmp::Ordering::Equal);
    }

    /// c:45 — `ZS_strcpy` copies + NUL-terminates when room.
    #[test]
    fn ZS_strcpy_copies_and_nul_terminates() {
        let src: Vec<char> = vec!['h', 'i', '\0'];
        let mut dst: Vec<char> = vec!['_'; 5];
        ZS_strcpy(&mut dst, &src);
        assert_eq!(dst[0], 'h');
        assert_eq!(dst[1], 'i');
        assert_eq!(dst[2], '\0', "NUL terminator added when room");
    }

    /// c:46 — `ZS_strncpy` pads shorter src with NUL up to n.
    #[test]
    fn ZS_strncpy_pads_short_src_with_nul() {
        let src: Vec<char> = vec!['a', '\0']; // 1-char string
        let mut dst: Vec<char> = vec!['X'; 5];
        ZS_strncpy(&mut dst, &src, 4);
        assert_eq!(dst[0], 'a');
        assert_eq!(dst[1], '\0', "padded with NUL");
        assert_eq!(dst[2], '\0');
        assert_eq!(dst[3], '\0');
        // Index 4 untouched.
    }

    /// c:50 — `ZS_strchr` finds existing char.
    #[test]
    fn ZS_strchr_finds_existing() {
        let s: Vec<char> = vec!['h', 'e', 'l', 'l', 'o'];
        assert_eq!(ZS_strchr(&s, 'l'), Some(2), "first 'l' at index 2");
        assert_eq!(ZS_strchr(&s, 'h'), Some(0));
        assert_eq!(ZS_strchr(&s, 'o'), Some(4));
    }

    /// c:50 — `ZS_strchr` missing char returns None.
    #[test]
    fn ZS_strchr_missing_returns_none() {
        let s: Vec<char> = vec!['h', 'i'];
        assert_eq!(ZS_strchr(&s, 'x'), None);
        assert_eq!(ZS_strchr(&[], 'a'), None);
    }

    /// c:51 — `ZS_memchr` respects bounded length.
    #[test]
    fn ZS_memchr_bounded_by_n() {
        let s: Vec<char> = vec!['a', 'b', 'c', 'd', 'e'];
        assert_eq!(ZS_memchr(&s, 'd', 5), Some(3), "found at 3 within range 5");
        assert_eq!(ZS_memchr(&s, 'd', 3), None, "n=3 stops before 'd' at idx 3");
    }

    /// c:49 — `ZS_width` returns char count (matches ZS_strlen).
    #[test]
    fn ZS_width_matches_strlen() {
        let s: Vec<char> = vec!['a', 'b', 'c', '\0'];
        assert_eq!(ZS_width(&s), ZS_strlen(&s));
    }

    /// c:40 — `ZS_memcpy` does NOT overflow dst when n < dst.len().
    #[test]
    fn ZS_memcpy_respects_n_bound() {
        let src: Vec<char> = vec!['a', 'b', 'c', 'd', 'e'];
        let mut dst: Vec<char> = vec!['_'; 5];
        ZS_memcpy(&mut dst, &src, 3);
        assert_eq!(dst[0], 'a');
        assert_eq!(dst[1], 'b');
        assert_eq!(dst[2], 'c');
        assert_eq!(dst[3], '_', "untouched past n");
        assert_eq!(dst[4], '_');
    }

    /// c:47 — `ZS_strncmp` of "ab" vs "ab" with n=2 returns Equal.
    #[test]
    fn ZS_strncmp_equal_bounded() {
        let a: Vec<char> = vec!['a', 'b', '\0'];
        let b: Vec<char> = vec!['a', 'b', '\0'];
        assert_eq!(ZS_strncmp(&a, &b, 2), std::cmp::Ordering::Equal);
    }

    /// c:47 — `ZS_strncmp("abc", "abd", 2)` Equal (both stop at idx 2).
    #[test]
    fn ZS_strncmp_n_clamps_comparison() {
        let a: Vec<char> = vec!['a', 'b', 'c', '\0'];
        let b: Vec<char> = vec!['a', 'b', 'd', '\0'];
        assert_eq!(ZS_strncmp(&a, &b, 2), std::cmp::Ordering::Equal);
        // With n=3, differs.
        assert_ne!(ZS_strncmp(&a, &b, 3), std::cmp::Ordering::Equal);
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Zle/zle.h
    // c:34 ZLE_CHAR_SIZE / c:37 ZLEEOF / c:71 Th / c:122 invicmdmode /
    // c:155 ZS_memset / c:225 ZS_strchr / c:233 ZS_memchr / c:242 ZS_width /
    // c:256-303 ZC_* classifiers
    // ═══════════════════════════════════════════════════════════════════

    /// c:34 — `ZLE_CHAR_SIZE` is 4 (per Unicode codepoint size).
    #[test]
    fn zle_char_size_is_four() {
        assert_eq!(ZLE_CHAR_SIZE, 4, "wide-char size is 4 bytes");
    }

    /// c:37 — `ZLEEOF` is -1 (WEOF sentinel).
    #[test]
    fn zleeof_is_minus_one() {
        assert_eq!(ZLEEOF, -1, "WEOF sentinel = -1");
    }

    /// c:71 — `Th(-1)` returns None (out-of-range index).
    #[test]
    fn th_negative_index_returns_none() {
        let _g = crate::test_util::global_state_lock();
        let _g2 = zle_test_setup();
        assert!(Th(-1).is_none());
    }

    /// c:71 — `Th(99999)` returns None (far-out-of-range index).
    #[test]
    fn th_huge_index_returns_none() {
        let _g = crate::test_util::global_state_lock();
        let _g2 = zle_test_setup();
        assert!(Th(99999).is_none());
    }

    /// c:122 — `invicmdmode("emacs")` returns false.
    #[test]
    fn invicmdmode_emacs_returns_false() {
        assert!(!invicmdmode("emacs"), "emacs keymap is NOT vi cmd mode");
    }

    /// c:122 — `invicmdmode("vicmd")` returns true.
    #[test]
    fn invicmdmode_vicmd_returns_true() {
        assert!(invicmdmode("vicmd"), "vicmd keymap IS vi cmd mode");
    }

    /// c:122 — `invicmdmode("")` returns false.
    #[test]
    fn invicmdmode_empty_returns_false() {
        assert!(!invicmdmode(""), "empty keymap is NOT vi cmd mode");
    }

    /// c:155 — `ZS_memset(empty, _, 0)` is safe.
    #[test]
    fn zs_memset_zero_n_empty_buf_safe() {
        let mut empty: Vec<char> = vec![];
        ZS_memset(&mut empty, 'x', 0);
        assert!(empty.is_empty());
    }

    /// c:225 — `ZS_strchr(empty, _)` returns None.
    #[test]
    fn zs_strchr_empty_returns_none() {
        let empty: Vec<char> = vec![];
        assert_eq!(ZS_strchr(&empty, 'a'), None);
    }

    /// c:233 — `ZS_memchr(empty, _, 0)` returns None.
    #[test]
    fn zs_memchr_empty_zero_n_returns_none() {
        let empty: Vec<char> = vec![];
        assert_eq!(ZS_memchr(&empty, 'a', 0), None);
    }

    /// c:242 — `ZS_width(empty)` returns 0.
    #[test]
    fn zs_width_empty_returns_zero() {
        let empty: Vec<char> = vec![];
        assert_eq!(ZS_width(&empty), 0);
    }

    /// c:256-303 — ZC_* classifiers pure for ASCII range.
    #[test]
    fn zc_classifiers_pure_for_ascii() {
        for c in ['a', 'A', '0', ' ', '\t', '\n', '!'] {
            let first_alpha = ZC_ialpha(c);
            let first_digit = ZC_idigit(c);
            for _ in 0..3 {
                assert_eq!(ZC_ialpha(c), first_alpha, "ZC_ialpha({:?}) must be pure", c);
                assert_eq!(ZC_idigit(c), first_digit, "ZC_idigit({:?}) must be pure", c);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Zle/zle.h
    // c:122 invicmdmode / c:155 ZS_memset / c:225 ZS_strchr /
    // c:233 ZS_memchr / c:242 ZS_width / c:256-303 ZC_* classifiers
    // ═══════════════════════════════════════════════════════════════════

    /// c:122 — `invicmdmode` returns bool (compile-time pin).
    #[test]
    fn invicmdmode_returns_bool_type() {
        let _: bool = invicmdmode("emacs");
    }

    /// c:122 — `invicmdmode` deterministic across keymap names.
    #[test]
    fn invicmdmode_deterministic() {
        for name in ["emacs", "vicmd", "viins", "", "anything"] {
            let first = invicmdmode(name);
            for _ in 0..3 {
                assert_eq!(
                    invicmdmode(name),
                    first,
                    "invicmdmode({:?}) must be pure",
                    name
                );
            }
        }
    }

    /// c:155 — `ZS_memset` actually fills the buffer.
    #[test]
    fn zs_memset_fills_buffer() {
        let mut buf: Vec<char> = vec!['a', 'a', 'a', 'a'];
        ZS_memset(&mut buf, 'X', 4);
        assert_eq!(
            buf,
            vec!['X', 'X', 'X', 'X'],
            "ZS_memset must fill all 4 slots with 'X'"
        );
    }

    /// c:225 — `ZS_strchr` finds present char.
    #[test]
    fn zs_strchr_finds_present_char() {
        let buf: Vec<char> = "hello".chars().collect();
        let r = ZS_strchr(&buf, 'l');
        assert!(r.is_some(), "must find 'l' in 'hello'");
    }

    /// c:225 — `ZS_strchr` for absent char returns None.
    #[test]
    fn zs_strchr_absent_char_returns_none() {
        let buf: Vec<char> = "hello".chars().collect();
        assert_eq!(ZS_strchr(&buf, 'z'), None, "'z' not in 'hello' → None");
    }

    /// c:233 — `ZS_memchr` with n=0 always returns None.
    #[test]
    fn zs_memchr_zero_n_always_returns_none() {
        for buf in [vec!['a', 'b', 'c'], vec!['x']] {
            assert_eq!(
                ZS_memchr(&buf, 'a', 0),
                None,
                "n=0 search → None regardless of buffer content"
            );
        }
    }

    /// c:242 — `ZS_width` for ASCII returns count.
    #[test]
    fn zs_width_ascii_matches_char_count() {
        for s in ["", "x", "hello", "12345"] {
            let buf: Vec<char> = s.chars().collect();
            let w = ZS_width(&buf);
            assert_eq!(
                w as usize,
                s.chars().count(),
                "ASCII '{}' width = char count",
                s
            );
        }
    }

    /// c:256-303 — `ZC_ialpha` returns bool (compile-time pin).
    #[test]
    fn zc_ialpha_returns_bool_type() {
        let _: bool = ZC_ialpha('a');
    }

    /// c:256-303 — `ZC_idigit` returns bool (compile-time pin).
    #[test]
    fn zc_idigit_returns_bool_type() {
        let _: bool = ZC_idigit('0');
    }

    /// c:256-303 — `ZC_ialpha` correctly classifies basic ASCII.
    #[test]
    fn zc_ialpha_basic_ascii_classification() {
        assert!(ZC_ialpha('a'), "'a' is alpha");
        assert!(ZC_ialpha('Z'), "'Z' is alpha");
        assert!(!ZC_ialpha('0'), "'0' is NOT alpha");
        assert!(!ZC_ialpha(' '), "' ' is NOT alpha");
    }

    /// c:256-303 — `ZC_idigit` correctly classifies basic ASCII.
    #[test]
    fn zc_idigit_basic_ascii_classification() {
        assert!(ZC_idigit('0'), "'0' is digit");
        assert!(ZC_idigit('9'), "'9' is digit");
        assert!(!ZC_idigit('a'), "'a' is NOT digit");
        assert!(!ZC_idigit(' '), "' ' is NOT digit");
    }

    /// c:71 — `Th` returns None for negative + MIN (alt pin).
    #[test]
    fn th_negative_alt_pin() {
        let _g = crate::test_util::global_state_lock();
        let _g2 = zle_test_setup();
        for idx in [-1, -100, i32::MIN] {
            assert!(Th(idx).is_none(), "Th({}) must be None", idx);
        }
    }
}