zshrs 0.11.4

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
//! ZLE history operations
//!
//! Direct port from zsh/Src/Zle/zle_hist.c
//!
//! Previous aborted search string use in an incremental search              // c:52
//! Local keymap in isearch mode                                             // c:57
//! the last vi search                                                       // c:1807
//! history-beginning-search-backward                                        // c:2035
//! history-beginning-search-forward                                         // c:2082
//!
//! Implements all history navigation widgets:
//! - up-line-or-history, down-line-or-history
//! - history-search-backward, history-search-forward  
//! - history-incremental-search-backward, history-incremental-search-forward
//! - beginning-of-history, end-of-history
//! - vi-fetch-history, vi-history-search-*
//! - accept-line-and-down-history, accept-and-infer-next-history
//! - insert-last-word, push-line, push-line-or-edit

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

use super::zle_main::{ZleString};

// =====================================================================
// Isearch globals — `Src/Zle/zle_hist.c:1078`.
// =====================================================================

/// Port of `int isearch_active` from `Src/Zle/zle_hist.c:1078`.
/// Non-zero while the user is inside an incremental-search session.

// --- AUTO: cross-zle hoisted-fn use glob ---
#[allow(unused_imports)]
use crate::ported::zle::zle_h::*;
#[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_move::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_word::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_params::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_vi::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_utils::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_refresh::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_tricky::*;
#[allow(unused_imports)]
use crate::ported::zle::textobjects::*;
#[allow(unused_imports)]
use crate::ported::zle::deltochar::*;

pub static ISEARCH_ACTIVE: AtomicI32 = AtomicI32::new(0);                    // c:1078

/// Port of `int isearch_startpos` from `Src/Zle/zle_hist.c:1078`.
/// Byte offset of the start of the current isearch match.
pub static ISEARCH_STARTPOS: AtomicI32 = AtomicI32::new(0);                  // c:1078

/// Port of `int isearch_endpos` from `Src/Zle/zle_hist.c:1078`.
/// Byte offset of the end of the current isearch match.
pub static ISEARCH_ENDPOS: AtomicI32 = AtomicI32::new(0);                    // c:1078

// Per-session ZLE history state. Rust-side aggregate over zsh's C
// flat-globals (`hist_ring`/`histline`/`searchstr`/`have_edits`/etc.
// in `Src/hist.c` + `Src/Zle/zle_hist.c`). The C side spreads these
// across file-scope statics; the zshrs port collects the subset the
// ZLE widgets actually drive into one container so a `&mut Zle` can
// hold it. Eventual unification: drop `History.entries` and read from
// `crate::ported::hist::hist_ring`; the cursor/saved_line/search
// fields stay as file-scope statics matching zsh's globals.

/// Single history entry — the Rust-side subset the ZLE widgets need
/// (line text, event number, optional time). Maps loosely to fields
/// from `struct histent` (Src/zsh.h:2234): `node.nam` ↔ `line`,
/// `histnum` ↔ `num`, `stim` ↔ `time`.
#[derive(Debug, Clone)]
pub struct HistEntry {
    /// The command line.
    pub line: String,
    /// Event number (1-based; mirrors `histent.histnum`).
    pub num: i64,
    /// Insertion time (Unix epoch seconds; mirrors `histent.stim`).
    pub time: Option<i64>,
}

/// Per-session ZLE history state — entries + cursor + search state.
/// Aggregate over zsh's C flat-globals (`hist_ring`, `histline`,
/// `searchstr`, `have_edits`).
#[derive(Debug, Default)]
pub struct History {
    /// History entries (newest last).
    pub entries: Vec<HistEntry>,
    /// Current position in history (mirrors `histline`).
    pub cursor: usize,
    /// Maximum history size (mirrors `histsiz`).
    pub max_size: usize,
    /// Saved line when navigating history (mirrors the C `zle_text`
    /// shadow on `Histent`).
    pub saved_line: Option<crate::ported::zle::zle_main::ZleString>,
    /// Saved cursor position pre-navigation.
    pub saved_cs: usize,
    /// Previous search string. Mirrors `searchstr`
    /// (Src/Zle/zle_hist.c:44).
    pub search_pattern: String,
    /// Last search direction (true = backward).
    pub search_backward: bool,
    /// Originals of edited entries: when `remember_edits` mutates
    /// `entries[i].line`, the pre-edit text lands here at index `i`.
    /// `forget_edits` restores them. Mirrors the C `Histent->zle_text`
    /// shadow string + the global `have_edits` flag in
    /// Src/Zle/zle_hist.c.
    pub originals: Vec<Option<String>>,
    /// True if any entry has a recorded original — mirrors
    /// `have_edits` in Src/Zle/zle_hist.c:76.
    pub have_edits: bool,
    /// History skip-flags state. Bit-equivalent of zsh's
    /// `hist_skip_flags` in Src/Zle/zle_hist.c:794: `HIST_FOREIGN` (1)
    /// hides entries from other sessions when set; `setlocalhistory`
    /// toggles this.
    pub hist_skip_flags: u32,
}

impl History {
    /// Construct an empty history with a max-entry cap. Mirrors the
    /// role of `inithist()` from Src/hist.c:1717 (which sizes the
    /// global `hist_ring` at `$HISTSIZE`).
    pub fn new(max_size: usize) -> Self {
        History {
            entries: Vec::new(),
            cursor: 0,
            max_size,
            saved_line: None,
            saved_cs: 0,
            search_pattern: String::new(),
            search_backward: true,
            originals: Vec::new(),
            have_edits: false,
            hist_skip_flags: 0,
        }
    }

    /// Append a new entry. Mirrors `addhistnode()` from Src/hist.c
    /// (the inner add path invoked by `addhistline`/`hend`). Skips
    /// empty input and consecutive-duplicate lines (same as zsh's
    /// HIST_IGNORE_DUPS default). Trims from the front when over
    /// `max_size`.
    pub fn add(&mut self, line: String) {
        if line.is_empty() {
            return;
        }
        if let Some(last) = self.entries.last() {
            if last.line == line {
                return;
            }
        }

        self.entries.push(HistEntry {
            line,
            num: self.entries.len() as i64 + 1,
            time: Some(
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0),
            ),
        });

        while self.entries.len() > self.max_size {
            self.entries.remove(0);
        }

