zshrs 0.11.0

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
//! ZLE tricky - completion and expansion widgets
//!
//! Direct port from zsh/Src/Zle/zle_tricky.c
//!
//! Implements completion widgets:
//! - complete-word, menu-complete, reverse-menu-complete
//! - expand-or-complete, expand-or-complete-prefix
//! - list-choices, list-expand
//! - expand-word, expand-history
//! - spell-word, delete-char-or-list
//! - magic-space, accept-and-menu-complete

use std::sync::atomic::AtomicI32;

use crate::ported::zsh_h::{isset, GLOBCOMPLETE, MENUCOMPLETE, RECEXACT};

// =====================================================================
// Globals — `Src/Zle/zle_tricky.c:96-106`.
// =====================================================================
//
// usemenu/useglob — controls type of completion (set by entry widget,
// read by `docomplete`/`callcompfunc`). usemenu==2 starts automenu;
// usemenu==3 inserts as if for menucomp without really starting it.
// wouldinstab — non-zero if we'd insert TAB but for the comp widget.

/// Port of `mod_export int usemenu` from `Src/Zle/zle_tricky.c:96`.

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

pub static USEMENU: AtomicI32 = AtomicI32::new(0);                           // c:96

/// Port of `mod_export int useglob` from `Src/Zle/zle_tricky.c:96`.
pub static USEGLOB: AtomicI32 = AtomicI32::new(0);                           // c:96

/// Port of `mod_export int wouldinstab` from `Src/Zle/zle_tricky.c:101`.
pub static WOULDINSTAB: AtomicI32 = AtomicI32::new(0);                       // c:101

/// Port of `mod_export int nbrbeg` from `Src/Zle/zle_tricky.c:114`.
/// Number of opened braces seen in the current word during completion.
pub static NBRBEG: AtomicI32 = AtomicI32::new(0);                            // c:114
/// Port of `mod_export int nbrend` from `Src/Zle/zle_tricky.c:114`.
pub static NBREND: AtomicI32 = AtomicI32::new(0);                            // c:114

/// Port of `mod_export int origcs` from `Src/Zle/zle_tricky.c:75`.
/// Cursor position saved at completion entry.
pub static ORIGCS: AtomicI32 = AtomicI32::new(0);                            // c:75
/// Port of `mod_export int origll` from `Src/Zle/zle_tricky.c:75`.
/// Line length saved at completion entry.
pub static ORIGLL: AtomicI32 = AtomicI32::new(0);                            // c:75

/// Port of `mod_export int insubscr` from `Src/Zle/zle_tricky.c:405`.
/// != 0 if we are inside `${name[...]}` or `${(P)name[...]}`.
pub static INSUBSCR: AtomicI32 = AtomicI32::new(0);                          // c:405

/// Port of `mod_export int instring` from `Src/Zle/zle_tricky.c:419`.
/// QT_NONE (0), QT_SINGLE, QT_DOUBLE, QT_DOLLARS, or QT_BACKSLASH.
pub static INSTRING: AtomicI32 = AtomicI32::new(0);                          // c:419
/// Port of `mod_export int inbackt` from `Src/Zle/zle_tricky.c:419`.
pub static INBACKT: AtomicI32 = AtomicI32::new(0);                           // c:419

/// Port of `mod_export char *origline` from `Src/Zle/zle_tricky.c`.
/// The metafied line saved at completion entry.
pub static ORIGLINE: std::sync::OnceLock<std::sync::Mutex<String>> =
    std::sync::OnceLock::new();                                              // zle_tricky.c

/// Port of `mod_export char *lastprebr` from `Src/Zle/zle_tricky.c`.
pub static LASTPREBR: std::sync::OnceLock<std::sync::Mutex<String>> =
    std::sync::OnceLock::new();                                              // zle_tricky.c
/// Port of `mod_export char *lastpostbr` from `Src/Zle/zle_tricky.c`.
pub static LASTPOSTBR: std::sync::OnceLock<std::sync::Mutex<String>> =
    std::sync::OnceLock::new();                                              // zle_tricky.c

/// Port of `mod_export char *compquote` from `Src/Zle/zle_tricky.c`.
/// `$compstate[quote]` — current quoting context character.
pub static COMPQUOTE: std::sync::OnceLock<std::sync::Mutex<String>> =
    std::sync::OnceLock::new();                                              // zle_tricky.c
/// Port of `mod_export char *autoq` from `Src/Zle/zle_tricky.c`.
pub static AUTOQ: std::sync::OnceLock<std::sync::Mutex<String>> =
    std::sync::OnceLock::new();                                              // zle_tricky.c

/// Port of `mod_export int menucmp` from `Src/Zle/zle_tricky.c:106`.
/// Non-zero while inside a menu-completion sequence.
pub static MENUCMP: AtomicI32 = AtomicI32::new(0);                           // c:106

/// Port of `int comppref` from `Src/Zle/zle_tricky.c`. Set to 1 by
/// `expandorcompleteprefix` so completion treats only the part of
/// the word up to the cursor as the prefix.
pub static COMPPREF: AtomicI32 = AtomicI32::new(0);                          // c:78

/// Port of `mod_export int validlist` from `Src/Zle/zle_tricky.c:122`.
/// Non-zero when the cached list of completion matches is still
/// usable (didn't fall victim to a `clearlist` / `invalidate_list`).
pub static VALIDLIST: AtomicI32 = AtomicI32::new(0);                         // c:122

/// Port of `mod_export int showagain` from `Src/Zle/zle_tricky.c:127`.
/// Set by `comp_list` when the user re-asks for the same list — drives
/// the "redraw without re-running compfunc" branch in `before_complete`.
pub static SHOWAGAIN: AtomicI32 = AtomicI32::new(0);                         // c:127

/// Port of `mod_export int lastambig` from `Src/Zle/zle_tricky.c:157`.
/// Sticky flag set when the last completion left the line in an
/// ambiguous state — drives automenu kick-in via `before_complete`.
pub static LASTAMBIG: AtomicI32 = AtomicI32::new(0);                         // c:157

/// Port of `mod_export int bashlistfirst` from
/// `Src/Zle/zle_tricky.c:157`. Sets the listing style.
pub static BASHLISTFIRST: AtomicI32 = AtomicI32::new(0);                     // c:157

/// Port of `mod_export int amenu` from `Src/Zle/zle_tricky.c`. Set
/// non-zero while a menu-completion is in progress — drives the
/// list-with-cursor refresh path.
pub static AMENU: AtomicI32 = AtomicI32::new(0);                             // c:zle_tricky.c

// `CompletionState` struct deleted — Rust-invented state container
// with no C counterpart. C uses file-static globals (`compcontext`,
// `compfunc`, `usemenu`, `useglob`, brbeg/brend, etc.) for the same
// data, not a passed struct. The Rust port's old `impl Zle` methods
// (since dissolved into free fns) that took `&mut CompletionState`
// (complete_word/menu_complete/
// reverse_menu_complete/expand_or_complete/expand_or_complete_prefix/
// list_choices/delete_char_or_list/accept_and_menu_complete + their
// do_complete/apply_completion/get_word_bounds/try_expand/do_expansion/
// do_expand_hist/get_completions helpers) were also Rust-only
// simplified stand-alones — they didn't match C signatures and had
// no external callers. The real C-faithful ports (completeword,
// menucomplete, deletecharorlist, docomplete, docompletion, etc.)
// already live as `pub fn` at file scope below; they read/write the
// C globals directly.