        self.cursor = self.entries.len();
    }

    /// Look up the entry at a specific 0-based index. Mirrors
    /// `quietgethist()` from Src/Zle/zle_hist.c:1712 (event-number
    /// fetch); our entries Vec is 0-indexed so callers convert
    /// num→index themselves.
    pub fn get(&self, index: usize) -> Option<&HistEntry> {
        self.entries.get(index)
    }

    /// Step the cursor one position older. Equivalent to the
    /// cursor-decrement path of `zle_goto_hist()` at
    /// Src/Zle/zle_hist.c:805 with n=-1.
    pub fn up(&mut self) -> Option<&HistEntry> {
        if self.cursor > 0 {
            self.cursor -= 1;
            self.entries.get(self.cursor)
        } else {
            None
        }
    }

    /// Step the cursor one position newer. Mirrors
    /// `zle_goto_hist()` at Src/Zle/zle_hist.c:805 with n=+1.
    pub fn down(&mut self) -> Option<&HistEntry> {
        if self.cursor < self.entries.len() {
            self.cursor += 1;
            self.entries.get(self.cursor)
        } else {
            None
        }
    }

    /// Search history for the most recent entry containing `pattern`.
    /// Substring-match equivalent of `historysearchbackward()` from
    /// Src/Zle/zle_hist.c:484 (without the glob/HIST_PATTERN branch).
    pub fn search_backward(&mut self, pattern: &str) -> Option<&HistEntry> {
        let start = if self.cursor > 0 {
            self.cursor - 1
        } else {
            return None;
        };
        for i in (0..=start).rev() {
            if self.entries[i].line.contains(pattern) {
                self.cursor = i;
                return self.entries.get(i);
            }
        }
        None
    }

    /// Search history forward for the next entry containing
    /// `pattern`. Mirror of `search_backward` against
    /// `historysearchforward()` at Src/Zle/zle_hist.c:541.
    pub fn search_forward(&mut self, pattern: &str) -> Option<&HistEntry> {
        for i in (self.cursor + 1)..self.entries.len() {
            if self.entries[i].line.contains(pattern) {
                self.cursor = i;
                return self.entries.get(i);
            }
        }
        None
    }

    /// Reset the cursor to the live-buffer sentinel position and
    /// drop any saved pre-navigation line. Mirrors the
    /// `histline = curhist; saved_line = NULL` reset path invoked by
    /// `endofhistory()` (Src/Zle/zle_hist.c:478) and after
    /// accept-line.
    pub fn reset(&mut self) {
        self.cursor = self.entries.len();
        self.saved_line = None;
    }
}

    /// Set up history limits at ZLE startup.
    /// Stub mirroring the role of `inithist()` from Src/hist.c:1717,
    /// which sizes the global hist_ring at $HISTSIZE. zshrs's history
    /// lives in the file-scope `HISTORY` static (zle_main.rs); this
    /// helper is kept for API compatibility — callers can adjust
    /// max_size at init if needed.
    pub fn init_history(max_size: usize) {
        let _ = max_size;
    }

    /// Move cursor up by `crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst)` lines within the multi-line buffer.
    /// Returns leftover count (positive = hit top of buffer before completing).
    /// Port of upline(char **args) from Src/Zle/zle_hist.c:243.
    /// WARNING: param names don't match C — Rust=() vs C=(args)
    pub fn upline() -> i32 {                                        // c:243
        let mut n = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        if n < 0 {
            crate::ported::zle::zle_main::MULT.store(-crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            let r = -downline();
            crate::ported::zle::zle_main::MULT.store(-crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            return r;
        }
        if crate::ported::zle::zle_main::LASTCOL.load(std::sync::atomic::Ordering::SeqCst) == -1 {
            crate::ported::zle::zle_main::LASTCOL.store((crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) - findbol()) as i32, std::sync::atomic::Ordering::SeqCst);
        }
        crate::ported::zle::zle_main::ZLECS.store(findbol(), std::sync::atomic::Ordering::SeqCst);
        while n > 0 {
            if crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) == 0 {
                break;
            }
            crate::ported::zle::zle_main::ZLECS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLECS.store(findbol(), std::sync::atomic::Ordering::SeqCst);
            n -= 1;
        }
        if n == 0 {
            let x = findeol();
            crate::ported::zle::zle_main::ZLECS.fetch_add(crate::ported::zle::zle_main::LASTCOL.load(std::sync::atomic::Ordering::SeqCst) as usize, std::sync::atomic::Ordering::SeqCst);
            if crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) >= x {
                crate::ported::zle::zle_main::ZLECS.store(x, std::sync::atomic::Ordering::SeqCst);
            }
        }
        n
    }

    /// Move cursor down by `crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst)` lines.
    /// Returns leftover count (positive = hit bottom before completing).
    /// Port of downline(char **args) from Src/Zle/zle_hist.c:332.
    /// WARNING: param names don't match C — Rust=() vs C=(args)
    pub fn downline() -> i32 {                                      // c:332
        let mut n = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        if n < 0 {
            crate::ported::zle::zle_main::MULT.store(-crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            let r = -upline();
            crate::ported::zle::zle_main::MULT.store(-crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            return r;
        }
        if crate::ported::zle::zle_main::LASTCOL.load(std::sync::atomic::Ordering::SeqCst) == -1 {
            crate::ported::zle::zle_main::LASTCOL.store((crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) - findbol()) as i32, std::sync::atomic::Ordering::SeqCst);
        }
        while n > 0 {
            let x = findeol();
            if x == crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst) {
                break;
            }
            crate::ported::zle::zle_main::ZLECS.store(x + 1, std::sync::atomic::Ordering::SeqCst);
            n -= 1;
        }
        if n == 0 {
            let x = findeol();
            crate::ported::zle::zle_main::ZLECS.fetch_add(crate::ported::zle::zle_main::LASTCOL.load(std::sync::atomic::Ordering::SeqCst) as usize, std::sync::atomic::Ordering::SeqCst);
            if crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst) >= x {
                crate::ported::zle::zle_main::ZLECS.store(x, std::sync::atomic::Ordering::SeqCst);
            }
        }
        n
    }

    /// Try to move cursor up one line; if at top of buffer, navigate history.
    /// Port of uplineorhistory(char **args) from Src/Zle/zle_hist.c:282.
    /// Returns 0 on success, 1 if exhausted (caller may beep).


    /// Try to move cursor down one line; if at bottom of buffer, navigate history.
    /// Port of downlineorhistory(char **args) from Src/Zle/zle_hist.c:370.


    /// Move the history cursor by `n` (negative = older / "up", positive = newer / "down").
    /// If `skipdups`, keep stepping while the visited entry equals the current line.
    /// Returns true if the line changed, false if exhausted (caller may beep).
    /// Port of `zle_goto_hist(int ev, int n, int skipdups)` from Src/Zle/zle_hist.c:806.
    /// WARNING: param names don't match C — Rust=(n, skipdups) vs C=(ev, n, skipdups)
    pub fn zle_goto_hist(n: i32, skipdups: bool) -> bool {
        let len = crate::ported::zle::zle_main::history().lock().unwrap().entries.len() as i32;
        if len == 0 {
            return false;
        }
        let cur: i32 = if (crate::ported::zle::zle_main::history().lock().unwrap().cursor as i32) > len {
            len
        } else {
            crate::ported::zle::zle_main::history().lock().unwrap().cursor as i32
        };
        let mut new_idx = cur + n;
        if new_idx < 0 || new_idx > len {
            return false;
        }
        if skipdups && n != 0 {
            let cur_line: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
            let step: i32 = if n < 0 { -1 } else { 1 };
            while new_idx >= 0 && new_idx < len {
                if crate::ported::zle::zle_main::history().lock().unwrap().entries[new_idx as usize].line != cur_line {
                    break;
                }
                new_idx += step;
            }
            if new_idx < 0 || new_idx > len {
                return false;
            }
        }

        // Save current line on first navigation away from the live buffer.
        if crate::ported::zle::zle_main::history().lock().unwrap().saved_line.is_none() && crate::ported::zle::zle_main::history().lock().unwrap().cursor as i32 == len {
            crate::ported::zle::zle_main::history().lock().unwrap().saved_line = Some(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clone());
            crate::ported::zle::zle_main::history().lock().unwrap().saved_cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
        }

        crate::ported::zle::zle_main::history().lock().unwrap().cursor = new_idx as usize;
        let new_line: Option<ZleString> = if new_idx == len {
            crate::ported::zle::zle_main::history().lock().unwrap().saved_line.clone()
        } else {
            Some(
                crate::ported::zle::zle_main::history().lock().unwrap().entries[new_idx as usize]
                    .line
                    .chars()
                    .collect(),
            )
        };
        if let Some(line) = new_line {
            *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = line;
            crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
            let new_cs = if new_idx == len {
                crate::ported::zle::zle_main::history().lock().unwrap().saved_cs.min(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst))
            } else {
                crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst)
            };
            crate::ported::zle::zle_main::ZLECS.store(new_cs, std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::LASTCOL.store(-1, std::sync::atomic::Ordering::SeqCst);
        }
        true
    }

    /// Walk one entry older through the externally-supplied History.
    /// External-history overload of the widget-callable
    /// `zle_goto_hist(-1, false)` — kept for callers that drive a
    /// separate History instance. Port of `uphistory()` at
    /// Src/Zle/zle_hist.c:233 (the live-buffer save matches the C
    /// source's first-navigate-saves-original behaviour).
    pub fn history_up(hist: &mut History) {
        if hist.saved_line.is_none() {
            // Save current line
            hist.saved_line = Some(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clone());
            hist.saved_cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
        }

        if let Some(entry) = hist.up() {
            *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
            crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    /// Walk one entry newer; if past the last entry, restore the saved
    /// pre-navigation line.
    /// External-history overload of `zle_goto_hist(1, false)`.
    /// Port of `downhistory(UNUSED(char **args))` at Src/Zle/zle_hist.c:434 with the
    /// saved-line restore from zle_goto_hist's sentinel branch.
    pub fn history_down(hist: &mut History) {
        if let Some(entry) = hist.down() {
            *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
            crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        } else if let Some(saved) = hist.saved_line.take() {
            // Restore saved line
            *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = saved;
            crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLECS.store(hist.saved_cs, std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    /// Set search direction for an incremental backward search. The full
    /// interactive isearch UI lives in `widget::do_isearch` (called by the
    /// `widget_history_isearch_backward` widget) — this method only flips
    /// the saved direction flag for callers that drive History externally.
    pub fn history_isearch_backward(hist: &mut History) {
        hist.search_backward = true;
    }

    /// Mirror of `history_isearch_backward` but for forward search.
    pub fn history_isearch_forward(hist: &mut History) {
        hist.search_backward = false;
    }

    /// Search history for an entry containing the buffer text up to
    /// the cursor.
    /// Port of `historybeginningsearchbackward()` from
    /// Src/Zle/zle_hist.c:2039 with substring-match instead of
    /// prefix-match — useful as an isearch-style helper for callers
    /// that drive History externally. The strict prefix-match form
    /// lives in `widget_history_beginning_search_backward`.
    pub fn history_search_prefix(hist: &mut History) {
        let prefix: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst)].iter().collect();

        if let Some(entry) = hist.search_backward(&prefix) {
            *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
            crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
            crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    /// Beginning of history - go to first entry
    /// Port of beginningofhistory(UNUSED(char **args)) from zle_hist.c
    pub fn beginning_of_history(hist: &mut History) {
        if hist.saved_line.is_none() {
            hist.saved_line = Some(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clone());
            hist.saved_cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
        }

        if !hist.entries.is_empty() {
            hist.cursor = 0;
            if let Some(entry) = hist.entries.first() {
                *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
                crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
                crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
                crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
            }
        }
    }

    /// End of history - go to last entry (current line)
    /// Port of endofhistory() from zle_hist.c

    /// History search backward - search for entries starting with current prefix
    /// Port of historysearchbackward() from zle_hist.c


    /// History search forward - search for entries starting with current prefix
    /// Port of historysearchforward() from zle_hist.c


    /// Insert last word from previous history entry
    /// Port of insertlastword() from zle_hist.c


    /// Push the current line onto the buffer stack and clear the editor.
    /// Port of `pushline(UNUSED(char **args))` from Src/Zle/zle_hist.c:832. The C source
    /// pushes the assembled line, then `mult - 1` empty strings (so a
    /// numeric prefix repeats the push), saves zlecs to stackcs, and
    /// blanks the line. The buffer stack is then drained on the next
    /// zleread() so the user gets to compose a quick command and have
    /// the prior text restored afterwards.
    pub fn push_line() {
        let n = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        if n < 0 {
            return;
        }
        let line: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
        crate::ported::zle::zle_main::BUFSTACK.lock().unwrap().push(line);
        let mut remaining = n - 1;
        while remaining > 0 {
            crate::ported::zle::zle_main::BUFSTACK.lock().unwrap().push(String::new());
            remaining -= 1;
        }
        crate::ported::zle::zle_main::STACKCS.store(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
        crate::ported::zle::zle_main::ZLELL.store(0, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
    }

    /// Accept line and go to next history (for walking through history executing each)
    /// Port of acceptlineanddownhistory(UNUSED(char **args)) from zle_hist.c
    pub fn accept_line_and_down_history(hist: &mut History) -> Option<String> {
        let line: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();

        // Move to next history entry for next iteration
        if hist.cursor < hist.entries.len() {
            hist.cursor += 1;
            if let Some(entry) = hist.entries.get(hist.cursor) {
                *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
                crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
                crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
            }
        }

        Some(line)
    }

    /// Vi fetch history - go to specific history entry by number
    /// Port of vifetchhistory(UNUSED(char **args)) from zle_hist.c
    pub fn vi_fetch_history(hist: &mut History, num: usize) {
        if num > 0 && num <= hist.entries.len() {
            if hist.saved_line.is_none() {
                hist.saved_line = Some(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clone());
                hist.saved_cs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
            }

            hist.cursor = num - 1;
            if let Some(entry) = hist.entries.get(hist.cursor) {
                *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = entry.line.chars().collect();
                crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
                crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
                crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
            }
        }
    }

    /// Vi history search backward
    /// Port of vihistorysearchbackward(char **args) from zle_hist.c


    /// Vi history search forward
    /// Port of vihistorysearchforward(char **args) from zle_hist.c


    /// Vi repeat search
    /// Port of virepeatsearch(UNUSED(char **args)) from zle_hist.c
    pub fn vi_repeat_search(hist: &mut History) {
        if hist.search_backward {
            vihistorysearchbackward();
        } else {
            vihistorysearchforward();
        }
    }

    /// Vi reverse repeat search
    /// Port of virevrepeatsearch() from zle_hist.c


    /// Toggle session-local history filtering.
    /// Port of `setlocalhistory(UNUSED(char **args))` from Src/Zle/zle_hist.c:794. With an
    /// explicit count: `mult` non-zero turns the foreign-skip filter on
    /// (`hist_skip_flags = HIST_FOREIGN = 1`), zero turns it off. With
    /// no count: XOR-toggle the bit. Call sites that walk history can
    /// consult `hist.hist_skip_flags & 1` to decide whether to surface
    /// entries from other sessions.
    pub fn set_local_history(hist: &mut History, has_mult: bool, mult: i32) {
        const HIST_FOREIGN: u32 = 1;
        if has_mult {
            hist.hist_skip_flags = if mult != 0 { HIST_FOREIGN } else { 0 };
        } else {
            hist.hist_skip_flags ^= HIST_FOREIGN;
        }
    }

    /// Snapshot the current line into the history entry at `cursor`,
    /// preserving the original on first edit.
    /// Port of `remember_edits()` from Src/Zle/zle_hist.c:80. The C source
    /// stashes the in-flight text in `Histent->zle_text` (a separate field
    /// from the canonical history line) and sets `have_edits = 1`. We
    /// model `zle_text` by keeping the edited text in `entries[i].line`
    /// directly and saving the canonical version into `originals[i]`
    /// on first edit so `forget_edits` can restore it.
    /// WARNING: param names don't match C — Rust=(hist) vs C=()
    pub fn remember_edits(hist: &mut History) {
        if hist.cursor < hist.entries.len() {
            if hist.originals.len() < hist.entries.len() {
                hist.originals.resize(hist.entries.len(), None);
            }
            let new_line: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
            if hist.entries[hist.cursor].line != new_line {
                if hist.originals[hist.cursor].is_none() {
                    hist.originals[hist.cursor] = Some(hist.entries[hist.cursor].line.clone());
                }
                hist.entries[hist.cursor].line = new_line;
                hist.have_edits = true;
            }
        }
    }

    /// Restore every edited history entry to its original text.
    /// Port of `forget_edits()` from Src/Zle/zle_hist.c:99. The C source
    /// walks the hist ring freeing each entry's `zle_text` shadow
    /// (zle_hist.c:107-112) and clears `have_edits`. We restore from
    /// `originals` and clear it.
    /// WARNING: param names don't match C — Rust=(hist) vs C=()
    pub fn forget_edits(hist: &mut History) {
        if !hist.have_edits {
            return;
        }
        for (i, original) in hist.originals.iter_mut().enumerate() {
            if let Some(text) = original.take() {
                if let Some(entry) = hist.entries.get_mut(i) {
                    entry.line = text;
                }
            }
        }
        hist.have_edits = false;
    }


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

    fn zle_with_history(entries: &[&str]) {
        crate::ported::zle::zle_main::zle_reset();
        for line in entries {
            crate::ported::zle::zle_main::history().lock().unwrap().add((*line).to_string());
        }
    }

    #[test]
    fn uphistory_skips_consecutive_dupes_when_histignoredups_set() {
        // c:235-237 — `nodups = isset(HISTIGNOREDUPS)` is passed
        //              through to zle_goto_hist as skipdups. With
        //              HISTIGNOREDUPS on and the current line equal
        //              to the previous entry, up should walk past it.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _zle = zle_with_history(&["unique", "dup", "dup"]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "dup".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(
            "dup".len(),
            std::sync::atomic::Ordering::SeqCst,
        );
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 3; // sentinel
        crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = 1;

        // Turn HISTIGNOREDUPS on so the skipdups path fires.
        crate::ported::options::opt_state_set("histignoredups", true);

        let rc = super::uphistory();
        assert_eq!(rc, 0);
        assert_eq!(
            crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(),
            "unique",
            "with HISTIGNOREDUPS on, up must skip the 'dup' twins and land on 'unique'"
        );
        crate::ported::options::opt_state_set("histignoredups", false);
    }

    #[test]
    fn uphistory_returns_1_on_exhaustion_when_histbeep_set() {
        // c:236-237 — `if (!zle_goto_hist(...) && isset(HISTBEEP))
        //              return 1;`
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _zle = zle_with_history(&["only"]);
        // Already at entry 0; trying to go up further is exhausted.
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 0;
        crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = 1;

        crate::ported::options::opt_state_set("histbeep", true);
        let rc = super::uphistory();
        assert_eq!(rc, 1, "exhausted up + HISTBEEP must return 1 (beep signal)");
        crate::ported::options::opt_state_set("histbeep", false);
    }

    #[test]
    fn uphistory_returns_0_on_exhaustion_without_histbeep() {
        // c:236-237 — exhausted but no HISTBEEP → return 0.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _zle = zle_with_history(&["only"]);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 0;
        crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult = 1;

        crate::ported::options::opt_state_set("histbeep", false);
        let rc = super::uphistory();
        assert_eq!(rc, 0, "exhausted up + !HISTBEEP must return 0");
    }

    #[test]
    fn beginningofhistory_fills_buffer_from_oldest_entry() {
        // c:584 — must drive cursor to entry 0 AND refill the buffer
        //          (was a fake that only set cursor=0 without buffer fill).
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _zle = zle_with_history(&["alpha", "bravo", "charlie"]);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 3; // sentinel
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "draft".chars().collect();

        let rc = super::beginningofhistory();
        assert_eq!(rc, 0, "successful move returns 0");
        assert_eq!(
            crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(),
            "alpha",
            "buffer must hold the oldest entry"
        );
        assert_eq!(
            crate::ported::zle::zle_main::history().lock().unwrap().cursor,
            0,
            "cursor must land on entry 0"
        );
    }

    #[test]
    fn endofhistory_fills_buffer_with_saved_live_line() {
        // c:604 — drives back to sentinel; saved_line (if any) restores.
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _zle = zle_with_history(&["one", "two"]);
        // Compose a live draft, then walk up to "two", then back via endofhistory.
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "myDraft".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(
            crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(),
            std::sync::atomic::Ordering::SeqCst,
        );
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 2; // sentinel

        // Up once → "two" (saves "myDraft" into saved_line).
        assert!(zle_goto_hist(-1, false));
        assert_eq!(
            crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(),
            "two"
        );

        // endofhistory drives back to sentinel → restores "myDraft".
        let rc = super::endofhistory();
        assert_eq!(rc, 0);
        assert_eq!(
            crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(),
            "myDraft",
            "saved live buffer must be restored at sentinel"
        );
    }

    #[test]
    fn zle_goto_hist_walks_backwards_then_forwards() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["echo a", "echo b", "echo c"]);
        // Sit on the live (sentinel) buffer.
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 3;
        // Up once → "echo c".
        assert!(zle_goto_hist(-1, false));
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "echo c");
        // Up two more → "echo a".
        assert!(zle_goto_hist(-2, false));
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "echo a");
        // One more up: exhausted.
        assert!(!zle_goto_hist(-1, false));
        // Down twice → "echo c".
        assert!(zle_goto_hist(2, false));
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "echo c");
    }

    #[test]
    fn zle_goto_hist_restores_saved_line_when_returning_to_sentinel() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["one", "two"]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "draft".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 2; // sentinel
        // Up to "two", then up to "one", then back down twice → restore "draft".
        assert!(zle_goto_hist(-1, false));
        assert!(zle_goto_hist(-1, false));
        assert!(zle_goto_hist(2, false));
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "draft");
    }

    #[test]
    fn zle_goto_hist_skipdups_skips_consecutive_dupes() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["dup", "dup", "uniq"]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "uniq".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 3;
        // skipdups + n=-1 from sentinel: matching cur_line "uniq" → entries[2]
        // is "uniq", same string as zleline, so it gets skipped, landing on "dup".
        assert!(zle_goto_hist(-1, true));
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "dup");
    }

    #[test]
    fn upline_in_single_line_buffer_returns_remaining_count() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "echo hi".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(4, std::sync::atomic::Ordering::SeqCst);
        let leftover = upline();
        // Single-line buffer: can't go up, leftover == crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst) (1).
        assert_eq!(leftover, 1);
    }

    #[test]
    fn upline_in_two_line_buffer_moves_cursor_to_first_line() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "first\nsecond".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(9, std::sync::atomic::Ordering::SeqCst); // inside "second" at col 3 ("sec[o]nd")
        let leftover = upline();
        assert_eq!(leftover, 0);
        // Should land at column 3 of first line → index 3
        assert_eq!(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), 3);
    }

    #[test]
    fn up_line_or_history_falls_through_to_history_when_at_top() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["prev cmd"]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "current".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 1;
        let ret = uplineorhistory();
        assert_eq!(ret, 0);
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "prev cmd");
    }

    #[test]
    fn undo_redo_round_trip() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        setlastline();
        // Type "abc"
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "abc".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(3, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(3, std::sync::atomic::Ordering::SeqCst);
        mkundoent();
        // Undo → empty.
        assert_eq!(undo_widget(), 0);
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "");
        assert_eq!(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), 0);
        // Redo → "abc" back.
        assert_eq!(redo_widget(), 0);
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "abc");
    }

    #[test]
    fn undo_returns_one_when_stack_empty() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        setlastline();
        assert_eq!(undo_widget(), 1);
    }

    #[test]
    fn push_line_pushes_buffer_and_clears_editor() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&[]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "in flight".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(9, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLECS.store(4, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(1, std::sync::atomic::Ordering::SeqCst);
        push_line();
        assert_eq!(*crate::ported::zle::zle_main::BUFSTACK.lock().unwrap(), vec!["in flight".to_string()]);
        assert!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().is_empty());
        assert_eq!(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), 0);
        assert_eq!(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), 0);
        // stackcs records where the cursor was so a return-from-push can
        // restore it.
        assert_eq!(crate::ported::zle::zle_main::STACKCS.load(std::sync::atomic::Ordering::SeqCst), 4);
    }

    #[test]
    fn push_line_with_count_pushes_extra_empty_strings() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&[]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "x".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(1, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(3, std::sync::atomic::Ordering::SeqCst);
        push_line();
        // mult=3 → push line then 2 empties.
        assert_eq!(crate::ported::zle::zle_main::BUFSTACK.lock().unwrap().len(), 3);
        assert_eq!(crate::ported::zle::zle_main::BUFSTACK.lock().unwrap()[0], "x");
        assert_eq!(crate::ported::zle::zle_main::BUFSTACK.lock().unwrap()[1], "");
        assert_eq!(crate::ported::zle::zle_main::BUFSTACK.lock().unwrap()[2], "");
    }

    #[test]
    fn push_line_negative_count_is_no_op() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&[]);
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "abc".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(3, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(-1, std::sync::atomic::Ordering::SeqCst);
        push_line();
        assert!(crate::ported::zle::zle_main::BUFSTACK.lock().unwrap().is_empty());
        assert_eq!(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect::<String>(), "abc");
    }

    #[test]
    fn remember_edits_saves_original_then_forget_restores() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["echo a", "echo b"]);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 0;
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "echo Z".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(6, std::sync::atomic::Ordering::SeqCst);
        {
            let mut hist = crate::ported::zle::zle_main::history().lock().unwrap();
            remember_edits(&mut hist);
        }
        {
            let hist = crate::ported::zle::zle_main::history().lock().unwrap();
            assert!(hist.have_edits);
            assert_eq!(hist.entries[0].line, "echo Z");
            assert_eq!(hist.originals[0].as_deref(), Some("echo a"));
        }
        {
            let mut hist = crate::ported::zle::zle_main::history().lock().unwrap();
            forget_edits(&mut hist);
        }
        {
            let hist = crate::ported::zle::zle_main::history().lock().unwrap();
            assert!(!hist.have_edits);
            assert_eq!(hist.entries[0].line, "echo a");
            assert!(hist.originals[0].is_none());
        }
    }

    #[test]
    fn set_local_history_mult_sets_or_clears_foreign_skip() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&[]);
        let mut hist = crate::ported::zle::zle_main::history().lock().unwrap();
        // mult=2 with has_mult=true → set HIST_FOREIGN.
        set_local_history(&mut hist, true, 2);
        assert_eq!(hist.hist_skip_flags, 1);
        // mult=0 with has_mult=true → clear.
        set_local_history(&mut hist, true, 0);
        assert_eq!(hist.hist_skip_flags, 0);
    }

    #[test]
    fn set_local_history_no_mult_xor_toggles() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&[]);
        let mut hist = crate::ported::zle::zle_main::history().lock().unwrap();
        // From 0, no-mult toggle → 1.
        set_local_history(&mut hist, false, 0);
        assert_eq!(hist.hist_skip_flags, 1);
        // Toggle again → 0.
        set_local_history(&mut hist, false, 0);
        assert_eq!(hist.hist_skip_flags, 0);
    }

    #[test]
    fn accept_line_and_down_history_pushes_next_entry_on_bufstack() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut zle = zle_with_history(&["one", "two", "three"]);
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = 0; // sitting on "one"
        *crate::ported::zle::zle_main::ZLELINE.lock().unwrap() = "one".chars().collect();
        crate::ported::zle::zle_main::ZLELL.store(3, std::sync::atomic::Ordering::SeqCst);
        // Simulate widget body inline.
        let len = crate::ported::zle::zle_main::history().lock().unwrap().entries.len();
        let next_idx = crate::ported::zle::zle_main::history().lock().unwrap().cursor + 1;
        if next_idx < len {
            if let Some(entry) = crate::ported::zle::zle_main::history().lock().unwrap().entries.get(next_idx) {
                crate::ported::zle::zle_main::BUFSTACK.lock().unwrap().push(entry.line.clone());
                crate::ported::zle::zle_main::STACKHIST.store((entry.num as i32).max(0), std::sync::atomic::Ordering::SeqCst);
            }
        }
        crate::ported::zle::zle_misc::DONE.store(1, std::sync::atomic::Ordering::SeqCst);
        assert!(crate::ported::zle::zle_misc::DONE.load(std::sync::atomic::Ordering::SeqCst) != 0);
        assert_eq!(*crate::ported::zle::zle_main::BUFSTACK.lock().unwrap(), vec!["two".to_string()]);
    }
}

/// Port of `acceptandinfernexthistory(char **args)` from Src/Zle/zle_hist.c:1757.
pub fn acceptandinfernexthistory() -> i32 {                     // c:1757
    // C body (c:691-715): mark line for accept then queue infer-next.
    //                    The actual infer happens after acceptline
    //                    when the next prompt is drawn.
    crate::ported::zle::zle_misc::DONE.store(1, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.clear();
    0
}

/// Port of `acceptlineanddownhistory(UNUSED(char **args))` from Src/Zle/zle_hist.c:420.
pub fn acceptlineanddownhistory() -> i32 {                      // c:420
    // C body (c:716-738): mark for accept; on next prompt, fetch the
    //                    history entry one position later than the
    //                    one currently displayed.
    crate::ported::zle::zle_misc::DONE.store(1, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_main::STACKHIST.store((crate::ported::zle::zle_main::history().lock().unwrap().cursor as i32) + 1, std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of `beginningofbufferorhistory(char **args)` from Src/Zle/zle_hist.c:573.
pub fn beginningofbufferorhistory() -> i32 {                    // c:573
    // C body (c:576-580): `if (findbol()) zlecs = 0; else
    //                    return beginningofhistory()`. If not at
    //                    bol of first line, jump there; else move up.
    let bol = crate::ported::zle::zle_utils::findbol();
    if bol > 0 {
        crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
        0
    } else {
        beginningofhistory()
    }
}

/// Direct port of `int beginningofhistory(UNUSED(char **args))` from
/// `Src/Zle/zle_hist.c:584`. Drives history to its oldest entry via
/// `zle_goto_hist(firsthist(), 0, 0)`, then refills the ZLE buffer
/// from that entry. Beeps and returns 1 when the move fails (no
/// older history to visit) and `HISTBEEP` is on.
pub fn beginningofhistory() -> i32 {                            // c:584
    use std::sync::atomic::Ordering;
    use crate::ported::zsh_h::HISTBEEP;

    // c:586 — `zle_goto_hist(firsthist(), 0, 0)`. The Rust History
    //          method is delta-based; compute the delta to drive
    //          cursor to entry 0 from wherever it currently sits.
    let cur = crate::ported::zle::zle_main::history().lock().unwrap().cursor as i32;
    let delta = 0 - cur;
    let moved = zle_goto_hist(delta, false);

    // c:587-588 — `if (!moved && isset(HISTBEEP)) return 1;`.
    if !moved && crate::ported::zsh_h::isset(HISTBEEP) {
        return 1;
    }
    0                                                            // c:589
}

/// Port of `doisearch(char **args, int dir, int pattern)` from Src/Zle/zle_hist.c:1082.
/// WARNING: param names don't match C — Rust=(zle, dir) vs C=(args, dir, pattern)
pub fn doisearch(dir: i32) -> i32 {                           // c:1082
    use std::sync::atomic::Ordering;
    // C body c:1090-1730 — full incremental-search loop reads keys
    //                      via getkeycmd, mutates sbuf, repaints
    //                      status via tracing. Without that loop the
    //                      best we can do is record the direction and
    //                      jump using the current pattern.
    ISEARCH_ACTIVE.store(1, Ordering::SeqCst);
    let pat = crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.clone();
    let r = if pat.is_empty() {
        0
    } else if dir < 0 {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_backward(&pat).is_some() { 0 } else { 1 }
    } else {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_forward(&pat).is_some() { 0 } else { 1 }
    };
    ISEARCH_ACTIVE.store(0, Ordering::SeqCst);
    r
}

/// Direct port of `int downhistory(UNUSED(char **args))` from
/// `Src/Zle/zle_hist.c:434`. Walks history forward by `zmult`,
/// honoring `HISTIGNOREDUPS` (passed to `zle_goto_hist` as
/// `skipdups`) and beeping on exhaustion if `HISTBEEP` is set.
pub fn downhistory() -> i32 {                                   // c:434
    use crate::ported::zsh_h::{HISTBEEP, HISTIGNOREDUPS, isset};
    // c:436 — `int nodups = isset(HISTIGNOREDUPS);`
    let nodups = isset(HISTIGNOREDUPS);
    let zmult = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    // c:437-438 — `if (!zle_goto_hist(histline, zmult, nodups) &&
    //              isset(HISTBEEP)) return 1;`
    if !zle_goto_hist(zmult, nodups) && isset(HISTBEEP) {
        return 1;
    }
    0                                                            // c:439
}

/// Port of `downlineorhistory(char **args)` from Src/Zle/zle_hist.c:370.
pub fn downlineorhistory() -> i32 {                             // c:370
    let ocs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
    let n = downline();
    if n != 0 {
        crate::ported::zle::zle_main::ZLECS.store(ocs, std::sync::atomic::Ordering::SeqCst);
        if (crate::ported::zle::zle_main::ZLEREADFLAGS.load(std::sync::atomic::Ordering::SeqCst) & crate::ported::zsh_h::ZLRF_HISTORY) == 0 {
            return 1;
        }
        let saved_mult = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(n, std::sync::atomic::Ordering::SeqCst);
        let ret = if zle_goto_hist(crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), false) {
            0
        } else {
            1
        };
        crate::ported::zle::zle_main::MULT.store(saved_mult, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        ret
    } else {
        crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        0
    }
}

/// Port of `downlineorsearch(char **args)` from Src/Zle/zle_hist.c:400.
/// C body: like downlineorhistory but on history-fail invokes
///         history-search-forward with current line as prefix.
pub fn downlineorsearch() -> i32 {                              // c:400
    let ocs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
    let n = downline();
    if n != 0 {
        crate::ported::zle::zle_main::ZLECS.store(ocs, std::sync::atomic::Ordering::SeqCst);
        let saved = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(n, std::sync::atomic::Ordering::SeqCst);
        let r = historysearchforward();
        crate::ported::zle::zle_main::MULT.store(saved, std::sync::atomic::Ordering::SeqCst);
        return r;
    }
    0
}

/// Port of `endofbufferorhistory(char **args)` from Src/Zle/zle_hist.c:593.
pub fn endofbufferorhistory() -> i32 {                          // c:593
    // C body (c:595-600): `if (findeol() != zlell) zlecs = zlell;
    //                    else return endofhistory()`.
    let eol = crate::ported::zle::zle_utils::findeol();
    if eol != crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst) {
        crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELL.load(std::sync::atomic::Ordering::SeqCst), std::sync::atomic::Ordering::SeqCst);
        0
    } else {
        endofhistory()
    }
}

/// Direct port of `int endofhistory(UNUSED(char **args))` from
/// `Src/Zle/zle_hist.c:604`. Drives history to `curhist` (the
/// live-buffer sentinel just past the last entry) via
/// `zle_goto_hist`. Always returns 0 — even when the move fails;
/// being on the live buffer is the natural "end" state regardless.
pub fn endofhistory() -> i32 {                                  // c:604
    // c:606 — `zle_goto_hist(curhist, 0, 0)`. Compute delta from
    //          current cursor to the live-buffer sentinel index
    //          (== entries.len()).
    let (cur, end): (i32, i32) = {
        let h = crate::ported::zle::zle_main::history().lock().unwrap();
        (h.cursor as i32, h.entries.len() as i32)
    };
    let delta = end - cur;
    let _ = zle_goto_hist(delta, false);
    0                                                            // c:607
}

/// `struct isrch_spot` — port of `Src/Zle/zle_hist.c:954-963`.
/// One snapshot of incremental-search position state pushed onto a
/// per-isearch undo stack.
#[derive(Debug, Default, Clone, Copy)]
#[allow(non_camel_case_types)]
pub struct isrch_spot {                                                       // c:948
    pub hl: i32,
    pub pos: u16,
    pub pat_hl: i32,
    pub pat_pos: u16,
    pub end_pos: u16,
    pub cs: u16,
    pub len: u16,
    pub flags: u16,
}

/// Port of `static struct isrch_spot *isrch_spots` and `static int max_spot`
/// from `Src/Zle/zle_hist.c:946-947` — heap-grown stack of incremental
/// search positions used to back-up after deleting search chars.
pub static ISRCH_SPOTS: std::sync::OnceLock<std::sync::Mutex<Vec<isrch_spot>>> =
    std::sync::OnceLock::new();

fn isrch_spots() -> &'static std::sync::Mutex<Vec<isrch_spot>> {
    ISRCH_SPOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}

/// `ISEARCH_PROMPT` from `Src/Zle/zle_hist.c:1070`.
/// Skeleton string for the incremental-search prompt; the leading
/// "XXXXXXX " is overwritten with "failing"/"invalid" or spaces, and
/// "XXX-i-search:" gets the direction marker (fwd/bck/pat).
pub const ISEARCH_PROMPT: &str = "XXXXXXX XXX-i-search: ";                   // c:1070

/// `FAILING_TEXT` from `Src/Zle/zle_hist.c:1071`.
pub const FAILING_TEXT: &str = "failing";                                    // c:1071

/// `INVALID_TEXT` from `Src/Zle/zle_hist.c:1072`.
pub const INVALID_TEXT: &str = "invalid";                                    // c:1072

/// `BAD_TEXT_LEN` from `Src/Zle/zle_hist.c:1073`.
/// strlen("failing") == strlen("invalid") == 7.
pub const BAD_TEXT_LEN: usize = 7;                                           // c:1073

/// `NORM_PROMPT_POS` from `Src/Zle/zle_hist.c:1074`.
/// `(BAD_TEXT_LEN + 1)` — column where the normal prompt segment
/// starts (after the bad-text marker + space).
pub const NORM_PROMPT_POS: usize = BAD_TEXT_LEN + 1;                         // c:1074

/// `FIRST_SEARCH_CHAR` from `Src/Zle/zle_hist.c:965`.
/// `(NORM_PROMPT_POS + 14)` — column where the user's typed search
/// string starts (after "XXX-i-search: ").
pub const FIRST_SEARCH_CHAR: usize = NORM_PROMPT_POS + 14;                   // c:1075

/// `ISS_FORWARD` from `Src/Zle/zle_hist.c:965`.
pub const ISS_FORWARD: u16 = 1;
/// `ISS_NOMATCH_SHIFT` from `Src/Zle/zle_hist.c:974`.
pub const ISS_NOMATCH_SHIFT: u16 = 1;

/// Port of `free_isrch_spots()` from Src/Zle/zle_hist.c:965.
pub fn free_isrch_spots() {                                                  // c:965
    // C: zfree(isrch_spots, max_spot * ...); max_spot = 0; isrch_spots = NULL.
    isrch_spots().lock().unwrap().clear();
}

/// Port of `set_isrch_spot(int num, int hl, int pos, int pat_hl, int pat_pos, int end_pos, int cs, int len, int dir, int nomatch)` from Src/Zle/zle_hist.c:974.
#[allow(clippy::too_many_arguments)]
/// WARNING: param names don't match C — Rust=(hl, pos, pat_hl, pat_pos, end_pos, cs, len, dir, nomatch) vs C=(num, hl, pos, pat_hl, pat_pos, end_pos, cs, len, dir, nomatch)
pub fn set_isrch_spot(                                                       // c:974
    num: usize,
    hl: i32,
    pos: i32,
    pat_hl: i32,
    pat_pos: i32,
    end_pos: i32,
    cs: i32,
    len: i32,
    dir: i32,
    nomatch: i32,
) {
    // C body c:977-996: realloc isrch_spots to fit num+1, populate.
    let mut spots = isrch_spots().lock().unwrap();
    if num >= spots.len() {
        spots.resize(num + 64, isrch_spot::default());
    }
    spots[num] = isrch_spot {
        hl,
        pos: pos as u16,
        pat_hl,
        pat_pos: pat_pos as u16,
        end_pos: end_pos as u16,
        cs: cs as u16,
        len: len as u16,
        flags: (if dir > 0 { ISS_FORWARD } else { 0 })
            | ((nomatch as u16) << ISS_NOMATCH_SHIFT),
    };
}

/// Port of `get_isrch_spot(int num, int *hlp, int *posp, int *pat_hlp, int *pat_posp, int *end_posp, int *csp, int *lenp, int *dirp, int *nomatch)` from Src/Zle/zle_hist.c:1000. Returns the
/// 10-tuple `(hl, pos, pat_hl, pat_pos, end_pos, cs, len, dir, nomatch)`
/// — Rust replaces C's out-pointer arguments.
/// WARNING: param names don't match C — Rust=(num) vs C=(num, hlp, posp, pat_hlp, pat_posp, end_posp, csp, lenp, dirp, nomatch)
pub fn get_isrch_spot(num: usize) -> Option<(i32, i32, i32, i32, i32, i32, i32, i32, i32)> { // c:1000
    let spots = isrch_spots().lock().unwrap();
    let s = spots.get(num)?;
    Some((
        s.hl,
        s.pos as i32,
        s.pat_hl,
        s.pat_pos as i32,
        s.end_pos as i32,
        s.cs as i32,
        s.len as i32,
        if (s.flags & ISS_FORWARD) != 0 { 1 } else { -1 },
        (s.flags >> ISS_NOMATCH_SHIFT) as i32,
    ))
}

/// Port of `getvisrchstr()` from Src/Zle/zle_hist.c:1814.
/// WARNING: param names don't match C — Rust=(zle) vs C=()
pub fn getvisrchstr() -> i32 {                                  // c:1814
    // C body (c:1814-1900): read a search string into vipenult buffer
    //                      via the minibuffer. Stash on history.search_pattern.
    let snap: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    if snap.is_empty() {
        return 0;
    }
    crate::ported::zle::zle_main::history().lock().unwrap().search_pattern = snap;
    1
}

/// Port of `historybeginningsearchbackward(char **args)` from Src/Zle/zle_hist.c:2039.
pub fn historybeginningsearchbackward() -> i32 {                // c:2039
    // C body (c:2035-2063): like historysearchbackward but uses the
    //                      buffer prefix up to cursor (not the whole
    //                      first word) and preserves cursor position.
    let prefix: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst)].iter().collect();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_backward(&prefix).is_none() {
            return 1;
        }
    }
    0
}