// `BraceInfo` deleted — Rust-invented `{ str_val, pos, cur_pos,
// qpos, curlen }` struct that wasn't referenced anywhere (dead
// code). C uses the legit `struct brinfo` at zle.h:368 (ported in
// zle_h.rs:528) for brace-expansion bookkeeping during completion.


/// Meta character for zsh's internal encoding (0x83)
pub const META: char = '\u{83}';

/// Metafy a line (escape special chars)
/// Port of metafy_line() from zle_tricky.c
pub fn metafy_line(s: &str) -> String {                                      // c:978
    let mut result = String::with_capacity(s.len() * 2);
    for c in s.chars() {
        if c == META || (c as u32) >= 0x83 {
            result.push(META);
            result.push(char::from_u32((c as u32) ^ 32).unwrap_or(c));
        } else {
            result.push(c);
        }
    }
    result
}

/// Unmetafy a line (unescape special chars)
/// Port of unmetafy_line() from zle_tricky.c
pub fn unmetafy_line(s: &str) -> String {                                    // c:995
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == META {
            if let Some(&next) = chars.peek() {
                chars.next();
                result.push(char::from_u32((next as u32) ^ 32).unwrap_or(next));
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Check if string has real tokens (not escaped)
/// Port of has_real_token(const char *s) from zle_tricky.c
pub fn has_real_token(s: &str) -> bool {
    let special = ['$', '`', '"', '\'', '\\', '{', '}', '[', ']', '*', '?', '~'];

    let mut escaped = false;
    for c in s.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        if c == '\\' {
            escaped = true;
            continue;
        }
        if special.contains(&c) {
            return true;
        }
    }

    false
}

/// Get length of common prefix
/// Port of pfxlen(char *s, char *t) from zle_tricky.c
pub fn pfxlen(s1: &str, s2: &str) -> usize {                                 // c:2359
    s1.chars()
        .zip(s2.chars())
        .take_while(|(a, b)| a == b)
        .count()
}

/// Get length of common suffix
/// Port of sfxlen(char *s, char *t) from zle_tricky.c
pub fn sfxlen(s1: &str, s2: &str) -> usize {                                 // c:2411
    s1.chars()
        .rev()
        .zip(s2.chars().rev())
        .take_while(|(a, b)| a == b)
        .count()
}

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

    #[test]
    fn test_pfxlen() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(pfxlen("hello", "help"), 3);
        assert_eq!(pfxlen("abc", "xyz"), 0);
        assert_eq!(pfxlen("test", "test"), 4);
    }

    #[test]
    fn test_sfxlen() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(sfxlen("testing", "running"), 3);
        assert_eq!(sfxlen("abc", "xyz"), 0);
    }

    #[test]
    fn addx_skips_when_cursor_in_middle_of_word() {
        // c:949-952 — when the char at cursor is a normal word-char
        //              (not separator/quote/blank/eol), addx must NOT
        //              insert anything; addedx → 0, *ptmp → NULL.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;
        use crate::ported::zle::zle_main::{ZLECS, ZLELINE, ZLELL};
        use crate::ported::zle::compcore::ADDEDX;

        *ZLELINE.lock().unwrap() = "hello".chars().collect();
        ZLECS.store(2, Ordering::SeqCst);                 // cursor on 'l'
        ZLELL.store(5, Ordering::SeqCst);
        INSTRING.store(crate::ported::zsh_h::QT_NONE, Ordering::SeqCst);
        COMPPREF.store(0, Ordering::SeqCst);
        ADDEDX.store(99, Ordering::SeqCst);               // sentinel

        let mut snap = String::new();
        let added = addx(&mut snap);
        assert_eq!(added, 0, "no insertion when cursor lands on word-char");
        assert_eq!(ADDEDX.load(Ordering::SeqCst), 0);
        assert!(snap.is_empty(), "ptmp must be NULL/empty when addx doesn't fire");
        assert_eq!(
            ZLELINE.lock().unwrap().iter().collect::<String>(),
            "hello",
            "buffer must be untouched"
        );
    }

    #[test]
    fn addx_inserts_at_end_of_line() {
        // c:937-947 — cursor at end-of-line → insert 'x', addedx=1.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;
        use crate::ported::zle::zle_main::{ZLECS, ZLELINE, ZLELL};
        use crate::ported::zle::compcore::ADDEDX;

        *ZLELINE.lock().unwrap() = "abc".chars().collect();
        ZLECS.store(3, Ordering::SeqCst);                 // cursor past end
        ZLELL.store(3, Ordering::SeqCst);
        INSTRING.store(crate::ported::zsh_h::QT_NONE, Ordering::SeqCst);
        COMPPREF.store(0, Ordering::SeqCst);

        let mut snap = String::new();
        let added = addx(&mut snap);
        assert_eq!(added, 1, "exactly one 'x' inserted at EOL");
        assert_eq!(ADDEDX.load(Ordering::SeqCst), 1);
        assert_eq!(snap, "abc", "snapshot is pre-edit buffer");
        assert_eq!(
            ZLELINE.lock().unwrap().iter().collect::<String>(),
            "abcx"
        );
    }

    #[test]
    fn addx_inserts_x_space_when_comppref_on_nonblank() {
        // c:936 + c:945-946 — comppref + non-blank at cursor →
        //                      insert "x ", addedx=2.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;
        use crate::ported::zle::zle_main::{ZLECS, ZLELINE, ZLELL};
        use crate::ported::zle::compcore::ADDEDX;

        *ZLELINE.lock().unwrap() = "ab".chars().collect();
        ZLECS.store(1, Ordering::SeqCst);                 // on 'b'
        ZLELL.store(2, Ordering::SeqCst);
        INSTRING.store(crate::ported::zsh_h::QT_NONE, Ordering::SeqCst);
        COMPPREF.store(1, Ordering::SeqCst);

        let mut snap = String::new();
        let added = addx(&mut snap);
        assert_eq!(added, 2, "comppref non-blank → 'x ' (2 chars)");
        assert_eq!(ADDEDX.load(Ordering::SeqCst), 2);
        // Reset for siblings.
        COMPPREF.store(0, Ordering::SeqCst);
    }

    #[test]
    fn addx_inserts_when_cursor_on_separator() {
        // c:929-933 — ')' / '|' / '&' / '>' / '<' etc. → insert.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;
        use crate::ported::zle::zle_main::{ZLECS, ZLELINE, ZLELL};

        *ZLELINE.lock().unwrap() = "echo|".chars().collect();
        ZLECS.store(4, Ordering::SeqCst);                 // on '|'
        ZLELL.store(5, Ordering::SeqCst);
        INSTRING.store(crate::ported::zsh_h::QT_NONE, Ordering::SeqCst);
        COMPPREF.store(0, Ordering::SeqCst);

        let mut snap = String::new();
        let added = addx(&mut snap);
        assert_eq!(added, 1, "separator at cursor → insert 'x'");
    }

    #[test]
    fn checkparams_hascompmod_gate() {
        // c:447-448 — `!menucmp && exact && (!hascompmod || RECEXACT)`.
        //              When hascompmod is true and RECEXACT is unset,
        //              the function must return 0 even on an exact
        //              prefix match with multiple candidates.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;

        // Seed paramtab with two params: "abc" + "abcd".
        crate::ported::params::setsparam("abc",  "v1");
        crate::ported::params::setsparam("abcd", "v2");
        MENUCMP.store(0, Ordering::SeqCst);
        crate::ported::zle::zle_main::HASCOMPMOD.store(true, Ordering::SeqCst);
        // RECEXACT is an OPT_*; unsetopt via flip().
        crate::ported::zle::zle_main::HASCOMPMOD.store(true, Ordering::SeqCst);

        // With hascompmod=true and RECEXACT presumed-off, gate closes.
        // (We can't easily flip OPT_RECEXACT here without disturbing
        // global option state; the assertion below verifies the
        // !hascompmod escape — set hascompmod=false → gate opens.)
        crate::ported::zle::zle_main::HASCOMPMOD.store(false, Ordering::SeqCst);
        assert_eq!(checkparams("abc"), 1,
                   "with !hascompmod, exact + non-menu → return 1");

        // Reset hascompmod for siblings.
        crate::ported::zle::zle_main::HASCOMPMOD.store(false, Ordering::SeqCst);
        // Cleanup params.
        crate::ported::params::setsparam("abc", "");
        crate::ported::params::setsparam("abcd", "");
    }

    #[test]
    fn test_has_real_token() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert!(has_real_token("$HOME"));
        assert!(has_real_token("*.txt"));
        assert!(!has_real_token("hello"));
        assert!(!has_real_token("test\\$var")); // escaped
    }

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

    #[test]
    fn dupstrspace_appends_space() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:954 — len + 1 + 1 NUL: "hello" → "hello "
        assert_eq!(dupstrspace("hello"), "hello ");
    }

    #[test]
    fn dupstrspace_empty_input() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:954 — empty input → just a single space
        assert_eq!(dupstrspace(""), " ");
    }

    #[test]
    fn freebrinfo_drops_chain() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use crate::ported::zle::zle_h::brinfo;
        // c:1015 — Box drop cascades through `next`.
        let head = Some(Box::new(brinfo {
            next: Some(Box::new(brinfo {
                next: None,
                prev: None,
                str: "second".into(),
                pos: 7,
                qpos: 8,
                curpos: 9,
            })),
            prev: None,
            str: "first".into(),
            pos: 1,
            qpos: 2,
            curpos: 3,
        }));
        // freebrinfo just consumes — no panic, drop succeeds.
        freebrinfo(head);
    }

    #[test]
    fn dupbrinfo_clones_chain() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use crate::ported::zle::zle_h::brinfo;
        // Build a 3-node chain: A → B → C.
        let src = Box::new(brinfo {
            next: Some(Box::new(brinfo {
                next: Some(Box::new(brinfo {
                    next: None,
                    prev: None,
                    str: "C".into(),
                    pos: 30,
                    qpos: 31,
                    curpos: 32,
                })),
                prev: None,
                str: "B".into(),
                pos: 20,
                qpos: 21,
                curpos: 22,
            })),
            prev: None,
            str: "A".into(),
            pos: 10,
            qpos: 11,
            curpos: 12,
        });
        let (head, last) = dupbrinfo(Some(&*src));
        assert!(last.is_some());
        let h = head.as_ref().unwrap();
        // c:1043-1046 — fields copied verbatim.
        assert_eq!(h.str, "A");
        assert_eq!(h.pos, 10);
        assert_eq!(h.qpos, 11);
        assert_eq!(h.curpos, 12);
        let n = h.next.as_ref().unwrap();
        assert_eq!(n.str, "B");
        assert_eq!(n.pos, 20);
        let n = n.next.as_ref().unwrap();
        assert_eq!(n.str, "C");
        assert_eq!(n.pos, 30);
        assert!(n.next.is_none());
    }

    #[test]
    fn dupbrinfo_empty_returns_none() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:1037 — `while (p)` never enters; ret stays NULL.
        let (head, last) = dupbrinfo(None);
        assert!(head.is_none());
        assert!(last.is_none());
    }

    #[test]
    fn spellword_zeroes_globals_returns_docomplete() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        use std::sync::atomic::Ordering;
        // Pre-set non-zero so the c:263 reset is observable.
        USEMENU.store(99, Ordering::SeqCst);
        USEGLOB.store(99, Ordering::SeqCst);
        WOULDINSTAB.store(99, Ordering::SeqCst);
        let r = spellword();
        // c:265 — `return docomplete(COMP_SPELL)`. docomplete() is
        // currently a stub returning 0 — verify pass-through.
        assert_eq!(r, 0);
        // c:263 — both zeroed.
        assert_eq!(USEMENU.load(Ordering::SeqCst), 0);
        assert_eq!(USEGLOB.load(Ordering::SeqCst), 0);
        // c:264 — wouldinstab cleared.
        assert_eq!(WOULDINSTAB.load(Ordering::SeqCst), 0);
    }
}

/// Port of `acceptandmenucomplete(char **args)` from Src/Zle/zle_tricky.c:353.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn acceptandmenucomplete() -> i32 {                                      // c:353
    use std::sync::atomic::Ordering;
    // C body c:355-369 — `if (!menucmp) return 1;
    //                     do_menucmp(0); menucmp = 2; ... menucomplete()`.
    if MENUCMP.load(Ordering::SeqCst) == 0 {
        return 1;
    }
    MENUCMP.store(2, Ordering::SeqCst);
    docomplete(crate::ported::zle::zle_h::COMP_COMPLETE)
}

/// Port of `addx(char **ptmp)` from Src/Zle/zle_tricky.c:922.
/// WARNING: param names don't match C — Rust=(zle, ptmp) vs C=(ptmp)
/// Direct port of `void addx(char **ptmp)` from
/// `Src/Zle/zle_tricky.c:922`. Conditionally inserts an 'x'
/// placeholder at the ZLE cursor so the parser sees a complete word
/// at completion time. The condition only fires when the char at the
/// cursor would terminate / split the word (whitespace, separators,
/// closing brackets, end-of-line, quote inside-string, or comppref
/// mode landing on a non-blank).
///
/// Rust signature: returns `*ptmp` as a Result-ish `Option<String>`
/// snapshot of the pre-edit buffer when addx fires; None when it
/// doesn't. Side effects: mutates `ZLELINE`, stores the insertion
/// length (1 or 2) in `ADDEDX`. The `int` return value mirrors C's
/// implicit return (its return type is `void`; the i32 conveys
/// `addedx` for callers that want it without a global read).
pub fn addx(ptmp: &mut String) -> i32 {                                       // c:922
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_main::{ZLECS, ZLELINE, ZLELL};
    use crate::ported::zsh_h::QT_NONE;
    use crate::ported::zle::compcore::ADDEDX;

    let cs = ZLECS.load(Ordering::SeqCst) as usize;
    let ll = ZLELL.load(Ordering::SeqCst) as usize;
    let instring = INSTRING.load(Ordering::SeqCst);
    let comppref = COMPPREF.load(Ordering::SeqCst) != 0;

    // Read the char at the cursor (and previous, for the iblank gate).
    let (ch_at, prev_at): (Option<char>, Option<char>) = {
        let line = ZLELINE.lock().unwrap();
        let at = line.get(cs).copied();
        let prev = if cs > 0 { line.get(cs - 1).copied() } else { None };
        (at, prev)
    };

    // c:924 — `iblank` in C tests space/tab (not '\n'). c:923's
    // outer check splits '\n' off as its own arm, so the iblank
    // gate proper is space/tab only.
    let is_iblank = matches!(ch_at, Some(' ' | '\t'));
    let is_blank_unescaped = is_iblank
        && (cs == 0 || prev_at != Some('\\'));                               // c:927-928

    // c:924-936 — the full insertion gate.
    let cs_at_end = ch_at.is_none() || cs >= ll;
    let is_newline = ch_at == Some('\n');                                    // c:925
    let is_separator = matches!(ch_at,
        Some(')' | '`' | '}' | ';' | '|' | '&' | '>' | '<'));                // c:929-933
    let is_instring_quote = instring != QT_NONE                              // c:934-935
        && matches!(ch_at, Some('"' | '\''));
    let addspace = comppref                                                  // c:936
        && ch_at.is_some()
        && !matches!(ch_at, Some(' ' | '\t'));

    let fire = cs_at_end || is_newline || is_blank_unescaped
        || is_separator || is_instring_quote || addspace;

    if fire {
        // c:937-946 — snapshot, insert 'x' (+ optional ' '), set addedx.
        let snap: String = ZLELINE.lock().unwrap().iter().collect();
        *ptmp = snap;
        let mut line = ZLELINE.lock().unwrap();
        // c:944 — `zlemetaline[zlemetacs] = 'x';`
        line.insert(cs, 'x');
        if addspace {
            // c:945-946 — `zlemetaline[zlemetacs+1] = ' ';`
            line.insert(cs + 1, ' ');
        }
        drop(line);
        // c:947 — `addedx = 1 + addspace;`
        let added = if addspace { 2 } else { 1 };
        ADDEDX.store(added, Ordering::SeqCst);
        // Keep ZLELL consistent with the insertion.
        ZLELL.fetch_add(added as usize, Ordering::SeqCst);
        added
    } else {
        // c:949-952 — `addedx = 0; *ptmp = NULL;`
        ADDEDX.store(0, Ordering::SeqCst);
        ptmp.clear();
        0
    }
}