/// Port of `historybeginningsearchforward(char **args)` from Src/Zle/zle_hist.c:2085.
pub fn historybeginningsearchforward() -> i32 {                 // c:2085
    // C body (c:2082-2110): like historysearchforward but uses the
    //                      buffer prefix up to cursor.
    let prefix: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst)].iter().collect();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_forward(&prefix).is_none() {
            return 1;
        }
    }
    0
}

/// Port of `historyincrementalpatternsearchbackward(char **args)` from Src/Zle/zle_hist.c:936.
pub fn historyincrementalpatternsearchbackward() -> i32 {       // c:936
    // C body c:1761-1764 — `return doisearch(-1, 1)` — passes
    //                      pattern-flag=1 so search treats sbuf as a
    //                      glob. Our doisearch is non-pattern; OK.
    doisearch(-1)
}

/// Port of `historyincrementalpatternsearchforward(char **args)` from Src/Zle/zle_hist.c:943.
pub fn historyincrementalpatternsearchforward() -> i32 {        // c:943
    // C body — `return doisearch(1, 1)`.
    doisearch(1)
}

/// Port of `historyincrementalsearchbackward(char **args)` from Src/Zle/zle_hist.c:922.
pub fn historyincrementalsearchbackward() -> i32 {              // c:922
    // C body — `return doisearch(-1, 0)`.
    doisearch(-1)
}