/// Port of `checkparams(char *p)` from Src/Zle/zle_tricky.c:435.
pub fn checkparams(p: &str) -> i32 {                                         // c:435
    use std::sync::atomic::Ordering;
    // C body c:437-449:
    //   - scanhashtable(paramtab) for names with `pfxlen(p, nam) == l`
    //   - count up to 2, track exact-match
    //   - n == 1   → getsparam(p) != NULL
    //   - n != 1   → !menucmp && exact && (!hascompmod || isset(RECEXACT))
    //
    // `pfxlen(p, nam) == l` means all of `p` is a prefix of `nam`,
    // i.e. `nam.starts_with(p)`. Rust port reads paramtab directly.
    let l = p.len();
    let mut n = 0;
    let mut exact = false;
    if let Ok(tab) = crate::ported::params::paramtab().read() {              // c:437
        for name in tab.keys() {                                             // c:438 walk nodes
            if name.starts_with(p) {                                         // c:439 pfxlen == l
                n += 1;                                                      // c:440
                if name.len() == l {                                         // c:441
                    exact = true;                                            // c:442
                }
                if n >= 2 {                                                  // c:438 n < 2 gate
                    break;
                }
            }
        }
    }
    if n == 1 {                                                              // c:446
        return if crate::ported::params::getsparam(p).is_some() { 1 } else { 0 };
    }
    // c:447-448 — `!menucmp && e && (!hascompmod || isset(RECEXACT))`.
    let menucmp = MENUCMP.load(Ordering::SeqCst) != 0;
    let hascompmod = crate::ported::zle::zle_main::HASCOMPMOD
        .load(Ordering::SeqCst);
    let recexact = isset(RECEXACT);
    if !menucmp && exact && (!hascompmod || recexact) {                      // c:448
        1
    } else {
        0
    }
}

/// Port of `cmphaswilds(char *str)` from Src/Zle/zle_tricky.c:457.
pub fn cmphaswilds(str: &str) -> i32 {                                         // c:457
    // C body c:459-481 — Inbrack/Outbrack as standalone return 0;
    //                    skip leading "%?"; scan for any unescaped
    //                    glob meta. We approximate "glob meta" as
    //                    `* ? [`.
    let bytes = str.as_bytes();
    if bytes.len() == 1 && (bytes[0] == b'[' || bytes[0] == b']') {
        return 0;
    }
    let mut idx = 0;
    if bytes.len() >= 2 && bytes[0] == b'%' && bytes[1] == b'?' {
        idx = 2;
    }
    let mut esc = false;
    while idx < bytes.len() {
        let c = bytes[idx];
        if esc {
            esc = false;
        } else if c == b'\\' {
            esc = true;
        } else if c == b'*' || c == b'?' || c == b'[' {
            return 1;
        }
        idx += 1;
    }
    0
}

/// Port of `completecall(char **args)` from Src/Zle/zle_tricky.c:202.
pub fn completecall(args: &[String]) -> i32 {                                // c:202
    // C body c:204-211 — `cfargs = args; cfret = 0;
    //                     compfunc = compwidget->u.comp.func;
    //                     if (compwidget->u.comp.fn(zlenoargs) && !cfret)
    //                         cfret = 1;
    //                     compfunc = NULL; return cfret`.
    // Without compwidget bound this dispatches to docomplete with the
    // default COMP_COMPLETE type so user-defined completion widgets
    // still cause a completion attempt.
    docomplete(crate::ported::zle::zle_h::COMP_COMPLETE)
}

/// Port of `completeword(char **args)` from Src/Zle/zle_tricky.c:216.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn completeword() -> i32 {                                               // c:216
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::{COMP_COMPLETE, COMP_LIST_COMPLETE};
    USEMENU.store(0, Ordering::SeqCst);                                      // c:218
    USEGLOB.store(1, Ordering::SeqCst);                                      // c:219
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:220
    // c:221-222 — `if (lastchar == '\t' && usetab()) return selfinsert()`.
    //              No live key state here; fall through to docomplete.
    docomplete(COMP_COMPLETE).max(COMP_LIST_COMPLETE - COMP_LIST_COMPLETE)
}

/// Port of `deletecharorlist(char **args)` from Src/Zle/zle_tricky.c:270.
pub fn deletecharorlist() -> i32 { // c:270
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_LIST_COMPLETE;
    USEMENU.store(0, Ordering::SeqCst);                                      // c:273
    USEGLOB.store(1, Ordering::SeqCst);                                      // c:274
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:275
    // c:277-279 — `if (zlecs == zlell) return docomplete(COMP_LIST_COMPLETE);
    //              else deletechar()`.
    if crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) == crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst) {
        docomplete(COMP_LIST_COMPLETE)
    } else {
        crate::ported::zle::zle_misc::deletechar()
    }
}

// The main entry point for completion.                                     // c:599
/// Port of `docomplete(int lst)` from Src/Zle/zle_tricky.c:599.
/// `lst` is `COMP_*` from `zle_h.rs`. The full body — c:602-2200 —
/// drives the entire completion engine: makecommaspecial, get_comp_string,
/// doexpansion, docompletion, after_complete_cleanup, etc. Without that
/// substrate the entry point can't actually complete; we accept the
/// `lst` arg for sig parity and return 0 so wrappers compile.
pub fn docomplete(lst: i32) -> i32 {                                         // c:599
    let _ = lst;
    0
}

/// Port of `docompletion(char *s, int lst, int incmd)` from Src/Zle/zle_tricky.c:2339.
/// Direct port of `int docompletion(...)` from
/// `Src/Zle/zle_tricky.c:2339`. Main driver after
/// `get_comp_string`: builds the Cmatch list via callcompfunc/
/// compfunc, sorts via matchcmp, picks insertion via do_single/
/// do_listing, updates cursor.
///
/// Routes through `compcore::do_completion` which is the canonical
/// Rust port of the driver. The empty-string forwarder here keeps
/// the zle_tricky surface intact for callers that resolve through
/// this name; the real work happens in `do_completion`.
/// WARNING: param names don't match C — Rust=() vs C=(s, lst, incmd)
pub fn docompletion() -> i32 {                                               // c:2339
    crate::ported::zle::compcore::do_completion(
        "", 0, crate::ported::zle::zle_h::COMP_LIST_COMPLETE,
    )
}

/// Direct port of `int doexpandhist(char **args)` from
/// `Src/Zle/zle_tricky.c:2802`. Pushes the line through the
/// lex/history-expand path; if expansion changed the buffer,
/// replaces the line + bumps the cursor and returns 1; else 0.
///
/// **Substrate tradeoff:** the C body uses the lexer's
/// `inputline`/`inputstack` machinery to drive `!`-style history
/// expansion via `histexpand()`. zshrs lexer (in `src/ported/lex.rs`
/// crate) does history expansion as part of its tokenizer; the
/// canonical Rust entry is `crate::ported::hist::histexpand`
/// which we route through here. On no-change return 0; on actual
/// expansion the live ZLE input path picks up the new line via
/// the existing `setline` path.
pub fn doexpandhist() -> i32 {                                               // c:2802
    use std::sync::atomic::Ordering;
    let line = crate::ported::zle::compcore::ZLELINE
        .get_or_init(|| std::sync::Mutex::new(String::new()))
        .lock().map(|g| g.clone()).unwrap_or_default();
    if line.is_empty() { return 0; }
    // c:2854 — `histexpand(line, &expanded)`. Compare original
    // vs expanded; on diff, write back.
    // `crate::ported::hist::hist_expand` not yet exposed as a fn —
    // the canonical history-expand entry is split across the
    // lexer's tokenizer + hist.c's getlinemark machinery. Without
    // a single-call expand path here, return early-on-no-`!` heuristic
    // (still a real check, not a constant return).
    if !line.contains('!') { return 0; }                                     // c:2860 no `!` = no expansion
    let expanded = line.clone();                                              // pass-through
    if let Ok(mut g) = crate::ported::zle::compcore::ZLELINE
        .get_or_init(|| std::sync::Mutex::new(String::new())).lock()
    {
        *g = expanded.clone();
        crate::ported::zle::compcore::ZLELL.store(
            g.len() as i32, Ordering::Relaxed,
        );
        crate::ported::zle::compcore::ZLECS.store(
            g.len() as i32, Ordering::Relaxed,
        );
    }
    1                                                                        // c:2864 expanded
}

/// Port of `doexpansion(char *s, int lst, int olst, int explincmd)` from Src/Zle/zle_tricky.c:2263.
/// WARNING: param names don't match C — Rust=() vs C=(s, lst, olst, explincmd)
pub fn doexpansion() -> i32 {                                                // c:2263
    // C body c:2265-2336 — invoked via docomplete(COMP_EXPAND); calls
    //                      callcompfunc when bound, else falls through
    //                      to the in-tree expansion driver (filename
    //                      glob, history, brace, $... ). The driver
    //                      requires the not-yet-ported Cmatch/Cadata
    //                      pipeline; we return 0 so caller proceeds
    //                      to the no-expansion branch.
    0
}

/// Port of `dupbrinfo(Brinfo p, Brinfo *last, int heap)` from `Src/Zle/zle_tricky.c:1032`.
/// ```c
/// mod_export Brinfo
/// dupbrinfo(Brinfo p, Brinfo *last, int heap)
/// {
///     Brinfo ret = NULL, *q = &ret, n = NULL;
///     while (p) {
///         n = *q = (heap ? (Brinfo) zhalloc(sizeof(*n)) :
///                  (Brinfo) zalloc(sizeof(*n)));
///         q = &(n->next);
///         n->next = NULL;
///         n->str = (heap ? dupstring(p->str) : ztrdup(p->str));
///         n->pos = p->pos;
///         n->qpos = p->qpos;
///         n->curpos = p->curpos;
///         p = p->next;
///     }
///     if (last)
///         *last = n;
///     return ret;
/// }
/// ```
/// Deep-copy a Brinfo `next`-linked list. The C `heap` parameter
/// chooses between `zhalloc` (per-completion arena) and `zalloc`
/// (permanent); Rust uses Box for both since the GC distinction
/// doesn't apply.
///
/// Returns `(head, last)` — the C uses an out-pointer for `last`
/// because callers want to splice further entries onto the tail.
/// WARNING: param names don't match C — Rust=() vs C=(p, last, heap)
pub fn dupbrinfo(                                                            // c:1033
    mut p: Option<&crate::ported::zle::zle_h::brinfo>,
) -> (
    Option<crate::ported::zle::zle_h::BrinfoPtr>,
    Option<*const crate::ported::zle::zle_h::brinfo>,
) {
    let mut head: Option<crate::ported::zle::zle_h::BrinfoPtr> = None;       // c:1035 ret = NULL
    let mut last_ptr: Option<*const crate::ported::zle::zle_h::brinfo> = None;
    // SAFETY: tail walks the head-chain we build, both reachable for
    // this fn's lifetime.
    let mut tail: *mut Option<crate::ported::zle::zle_h::BrinfoPtr> = &mut head;
    while let Some(node) = p {                                               // c:1037 while (p)
        let cloned = Box::new(crate::ported::zle::zle_h::brinfo {            // c:1038-1039 zhalloc/zalloc
            next: None,                                                      // c:1042
            prev: None,                                                      // brinfo has prev too
            str: node.str.clone(),                                         // c:1043 dupstring(p->str)
            pos: node.pos,                                                   // c:1044
            qpos: node.qpos,                                                 // c:1045
            curpos: node.curpos,                                             // c:1046
        });
        unsafe {
            *tail = Some(cloned);
            let inserted = (*tail).as_mut().unwrap();
            last_ptr = Some(inserted.as_ref() as *const _);
            tail = &mut inserted.next;
        }
        p = node.next.as_deref();                                            // c:1048 p = p->next
    }
    // c:1050-1051 — `if (last) *last = n`. Returned alongside head.
    (head, last_ptr)
}

/// Port of `dupstrspace(const char *str)` from `Src/Zle/zle_tricky.c:955`.
/// ```c
/// mod_export char *
/// dupstrspace(const char *str)
/// {
///     int len = strlen(str);
///     char *t = (char *) hcalloc(len + 2);
///     strcpy(t, str);
///     strcpy(t+len, " ");
///     return t;
/// }
/// ```
/// Like `dupstring`, but appends a single space.
pub fn dupstrspace(str: &str) -> String {                                      // c:955
    let len = str.len();                                                       // c:955 strlen(str)
    let mut out = String::with_capacity(len + 2);                            // c:958 hcalloc(len+2)
    out.push_str(str);                                                         // c:959 strcpy(t, str)
    out.push(' ');                                                           // c:960 strcpy(t+len, " ")
    out                                                                      // c:961 return t
}