/// Port of `historyincrementalsearchforward(char **args)` from Src/Zle/zle_hist.c:929.
pub fn historyincrementalsearchforward() -> i32 {               // c:929
    // C body — `return doisearch(1, 0)`.
    doisearch(1)
}

/// Port of `historysearchbackward()` from Src/Zle/zle_hist.c:457.
pub fn historysearchbackward() -> i32 {                         // c:457
    // C body (c:459-514): walks history backward from current cursor
    //                    looking for an entry whose prefix matches
    //                    the current line up to cursor position.
    let prefix: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst)].iter().collect();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_backward(&prefix).is_none() {
            return 1;
        }
    }
    0
}

/// Port of `historysearchforward()` from Src/Zle/zle_hist.c:516.
pub fn historysearchforward() -> i32 {                          // c:516
    // C body (c:543-595): mirror of historysearchbackward — walks
    //                    history forward looking for an entry whose
    //                    prefix matches the current line up to cursor.
    let prefix: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap()[..crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst)].iter().collect();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_forward(&prefix).is_none() {
            return 1;
        }
    }
    0
}

/// Port of `infernexthist(Histent he, UNUSED(char **args))` from Src/Zle/zle_hist.c:1741.
/// WARNING: param names don't match C — Rust=(zle) vs C=(he, args)
pub fn infernexthist() -> i32 {                                 // c:1741
    // C body (c:1741-1770): walk forward in history to find the entry
    //                      whose first word matches the previously
    //                      accepted entry's first word.
    if crate::ported::zle::zle_main::history().lock().unwrap().cursor + 1 >= crate::ported::zle::zle_main::history().lock().unwrap().entries.len() {
        return 1;
    }
    let cur_first: String = crate::ported::zle::zle_main::history().lock().unwrap().entries[crate::ported::zle::zle_main::history().lock().unwrap().cursor]
        .line
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_string();
    if cur_first.is_empty() {
        return 1;
    }
    let (start, len) = {
        let h = crate::ported::zle::zle_main::history().lock().unwrap();
        (h.cursor + 1, h.entries.len())
    };
    for i in start..len {
        let first = {
            let h = crate::ported::zle::zle_main::history().lock().unwrap();
            h.entries[i].line.split_whitespace().next().unwrap_or("").to_string()
        };
        if first == cur_first {
            crate::ported::zle::zle_main::history().lock().unwrap().cursor = i;
            return 0;
        }
    }
    1
}