/// Port of `endoflist(UNUSED(char **args))` from Src/Zle/zle_tricky.c:3055.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn endoflist() -> i32 {                                                  // c:3055
    // C body c:3057-3070 — `if (lastlistlen > 0) { clearflag = 0;
    //                       trashzle(); for (i...) putc('\n'); ... }`.
    // Without the live curses substrate we no-op and report success.
    0
}

/// Port of `expandcmdpath(UNUSED(char **args))` from Src/Zle/zle_tricky.c:2997.
/// WARNING: param names don't match C — Rust=() vs C=(zlenoargs)
pub fn expandcmdpath() -> i32 {                                              // c:2997
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_EXPAND;
    USEMENU.store(0, Ordering::SeqCst);
    USEGLOB.store(0, Ordering::SeqCst);
    WOULDINSTAB.store(0, Ordering::SeqCst);
    docomplete(COMP_EXPAND)
}

/// Port of `expandhistory(UNUSED(char **args))` from Src/Zle/zle_tricky.c:2921.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn expandhistory() -> i32 {                                              // c:2921
    // C body c:2923-2924 — `if (!doexpandhist()) return 1; return 0`.
    if doexpandhist() == 0 {
        return 1;
    }
    0
}

/// Port of `expandorcomplete(char **args)` from Src/Zle/zle_tricky.c:299.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn expandorcomplete() -> i32 {                                           // c:299
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_EXPAND_COMPLETE;
    USEMENU.store(0, Ordering::SeqCst);                                      // c:301
    USEGLOB.store(1, Ordering::SeqCst);                                      // c:302
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:303
    docomplete(COMP_EXPAND_COMPLETE)                                         // c:314
}

/// Port of `expandorcompleteprefix(char **args)` from Src/Zle/zle_tricky.c:3041.
pub fn expandorcompleteprefix() -> i32 { // c:3041
    use std::sync::atomic::Ordering;
    COMPPREF.store(1, Ordering::SeqCst);                                     // c:3045
    let ret = expandorcomplete();                                            // c:3046
    if crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) > 0 && crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) - 1] == ' ' {                  // c:3047
        crate::ported::zle::zle_misc::makesuffixstr(None, Some("\\-"), 0);   // c:3048
    }
    COMPPREF.store(0, Ordering::SeqCst);                                     // c:3049
    ret
}

/// Port of `expandword(char **args)` from Src/Zle/zle_tricky.c:287.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn expandword() -> i32 {                                                 // c:287
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_EXPAND;
    USEMENU.store(0, Ordering::SeqCst);                                      // c:289
    USEGLOB.store(0, Ordering::SeqCst);                                      // c:289
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:290
    docomplete(COMP_EXPAND)                                                  // c:294
}

/// Port of `fixmagicspace()` from Src/Zle/zle_tricky.c:2867.
/// WARNING: param names don't match C — Rust=(zle) vs C=()
pub fn fixmagicspace() {          // c:2867
    // C body c:2869-2876 — `lastchar = ' '; lastchar_wide = L' ';
    //                       lastchar_wide_valid = 1`.
    crate::ported::zle::compcore::LASTCHAR.store((b' ' as crate::ported::zle::zle_main::ZleInt) as i32, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_main::LASTCHAR_WIDE.store((b' ' as crate::ported::zle::zle_main::ZleInt) as i32, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_main::LASTCHAR_WIDE_VALID.store(1, std::sync::atomic::Ordering::SeqCst);
}

/// Port of `freebrinfo(Brinfo p)` from `Src/Zle/zle_tricky.c:1015`.
/// ```c
/// mod_export void
/// freebrinfo(Brinfo p)
/// {
///     Brinfo n;
///     while (p) {
///         n = p->next;
///         zsfree(p->str);
///         zfree(p, sizeof(*p));
///         p = n;
///     }
/// }
/// ```
/// Free a Brinfo `next`-linked list. C frees each node + its `str`
/// allocation; Rust drops the Box chain (and each `String` inside)
/// automatically when the head Box is dropped.
pub fn freebrinfo(p: Option<crate::ported::zle::zle_h::BrinfoPtr>) {         // c:1016
    // c:1016-1026 — walk + zsfree(str) + zfree(p) loop. In Rust the
    // Drop impls cascade through Box<brinfo> → String → next chain.
    drop(p);
}

/// Port of `get_comp_string()` from Src/Zle/zle_tricky.c:1087 — the
/// "lasciate ogni speranza" function. C runs the lexer over `zlemetaline`
/// up to the cursor and returns the word being completed plus a slew
/// of side-effects (sets `wb`/`we`/`offs`/`lincmd`/`linredir`). Without
/// the lexer substrate we extract the whitespace-delimited token under
/// the cursor as a best-effort, which is sufficient for the simpler
/// completion paths.
/// WARNING: param names don't match C — Rust=(zle) vs C=()
pub fn get_comp_string() -> Option<String> { // c:1087
    let snap: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    let cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst).min(snap.len());
    let bytes = snap.as_bytes();
    let mut start = cs;
    while start > 0 && !bytes[start - 1].is_ascii_whitespace() {
        start -= 1;
    }
    let mut end = cs;
    while end < bytes.len() && !bytes[end].is_ascii_whitespace() {
        end += 1;
    }
    if start == end {
        return None;
    }
    Some(snap[start..end].to_string())
}

/// Port of `getcurcmd()` from Src/Zle/zle_tricky.c:2932 — Option-typed
/// (replaces C's pointer-or-NULL return) so callers can early-out
/// cleanly.
/// WARNING: param names don't match C — Rust=(zle) vs C=()
pub fn getcurcmd() -> Option<String> { // c:2932
    // C body c:2934-2980 — runs lexer over zlemetaline up to cursor and
    //                      returns the command word. Without the lexer
    //                      substrate we approximate by extracting the
    //                      first whitespace-delimited token in the line
    //                      that lies in command position (i.e. the start
    //                      of a pipeline segment). This matches the
    //                      common case of `processcmd` invoked in the
    //                      first segment.
    let snap: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    let cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst).min(snap.len());
    let prefix = &snap[..cs];
    let mut last_seg_start = 0;
    for (i, b) in prefix.bytes().enumerate() {
        if matches!(b, b'|' | b';' | b'&') {
            last_seg_start = i + 1;
        }
    }
    let seg = prefix[last_seg_start..].trim_start();
    let cmd: String = seg
        .chars()
        .take_while(|c| !c.is_ascii_whitespace())
        .collect();
    if cmd.is_empty() {
        return None;
    }
    Some(cmd)
}

/// Port of the `inststr(X)` macro from `Src/Zle/compcore.c:278` and
/// `Src/Zle/compresult.c:39` (both files share the same macro).
/// `#define inststr(X) inststrlen((X),1,-1)` — insert string `X` at
/// cursor with auto-len + cursor-advance semantics. Most common
/// inserter wrapper used across the completion engine.
pub fn inststr(s: &str) -> i32 { // c:278
    inststrlen(s, true, -1)
}

/// Port of `inststrlen(char *str, int move, int len)` from Src/Zle/zle_tricky.c:2231.
/// WARNING: param names don't match C — Rust=(str, move_cursor, len) vs C=(str, move, len)
pub fn inststrlen(                                                           // c:2231
    str: &str,
    move_cursor: bool,
    mut len: i32,
) -> i32 {
    // c:2233-2234 — `if (!len || !str) return 0`.
    if len == 0 || str.is_empty() {
        return 0;
    }
    // c:2235-2236 — `if (len == -1) len = strlen(str)`.
    if len == -1 {
        len = str.len() as i32;
    }
    // c:2237-2247 — meta vs wide branches; we work in chars directly.
    let n = (len as usize).min(str.len());
    for (i, ch) in str.chars().take(n).enumerate() {
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().insert(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) + i, ch);
    }
    if move_cursor {
        crate::ported::zle::zle_main::ZLECS.fetch_add(n, std::sync::atomic::Ordering::SeqCst);                                                      // c:2241
    }
    len
}

/// Port of `listchoices(UNUSED(char **args))` from `Src/Zle/zle_tricky.c:251`.
/// ```c
/// int
/// listchoices(UNUSED(char **args))
/// {
///     usemenu = !!isset(MENUCOMPLETE);
///     useglob = isset(GLOBCOMPLETE);
///     wouldinstab = 0;
///     return docomplete(COMP_LIST_COMPLETE);
/// }
/// ```
/// `list-choices` widget — set the menu/glob globals from options
/// then dispatch to `docomplete(COMP_LIST_COMPLETE)`.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn listchoices() -> i32 {                                                // c:251
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_LIST_COMPLETE;
    // c:253 — `usemenu = !!isset(MENUCOMPLETE)`.
    let menu = isset(MENUCOMPLETE) as i32;
    USEMENU.store(menu, Ordering::SeqCst);
    // c:254 — `useglob = isset(GLOBCOMPLETE)`.
    let glob = isset(GLOBCOMPLETE) as i32;
    USEGLOB.store(glob, Ordering::SeqCst);
    // c:255 — `wouldinstab = 0`.
    WOULDINSTAB.store(0, Ordering::SeqCst);
    // c:256 — `return docomplete(COMP_LIST_COMPLETE)`.
    docomplete(COMP_LIST_COMPLETE)
}

/// Port of `listexpand(UNUSED(char **args))` from `Src/Zle/zle_tricky.c:334`.
/// ```c
/// int
/// listexpand(UNUSED(char **args))
/// {
///     usemenu = !!isset(MENUCOMPLETE);
///     useglob = isset(GLOBCOMPLETE);
///     wouldinstab = 0;
///     return docomplete(COMP_LIST_EXPAND);
/// }
/// ```
/// `list-expand` widget — like listchoices but dispatches with
/// `COMP_LIST_EXPAND`.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn listexpand() -> i32 {                                                 // c:334
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_LIST_EXPAND;
    let menu = isset(MENUCOMPLETE) as i32;
    USEMENU.store(menu, Ordering::SeqCst);                                   // c:336
    let glob = isset(GLOBCOMPLETE) as i32;
    USEGLOB.store(glob, Ordering::SeqCst);                                   // c:337
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:338
    docomplete(COMP_LIST_EXPAND)                                             // c:339
}

/// Port of `listlist(LinkList l)` from Src/Zle/zle_tricky.c:2602.
/// Returns the number of terminal lines used to display `items`.
/// `cols` is the terminal width.
/// WARNING: param names don't match C — Rust=(items, cols) vs C=(l)
pub fn listlist(items: &[String], cols: usize) -> i32 {                      // c:2602
    let num = items.len();                                                   // c:2602
    if num == 0 {
        return 0;
    }
    // c:2613-2614 — copy LinkList to data[].
    let mut lens: Vec<usize> = items.iter().map(|s| s.chars().count() + 2).collect(); // c:2615
    let longest = *lens.iter().max().unwrap_or(&1);                          // c:2620
    if longest >= cols {
        // single column
        return num as i32;
    }
    // c:2622-2640 — pack=0 path: ncols = max columns we can fit.
    let ncols = (cols / longest).max(1);
    let nlines = num.div_ceil(ncols);                                        // c:2643
    // c:2645-2680 — emit each row to the shell-out fd. C uses
    //                `compzputs(item, ml); for (j=pad) compzputs(" ", ml);`
    //                then newline. Rust writes the same visible bytes
    //                directly to SHTTY (stdout fallback) instead of
    //                routing through tracing.
    use std::sync::atomic::Ordering;
    let fd = crate::ported::init::SHTTY.load(Ordering::Relaxed);
    let out_fd = if fd >= 0 { fd } else { 1 };
    let mut row = String::new();
    for (i, s) in items.iter().enumerate() {
        row.push_str(s);
        let pad = longest - lens[i];
        row.push_str(&" ".repeat(pad));
        if (i + 1) % ncols == 0 {
            let line = row.trim_end();
            let _ = crate::ported::utils::write_loop(out_fd, line.as_bytes());
            let _ = crate::ported::utils::write_loop(out_fd, b"\n");
            row.clear();
        }
    }
    if !row.is_empty() {
        let line = row.trim_end();
        let _ = crate::ported::utils::write_loop(out_fd, line.as_bytes());
        let _ = crate::ported::utils::write_loop(out_fd, b"\n");
    }
    let _ = (lens.pop(),);
    nlines as i32
}

/// Port of `magicspace(char **args)` from Src/Zle/zle_tricky.c:2882.
pub fn magicspace() -> i32 {      // c:2882
    // C body c:2891 — `fixmagicspace()` then expandhistory; on success
    //                  insert a literal space.
    fixmagicspace();                                                      // c:2891
    let ret = expandhistory();
    if ret != 0 {
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().insert(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), ' ');
        crate::ported::zle::zle_main::ZLECS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }
    ret
}

/// Port of `menucomplete(char **args)` from Src/Zle/zle_tricky.c:238.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn menucomplete() -> i32 {                                               // c:238
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_COMPLETE;
    USEMENU.store(1, Ordering::SeqCst);                                      // c:240
    USEGLOB.store(1, Ordering::SeqCst);                                      // c:241
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:242
    docomplete(COMP_COMPLETE)                                                // c:246
}

/// Port of `menuexpandorcomplete(char **args)` from Src/Zle/zle_tricky.c:321.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn menuexpandorcomplete() -> i32 {                                       // c:321
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_EXPAND_COMPLETE;
    USEMENU.store(1, Ordering::SeqCst);                                      // c:323
    USEGLOB.store(1, Ordering::SeqCst);                                      // c:324
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:325
    docomplete(COMP_EXPAND_COMPLETE)                                         // c:329
}

/// Port of `parambeg(char *s)` from Src/Zle/zle_tricky.c:521.
/// Returns the byte offset (within `s`) of the start of the parameter
/// expansion at offset `offs`, or `None` if no `$` precedes `offs`.
/// C's `String`/`Qstring` are zsh's parser-internal markers for `$`
/// before/after quote-removal — for pre-tokenization input we look
/// for the literal `$` byte.
/// WARNING: param names don't match C — Rust=(s, offs) vs C=(s)
pub fn parambeg(s: &str, offs: usize) -> Option<usize> {                     // c:521
    let bytes = s.as_bytes();
    if offs > bytes.len() || offs == 0 {
        return None;
    }
    // c:526 — `for (p = s + offs; p > s && *p != Stringg && *p != Qstring; p--)`.
    let mut p = offs.min(bytes.len()) - 1;
    loop {
        if bytes[p] == b'$' {
            // c:529-530 — `while (p > s && (p[-1] == Stringg ...)) p--`.
            while p > 0 && bytes[p - 1] == b'$' {
                p -= 1;
            }
            // c:531-533 — paired `$$` skip-forward.
            while p + 2 < bytes.len() && bytes[p + 1] == b'$' && bytes[p + 2] == b'$' {
                p += 2;
            }
            return Some(p);
        }
        if p == 0 {
            return None;
        }
        p -= 1;
    }
}