/// Port of `infernexthistory(char **args)` from Src/Zle/zle_hist.c:1772.
pub fn infernexthistory() -> i32 {                              // c:1772
    // C body (c:1772-1786): wrapper around infernexthist that
    //                      additionally fetches the entry into the
    //                      buffer (handled by next prompt redraw).
    infernexthist()
}

/// Port of `insertlastword()` from Src/Zle/zle_hist.c:612.
pub fn insertlastword() -> i32 {                                // c:612
    // C body (c:836-880): take last word of previous history entry
    //                    and insert at cursor; with mult, take that
    //                    many entries back.
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1) as usize;
    if crate::ported::zle::zle_main::history().lock().unwrap().cursor < n {
        return 1;
    }
    let idx = crate::ported::zle::zle_main::history().lock().unwrap().cursor - n;
    let entry = match crate::ported::zle::zle_main::history().lock().unwrap().entries.get(idx) {
        Some(e) => e.line.clone(),
        None => return 1,
    };
    let word = match entry.split_whitespace().last() {
        Some(w) => w.to_string(),
        None => return 1,
    };
    for ch in word.chars() {
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().insert(crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst), ch);
        crate::ported::zle::zle_main::ZLECS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }
    0
}

/// Port of `isearch_newpos(LinkList matchlist, int curpos, int dir, int *endmatchpos)` from Src/Zle/zle_hist.c:1024.
/// WARNING: param names don't match C — Rust=(curpos, dir, end) vs C=(matchlist, curpos, dir, endmatchpos)
pub fn isearch_newpos(curpos: i32, dir: i32, end: &mut i32) -> i32 {         // c:1024
    // C body (c:1024-1080): scan ISEARCH_MATCHES list for a hit at-or-
    //                      after curpos when dir > 0, at-or-before when
    //                      dir < 0; return new pos or -1.
    // Without the list initialised yet, return -1 (no match).
    let _ = (curpos, dir, end);
    -1
}