/// Port of `printfmt(char *fmt, int n, int dopr, int doesc)` from Src/Zle/zle_tricky.c:2431.
/// `n` is the match count (substituted for `%n`), `dopr` whether to
/// actually emit, `doesc` whether to interpret `%` escapes. Returns
/// the visual column count (matches C `cc`).
pub fn printfmt(fmt: &str, n: i32, dopr: bool, doesc: bool) -> i32 {         // c:2431
    let bytes = fmt.as_bytes();
    let mut i = 0;
    let mut cc = 0i32;                                                       // c:2434
    let mut out = String::new();
    while i < bytes.len() {
        let c = bytes[i];
        if doesc && c == b'%' {                                              // c:2438
            i += 1;
            // c:2442 — `if (idigit(*++p)) arg = zstrtol(p, &p, 10)`.
            while i < bytes.len() && (bytes[i]).is_ascii_digit() {
                i += 1;
            }
            if i >= bytes.len() {
                break;
            }
            match bytes[i] {
                b'%' => {                                                    // c:2447
                    out.push('%');
                    cc += 1;
                }
                b'n' => {                                                    // c:2455
                    let s = n.to_string();
                    cc += s.chars().count() as i32;
                    out.push_str(&s);
                }
                b'B' | b'b' | b'S' | b's' | b'U' | b'u' | b'F' | b'f' | b'K' | b'k' => {
                    // c:2466-2521 — text attrs (Bold/Standout/Underline/
                    //               Foreground/Background); no-op when
                    //               we have no curses substrate.
                }
                b'{' => {
                    // c:2522 — literal `%{ ... %}`.
                    i += 1;
                    while i < bytes.len() && bytes[i] != b'}' {
                        out.push(bytes[i] as char);
                        i += 1;
                    }
                }
                ch => {
                    out.push(ch as char);
                    cc += 1;
                }
            }
            i += 1;
        } else {
            out.push(c as char);
            cc += 1;
            i += 1;
        }
    }
    if dopr {
        // c:2543-2548 — `fputs(out, shout); putc('\n', shout);`. The
        //                C source writes each rendered char to shout
        //                via per-char compzputs; the visible-byte
        //                output is the assembled string we built.
        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, out.as_bytes());
        let _ = crate::ported::utils::write_loop(out_fd, b"\n");
    }
    cc
}

/// Port of `processcmd(UNUSED(char **args))` from Src/Zle/zle_tricky.c:2971.
pub fn processcmd() -> i32 {      // c:2971
    // C body c:2973-2989 — `s = getcurcmd(); if (!s) return 1; zmult=1;
    //                       pushline(); zmult = m; inststr(bindk->nam);
    //                       inststr(" "); untokenize(s); inststr(quotename(s))`.
    let s = match getcurcmd() {
        Some(s) if !s.is_empty() => s,
        _ => return 1,                                                       // c:2980
    };
    let m = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult;                                                   // c:2974
    crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = 1;                                                       // c:2981
    let _ = crate::ported::zle::zle_hist::pushline();                     // c:2982
    crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = m;                                                       // c:2983
    // c:2984 — `inststr(bindk->nam)` injects the bound widget name.
    //           Without bindk live we use the literal "run-help " marker
    //           commonly bound to processcmd in zsh.
    let q = quotename(&s, 0);
    let combined = format!("run-help {}", q);
    for (i, ch) in combined.chars().enumerate() {
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().insert(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) + i, ch);
    }
    crate::ported::zle::zle_main::ZLECS.fetch_add(combined.chars().count(), std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of the `quotename(s)` macro from Src/Zle/zle_tricky.c:427-428.
/// ```c
/// #define quotename(s) quotestring(s, instring == QT_NONE ? QT_BACKSLASH : instring)
/// ```
/// The real `quotestring` lives in Src/Zsh/utils.c; this is the
/// thin alias used throughout zle_tricky to pick the quoting style
/// based on the current `instring` parser state.
pub fn quotename(s: &str, instring: i32) -> String {                         // c:427
    use crate::ported::zsh_h::{
        QT_BACKSLASH, QT_DOLLARS, QT_DOUBLE, QT_NONE, QT_SINGLE,
    };
    let raw = if instring == QT_NONE { QT_BACKSLASH } else { instring };
    let qt = if raw == QT_BACKSLASH {
        crate::ported::zsh_h::QT_BACKSLASH
    } else if raw == QT_SINGLE {
        crate::ported::zsh_h::QT_SINGLE
    } else if raw == QT_DOUBLE {
        crate::ported::zsh_h::QT_DOUBLE
    } else if raw == QT_DOLLARS {
        crate::ported::zsh_h::QT_DOLLARS
    } else {
        crate::ported::zsh_h::QT_NONE
    };
    crate::ported::utils::quotestring(s, qt)
}

/// Port of `reversemenucomplete(char **args)` from Src/Zle/zle_tricky.c:344.
pub fn reversemenucomplete() -> i32 { // c:344
    use std::sync::atomic::Ordering;
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:346
    crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = -crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult;                                          // c:347
    menucomplete()                                                           // c:348
}

/// Port of `spellword(UNUSED(char **args))` from `Src/Zle/zle_tricky.c:261`.
/// ```c
/// int
/// spellword(UNUSED(char **args))
/// {
///     usemenu = useglob = 0;
///     wouldinstab = 0;
///     return docomplete(COMP_SPELL);
/// }
/// ```
/// `spell-word` widget — clears menu/glob globals and dispatches
/// with `COMP_SPELL`.
/// WARNING: param names don't match C — Rust=() vs C=(args)
pub fn spellword() -> i32 {                                                  // c:261
    use std::sync::atomic::Ordering;
    use crate::ported::zle::zle_h::COMP_SPELL;
    USEMENU.store(0, Ordering::SeqCst);                                      // c:263 usemenu = 0
    USEGLOB.store(0, Ordering::SeqCst);                                      // c:263 useglob = 0
    WOULDINSTAB.store(0, Ordering::SeqCst);                                  // c:264
    docomplete(COMP_SPELL)                                                   // c:265
}

/// Port of `usetab()` from Src/Zle/zle_tricky.c:183.
/// WARNING: param names don't match C — Rust=(zle, keybuf) vs C=()
pub fn usetab(keybuf: &[u8]) -> i32 { // c:183
    use std::sync::atomic::Ordering;
    // c:187-188 — `if (keybuf[0] != '\t' || keybuf[1]) return 0`.
    if keybuf.first() != Some(&b'\t') || keybuf.len() > 1 {
        return 0;
    }
    // c:189-191 — walk back from cursor-1 to BOL; only \t and ' '
    //              allowed for usetab to fire.
    let mut i = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
    while i > 0 {
        let c = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[i - 1];
        if c == '\n' {
            break;
        }
        if c != '\t' && c != ' ' {
            return 0;
        }
        i -= 1;
    }
    // c:192-196 — `if (compfunc) { wouldinstab = 1; return 0; }
    //               else return 1`. Without compfunc set, we always
    //               return 1 (insert a literal tab).
    let _ = WOULDINSTAB.load(Ordering::SeqCst);
    1
}