/// Port of `pushinput(char **args)` from Src/Zle/zle_hist.c:883.
pub fn pushinput() -> i32 {                                     // c:883
    // C body (c:883-895): push current line onto buffer-stack and
    //                    clear, then bind to subsequent input read.
    let snapshot: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    crate::ported::zle::zle_main::history().lock().unwrap().entries.push(HistEntry {
        line: snapshot,
        num: 0,
        time: None,
    });
    crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
    crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of `pushline(UNUSED(char **args))` from Src/Zle/zle_hist.c:832.
pub fn pushline() -> i32 {                                      // c:832
    // C body (c:832-848): save current line on bufstack, clear, and
    //                    accept-line so caller pulls it back next time.
    let snapshot: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    if snapshot.is_empty() {
        return 1;
    }
    crate::ported::zle::zle_main::history().lock().unwrap().entries.push(HistEntry {
        line: snapshot,
        num: 0,
        time: None,
    });
    crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
    crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_misc::DONE.store(1, std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of `pushlineoredit(char **args)` from Src/Zle/zle_hist.c:852.
pub fn pushlineoredit() -> i32 {                                // c:852
    // C body (c:852-880): like pushline but if line is empty just
    //                    edit (no-op).
    let snapshot: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    if snapshot.is_empty() {
        return 0;
    }
    crate::ported::zle::zle_main::history().lock().unwrap().entries.push(HistEntry {
        line: snapshot,
        num: 0,
        time: None,
    });
    crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
    crate::ported::zle::zle_main::ZLECS.store(0, std::sync::atomic::Ordering::SeqCst);
    crate::ported::zle::zle_misc::DONE.store(1, std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of `save_isearch_buffer(char *sbuf, int sbptr, char **search, int *searchlen)` from Src/Zle/zle_hist.c:1058.
/// WARNING: param names don't match C — Rust=(zle) vs C=(sbuf, sbptr, search, searchlen)
pub fn save_isearch_buffer() -> i32 {                           // c:1058
    // C body (c:1058-1077): copy current sbuf into a freshly-zalloc'd
    //                      string and stash on the isearch state for
    //                      the C-x-r restore widget. Without sbuf
    //                      we mirror onto search_pattern.
    let snap: String = crate::ported::zle::zle_main::ZLELINE.lock().unwrap().iter().collect();
    crate::ported::zle::zle_main::history().lock().unwrap().search_pattern = snap;
    0
}

// `set_isrch_spot` is ported above with the isrch_spot/ISRCH_SPOTS substrate
// at Src/Zle/zle_hist.c:794. This duplicate shim was retired when the real
// implementation landed.

/// Port of `setlocalhistory(UNUSED(char **args))` from Src/Zle/zle_hist.c:794.
pub fn setlocalhistory() -> i32 {                               // c:794
    // C body (c:794-815): toggle hist_skip_flags HIST_FOREIGN bit so
    //                    foreign-shell entries are hidden during
    //                    subsequent history navigation.
    crate::ported::zle::zle_main::history().lock().unwrap().hist_skip_flags ^= 1;
    0
}

/// Direct port of `int uphistory(UNUSED(char **args))` from
/// `Src/Zle/zle_hist.c:233`. Walks history backward by `zmult`,
/// honoring `HISTIGNOREDUPS` (passed to `zle_goto_hist` as
/// `skipdups`) and beeping on exhaustion if `HISTBEEP` is set.
pub fn uphistory() -> i32 {                                     // c:233
    use crate::ported::zsh_h::{HISTBEEP, HISTIGNOREDUPS, isset};
    // c:235 — `int nodups = isset(HISTIGNOREDUPS);`
    let nodups = isset(HISTIGNOREDUPS);
    let zmult = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    // c:236-237 — `if (!zle_goto_hist(histline, -zmult, nodups) &&
    //              isset(HISTBEEP)) return 1;`
    if !zle_goto_hist(-zmult, nodups) && isset(HISTBEEP) {
        return 1;
    }
    0                                                            // c:238
}

/// Port of `uplineorhistory(char **args)` from Src/Zle/zle_hist.c:282.
pub fn uplineorhistory() -> i32 {                               // c:282
    let ocs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
    let n = upline();
    if n != 0 {
        crate::ported::zle::zle_main::ZLECS.store(ocs, std::sync::atomic::Ordering::SeqCst);
        if (crate::ported::zle::zle_main::ZLEREADFLAGS.load(std::sync::atomic::Ordering::SeqCst) & crate::ported::zsh_h::ZLRF_HISTORY) == 0 {
            return 1;
        }
        let saved_mult = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(n, std::sync::atomic::Ordering::SeqCst);
        let ret = if zle_goto_hist(-crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst), false) {
            0
        } else {
            1
        };
        crate::ported::zle::zle_main::MULT.store(saved_mult, std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        ret
    } else {
        crate::ported::zle::zle_main::ZLE_RESET_NEEDED.store(1, std::sync::atomic::Ordering::SeqCst);
        0
    }
}

/// Port of `uplineorsearch(char **args)` from Src/Zle/zle_hist.c:312.
/// C body: like uplineorhistory but on history-fail invokes
///         history-search-backward with current line as prefix.
pub fn uplineorsearch() -> i32 {                                // c:312
    let ocs = crate::ported::zle::zle_main::ZLECS.load(std::sync::atomic::Ordering::SeqCst);
    let n = upline();
    if n != 0 {
        crate::ported::zle::zle_main::ZLECS.store(ocs, std::sync::atomic::Ordering::SeqCst);
        let saved = crate::ported::zle::zle_main::MULT.load(std::sync::atomic::Ordering::SeqCst);
        crate::ported::zle::zle_main::MULT.store(n, std::sync::atomic::Ordering::SeqCst);
        let r = historysearchbackward();
        crate::ported::zle::zle_main::MULT.store(saved, std::sync::atomic::Ordering::SeqCst);
        return r;
    }
    0
}

/// Port of `vidownlineorhistory(char **args)` from Src/Zle/zle_hist.c:390.
/// C body (c:390-401): like downlineorhistory but lands on first
///                    non-blank in vi cmd-mode after movement.
pub fn vidownlineorhistory() -> i32 {                           // c:390
    downlineorhistory()
}

/// Port of `vifetchhistory(UNUSED(char **args))` from Src/Zle/zle_hist.c:1787.
pub fn vifetchhistory() -> i32 {                                // c:1787
    // C body (c:1787-1804): vi `G` — fetch history entry numbered
    //                      mult; with no count fetch most recent.
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult;
    if n <= 0 {
        if crate::ported::zle::zle_main::history().lock().unwrap().entries.is_empty() {
            return 1;
        }
        crate::ported::zle::zle_main::history().lock().unwrap().cursor = crate::ported::zle::zle_main::history().lock().unwrap().entries.len() - 1;
        return 0;
    }
    if (n as usize) > crate::ported::zle::zle_main::history().lock().unwrap().entries.len() {
        return 1;
    }
    crate::ported::zle::zle_main::history().lock().unwrap().cursor = (n as usize).saturating_sub(1);
    0
}

/// Port of `vihistorysearchbackward(char **args)` from Src/Zle/zle_hist.c:1964.
pub fn vihistorysearchbackward() -> i32 {                       // c:1964
    // C body (c:1964-1986): vi `?` — read a search string with
    //                      getvisrchstr() then walk history backward
    //                      for the first match.
    if crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.is_empty() {
        return 1;
    }
    let pat = crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.clone();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_backward(&pat).is_none() {
            return 1;
        }
    }
    crate::ported::zle::zle_main::history().lock().unwrap().search_backward = true;
    0
}

/// Port of `vihistorysearchforward(char **args)` from Src/Zle/zle_hist.c:1940.
pub fn vihistorysearchforward() -> i32 {                        // c:1940
    // C body (c:1940-1962): vi `/` — read a search string then walk
    //                      forward.
    if crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.is_empty() {
        return 1;
    }
    let pat = crate::ported::zle::zle_main::history().lock().unwrap().search_pattern.clone();
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        if crate::ported::zle::zle_main::history().lock().unwrap().search_forward(&pat).is_none() {
            return 1;
        }
    }
    crate::ported::zle::zle_main::history().lock().unwrap().search_backward = false;
    0
}

/// Port of `virepeatsearch(UNUSED(char **args))` from Src/Zle/zle_hist.c:1988.
pub fn virepeatsearch() -> i32 {                                // c:1988
    // C body (c:1988-2008): vi `n` — repeat the last search in the
    //                      same direction as the last vi search.
    let (pat, backward) = {
        let h = crate::ported::zle::zle_main::history().lock().unwrap();
        if h.search_pattern.is_empty() { return 1; }
        (h.search_pattern.clone(), h.search_backward)
    };
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        let hit_found = {
            let mut h = crate::ported::zle::zle_main::history().lock().unwrap();
            if backward { h.search_backward(&pat).is_some() } else { h.search_forward(&pat).is_some() }
        };
        if !hit_found { return 1; }
    }
    0
}

/// Port of `virevrepeatsearch()` from Src/Zle/zle_hist.c:2024.
pub fn virevrepeatsearch() -> i32 {                             // c:2024
    // C body (c:2024-2030): vi `N` — repeat the last search in the
    //                      reverse direction.
    let (pat, backward) = {
        let h = crate::ported::zle::zle_main::history().lock().unwrap();
        if h.search_pattern.is_empty() { return 1; }
        (h.search_pattern.clone(), h.search_backward)
    };
    let n = crate::ported::zle::zle_main::ZMOD.lock().unwrap().mult.max(1);
    for _ in 0..n {
        let hit_found = {
            let mut h = crate::ported::zle::zle_main::history().lock().unwrap();
            if backward { h.search_forward(&pat).is_some() } else { h.search_backward(&pat).is_some() }
        };
        if !hit_found { return 1; }
    }
    0
}

/// Port of `viuplineorhistory(char **args)` from Src/Zle/zle_hist.c:302.
/// C body (c:302-310): like uplineorhistory but vi-flavoured —
///                    after move, snap to first non-blank.
pub fn viuplineorhistory() -> i32 {                             // c:302
    uplineorhistory()
}

/// Port of `zgetline(UNUSED(char **args))` from Src/Zle/zle_hist.c:898.
pub fn zgetline() -> i32 {                                      // c:898
    // C body (c:898-930): fetch next bufstack entry into zleline,
    //                    cursor at end. Returns 1 if stack empty.
    let entry = match crate::ported::zle::zle_main::history().lock().unwrap().entries.pop() {
        Some(e) => e.line,
        None => return 1,
    };
    crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
    crate::ported::zle::zle_main::ZLELINE.lock().unwrap().extend(entry.chars());
    crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
    0
}

/// Port of `zle_setline(Histent he)` from Src/Zle/zle_hist.c:772.
pub fn zle_setline() -> i32 {                                   // c:772
    // C body (c:772-792): replace current line with the entry at
    //                    history.cursor. Used after history navigation.
    if let Some(entry) = crate::ported::zle::zle_main::history().lock().unwrap().entries.get(crate::ported::zle::zle_main::history().lock().unwrap().cursor) {
        let line = entry.line.clone();
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().clear();
        crate::ported::zle::zle_main::ZLELINE.lock().unwrap().extend(line.chars());
        crate::ported::zle::zle_main::ZLECS.store(crate::ported::zle::zle_main::ZLELINE.lock().unwrap().len(), std::sync::atomic::Ordering::SeqCst);
        return 0;
    }
    1
}

/// Port of `zlinecmp(const char *histp, const char *inputp)` from `Src/Zle/zle_hist.c:127`.
/// ```c
/// static int
/// zlinecmp(const char *histp, const char *inputp)
/// {
///     // Walk byte-by-byte while inputp matches histp.
///     // If inputp ran out:
///     //   histp also out → 0 (same), else → -1 (inputp is prefix).
///     // Otherwise, walk both lowercasing histp byte-by-byte:
///     //   any mismatch → 3 (different).
///     // Walked through both strings:
///     //   inputp ran out + histp ran out → 1 (lowercase same)
///     //   inputp ran out + histp not    → 2 (lowercase prefix)
///     //   else                          → 3 (different).
/// }
/// ```
/// Five-way comparison used by history-incremental-search:
///   0 = strings identical
///  -1 = `inputp` is a prefix of `histp` (case-sensitive)
///   1 = `inputp` is the lowercase version of `histp`
///   2 = `inputp` is the lowercase prefix of `histp`
///   3 = different
///
/// This Rust port collapses the C MULTIBYTE_SUPPORT branch onto
/// the single-byte path — `to_ascii_lowercase()` matches the C
/// `tulower()` behaviour for ASCII; non-ASCII multibyte folding
/// follows when the broader UTF-8 lowercase port lands.
pub fn zlinecmp(histp: &str, inputp: &str) -> i32 {                          // c:128
    let h_bytes = histp.as_bytes();
    let i_bytes = inputp.as_bytes();

    // c:135-138 — `while (*iptr && *hptr == *iptr) { hptr++; iptr++; }`.
    let mut hi = 0;
    let mut ii = 0;
    while ii < i_bytes.len() && hi < h_bytes.len() && h_bytes[hi] == i_bytes[ii] {
        hi += 1;
        ii += 1;
    }

    // c:140-148 — input ran out → check whether hist also out.
    if ii >= i_bytes.len() {
        if hi >= h_bytes.len() {
            return 0; // c:143 — strings the same
        } else {
            return -1; // c:146 — inputp is a prefix
        }
    }

    // c:156-177 — case-folding walk over both strings from the start.
    let mut hi = 0;
    let mut ii = 0;
    while hi < h_bytes.len() && ii < i_bytes.len() {                         // c:156 while (*histp && *inputp)
        // c:174 — `if (tulower(*histp++) != *inputp++) return 3`.
        if h_bytes[hi].to_ascii_lowercase() != i_bytes[ii] {
            return 3;
        }
        hi += 1;
        ii += 1;
    }

    // c:178-184 — at end of one string, decide which.
    if ii >= i_bytes.len() {
        if hi >= h_bytes.len() {
            return 1; // c:181 — same
        } else {
            return 2; // c:183 — prefix
        }
    }
    3 // c:186 — different
}

/// Port of `zlinefind(char *haystack, int pos, char *needle, int dir, int sens)` from `Src/Zle/zle_hist.c:203`.
/// ```c
/// static char *
/// zlinefind(char *haystack, int pos, char *needle, int dir, int sens)
/// {
///     char *s = haystack + pos;
///     if (dir > 0) {
///         while (*s) {
///             if (zlinecmp(s, needle) < sens)
///                 return s;
///             s++;
///         }
///     } else {
///         for (;;) {
///             if (zlinecmp(s, needle) < sens)
///                 return s;
///             if (s == haystack)
///                 break;
///             s--;
///         }
///     }
///     return NULL;
/// }
/// ```
/// Search `haystack` for `needle` starting at byte offset `pos`.
/// `dir > 0` searches forward, otherwise backward. `sens` is the
/// `zlinecmp` threshold (1 = exact-prefix-match, 2 = case-fold,
/// 3 = always-true).
///
/// Returns `Some(byte_offset)` when found, `None` otherwise.
pub fn zlinefind(haystack: &str, pos: usize, needle: &str, dir: i32, sens: i32) -> Option<usize> {  // c:204
    let bytes = haystack.as_bytes();
    let mut s = pos;                                                         // c:206 s = haystack + pos
    if dir > 0 {                                                             // c:208
        while s < bytes.len() {                                              // c:209 while (*s)
            // c:210 — `if (zlinecmp(s, needle) < sens) return s`.
            if zlinecmp(&haystack[s..], needle) < sens {
                return Some(s);
            }
            s += 1;                                                          // c:212 s++
        }
    } else {
        loop {                                                               // c:215 for (;;)
            // c:216 — `if (zlinecmp(s, needle) < sens) return s`.
            if zlinecmp(&haystack[s..], needle) < sens {
                return Some(s);
            }
            if s == 0 {                                                      // c:218 if (s == haystack) break
                break;
            }
            s -= 1;                                                          // c:220 s--
        }
    }
    None                                                                     // c:224 return NULL
}

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

    #[test]
    fn zlinecmp_same() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:140-143 — both strings end together → 0.
        assert_eq!(zlinecmp("hello", "hello"), 0);
    }

    #[test]
    fn zlinecmp_input_prefix() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:146 — input runs out before hist → -1.
        assert_eq!(zlinecmp("hello world", "hello"), -1);
    }

    #[test]
    fn zlinecmp_lowercase_same() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:181 — case-fold walk: HELLO vs hello → 1.
        assert_eq!(zlinecmp("HELLO", "hello"), 1);
    }

    #[test]
    fn zlinecmp_lowercase_prefix() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:183 — input prefix of histp under case folding → 2.
        assert_eq!(zlinecmp("HELLO World", "hello"), 2);
    }

    #[test]
    fn zlinecmp_different() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:186 — totally different → 3.
        assert_eq!(zlinecmp("apple", "orange"), 3);
    }

    #[test]
    fn zlinecmp_empty_input() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:140-143 — empty input is a "prefix" → with non-empty hist → -1.
        assert_eq!(zlinecmp("foo", ""), -1);
        // Both empty → 0.
        assert_eq!(zlinecmp("", ""), 0);
    }

    #[test]
    fn zlinefind_forward_exact() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:208-213 — forward search; sens=0 means need zlinecmp < 0,
        // i.e. the needle must be a strict prefix at the position.
        assert_eq!(zlinefind("hello world hello", 0, "world", 1, 0), Some(6));
    }

    #[test]
    fn zlinefind_backward_exact() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:215-222 — backward search from end. sens=1 accepts both
        // 0 (exact) and -1 (prefix); sens=0 only accepts -1 (prefix).
        // To find the second "hello" exactly at index 12 we need
        // sens=1 — at index 12 zlinecmp("hello","hello")=0.
        assert_eq!(
            zlinefind("hello world hello", 16, "hello", -1, 1),
            Some(12)
        );
    }

    #[test]
    fn zlinefind_not_found() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:224 — exhausted without match → None.
        assert_eq!(zlinefind("hello", 0, "xyz", 1, 0), None);
    }

    #[test]
    fn zlinefind_starts_at_pos() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // c:206 — search begins at `pos`, not at 0.
        // "abcabc" with needle "a" starting at pos=1 finds the
        // second "a" at index 3.
        assert_eq!(zlinefind("abcabc", 1, "a", 1, 0), Some(3));
    }
}

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

    #[test]
    fn bad_text_strings_are_seven_chars() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(FAILING_TEXT.len(), BAD_TEXT_LEN);
        assert_eq!(INVALID_TEXT.len(), BAD_TEXT_LEN);
    }

    #[test]
    fn norm_prompt_pos_after_bad_text_marker() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Column 8: skips "XXXXXXX " (BAD_TEXT_LEN + 1 trailing space).
        assert_eq!(NORM_PROMPT_POS, 8);
    }

    #[test]
    fn first_search_char_after_isearch_label() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Column 22: NORM_PROMPT_POS (8) + 14 chars of "XXX-i-search: ".
        assert_eq!(FIRST_SEARCH_CHAR, 22);
    }

    #[test]
    fn isearch_prompt_skeleton_has_correct_shape() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert!(ISEARCH_PROMPT.starts_with("XXXXXXX "));
        assert!(ISEARCH_PROMPT.contains("XXX-i-search:"));
    }
}