dirge-agent 0.7.3

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
use compact_str::CompactString;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::ui::picker::FilePicker;
#[cfg(feature = "slash-completion")]
use crate::ui::slash::CompletionResult;
#[cfg(feature = "slash-completion")]
use crate::ui::slash::try_complete;

const KILL_RING_MAX: usize = 10;

// `cursor` is a byte-offset into `buffer` (UTF-8). The helpers below move the
// cursor by one character boundary so we never land in the middle of a
// multibyte sequence — that would panic on the next insert/remove in
// `CompactString`/`String`.
enum KillDir {
    Prepend,
    Append,
}

#[derive(Default)]
struct YankState {
    index: usize,
    cursor: usize,
    len: usize,
}

fn prev_char_boundary(s: &str, idx: usize) -> usize {
    let mut i = idx.saturating_sub(1);
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

fn next_char_boundary(s: &str, idx: usize) -> usize {
    let len = s.len();
    let mut i = (idx + 1).min(len);
    while i < len && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

fn is_word_char(ch: char) -> bool {
    ch.is_alphanumeric() || ch == '_'
}

fn is_whitespace(ch: char) -> bool {
    ch.is_whitespace()
}

fn prev_word_boundary(s: &str, cursor: usize) -> usize {
    if cursor == 0 {
        return 0;
    }
    let mut idx = prev_char_boundary(s, cursor);
    // skip trailing whitespace
    while idx > 0 {
        let ch = s[..idx].chars().next_back().unwrap_or(' ');
        if !is_whitespace(ch) {
            break;
        }
        idx = prev_char_boundary(s, idx);
    }
    // determine character class at position
    if idx == 0 {
        return 0;
    }
    let ch = s[..idx].chars().next_back().unwrap_or(' ');
    let is_word = is_word_char(ch);
    // skip backward through same class
    while idx > 0 {
        let ch = s[..idx].chars().next_back().unwrap_or(' ');
        let current_is_word = is_word_char(ch);
        if current_is_word != is_word || is_whitespace(ch) {
            break;
        }
        let prev = prev_char_boundary(s, idx);
        if prev == idx {
            break;
        }
        idx = prev;
    }
    idx
}

fn next_word_boundary(s: &str, cursor: usize) -> usize {
    let len = s.len();
    if cursor >= len {
        return len;
    }
    let ch = s[cursor..].chars().next().unwrap_or(' ');
    let is_word = is_word_char(ch);
    let is_ws = is_whitespace(ch);
    let mut idx = cursor;
    // skip current class (word, punct, or whitespace)
    while idx < len {
        let ch = s[idx..].chars().next().unwrap_or(' ');
        let current_is_word = is_word_char(ch);
        let current_is_ws = is_whitespace(ch);
        if is_ws {
            if !current_is_ws {
                break;
            }
        } else if current_is_word != is_word {
            break;
        }
        idx = next_char_boundary(s, idx);
    }
    // skip whitespace and punctuation between words
    while idx < len {
        let ch = s[idx..].chars().next().unwrap_or(' ');
        if is_word_char(ch) {
            break;
        }
        idx = next_char_boundary(s, idx);
    }
    idx
}

fn cursor_line_start(s: &str, cursor: usize) -> usize {
    if cursor == 0 {
        return 0;
    }
    let haystack = &s[..cursor];
    match haystack.rfind('\n') {
        Some(pos) => pos + 1,
        None => 0,
    }
}

fn prev_line_start(s: &str, cursor: usize) -> Option<usize> {
    let line_start = cursor_line_start(s, cursor);
    if line_start == 0 {
        return None;
    }
    Some(cursor_line_start(s, line_start.saturating_sub(1)))
}

fn next_line_start(s: &str, cursor: usize) -> Option<usize> {
    let after = &s[cursor..];
    after.find('\n').map(|p| cursor + p + 1)
}

/// Byte offset to move the cursor to for a vertical (Up/Down) keystroke
/// across SOFT-wrapped display rows (dirge-5w9v). Reuses the renderer's
/// `wrap_editor` (the single soft-wrap source — no duplicated logic) to
/// find the cursor's display `(row, col)`, then locates the byte on the
/// adjacent row nearest that column. Returns `None` at the top/bottom
/// display row (caller then falls through to history). Every returned
/// offset is a real char boundary (the scan steps by `next_char_boundary`),
/// so a subsequent slice can't panic. O(rows·len) but only on a keypress
/// over a small compose buffer.
///
/// Only valid when the display buffer equals the raw buffer (no paste
/// placeholders); callers guard on that.
fn wrap_vertical_target(s: &str, cursor: usize, wrap_w: usize, up: bool) -> Option<usize> {
    use crate::ui::renderer::wrap_editor;
    let (rows, cur_row, cur_col) = wrap_editor(s, cursor, wrap_w);
    let target_row: u16 = if up {
        cur_row.checked_sub(1)?
    } else {
        let next = cur_row + 1;
        if next as usize >= rows.len() {
            return None;
        }
        next
    };
    // Scan char boundaries; on the target row, return the first offset
    // whose display column reaches `cur_col`, else the row's last offset.
    let mut best: Option<usize> = None;
    let mut b = 0usize;
    loop {
        let (_, r, c) = wrap_editor(s, b, wrap_w);
        if r == target_row {
            if c >= cur_col {
                return Some(b);
            }
            best = Some(b);
        } else if r > target_row {
            break;
        }
        if b >= s.len() {
            break;
        }
        b = next_char_boundary(s, b);
    }
    best
}

/// Map a CHAR column on the line `[start..end]` of `s` to its
/// byte offset within `s`. Clamps to `end` when the column exceeds
/// the line's char count. Used by history Up/Down (H-batch1-2) so
/// vertical motion across multi-byte chars never lands a cursor
/// mid-codepoint — slicing the buffer there would panic.
fn byte_at_char_col(s: &str, start: usize, end: usize, char_col: usize) -> usize {
    let line = &s[start..end];
    match line.char_indices().nth(char_col) {
        Some((i, _)) => start + i,
        None => end, // column past EOL — clamp
    }
}

/// Threshold for collapsing pastes: anything with >= this many newlines becomes a
/// `[N lines pasted]` placeholder. Single-line and short pastes go in raw so a
/// quick paste-of-a-command isn't surprising.
const PASTE_COLLAPSE_LINES: usize = 4;

/// Sentinel character bracketing a paste placeholder in the buffer. The buffer
/// stores `\x01<index>\x01`, where `<index>` is the decimal index into
/// `pastes`. Because `\x01` is filtered out of bracketed-paste content (see
/// `handle_paste`) and ignored as a typeable key, it can't appear in normal
/// input — so its presence reliably marks a placeholder block.
const PASTE_MARK: char = '\x01';

pub struct InputEditor {
    pub buffer: CompactString,
    pub cursor: usize,
    history: Vec<CompactString>,
    history_pos: Option<usize>,
    /// In-progress text stashed when the user starts navigating history.
    /// Restored when they navigate past the newest entry (Down at the
    /// most-recent history slot) so the draft isn't lost. `None` when
    /// the live buffer IS the draft (not navigating history).
    history_draft: Option<(CompactString, usize)>,
    pub picker: Option<FilePicker>,
    kill_ring: Vec<CompactString>,
    last_action_was_kill: bool,
    yank_state: Option<YankState>,
    /// Pasted text bodies indexed by the digits appearing between `\x01` marks
    /// in the buffer. `None` entries are tombstones for expanded pastes (so
    /// existing indices remain valid).
    pastes: Vec<Option<CompactString>>,
    /// Current slash-command completion state, for rendering a preview.
    #[cfg(feature = "slash-completion")]
    pub completion: Option<CompletionResult>,
    /// Display width the buffer is soft-wrapped to in the box, pushed in
    /// from the renderer before each key dispatch. `0` = unknown (e.g.
    /// before the first render) → Up/Down fall back to hard-newline
    /// motion. Used to make vertical motion wrap-aware (dirge-5w9v).
    wrap_w: usize,
    /// Whether Ctrl+R reverse-i-search mode is active.
    search_mode: bool,
    /// Accumulated search query during reverse-i-search.
    search_query: CompactString,
    /// Index into `history` of the currently displayed match.
    search_match_idx: Option<usize>,
    /// Buffer + cursor stashed when entering search mode. Restored on cancel.
    search_draft: Option<(CompactString, usize)>,
}

/// Find the marker block `\x01<digits>\x01` containing or starting at
/// `cursor`. Returns `(start_of_opening_mark, byte_after_closing_mark, index)`.
fn marker_containing(s: &str, cursor: usize) -> Option<(usize, usize, usize)> {
    let bytes = s.as_bytes();
    // Walk back from cursor to find an opening PASTE_MARK.
    let mut i = cursor.min(bytes.len());
    while i > 0 && bytes[i - 1] != PASTE_MARK as u8 {
        i -= 1;
    }
    if i == 0 {
        return None;
    }
    // i is just after a PASTE_MARK; the opening mark is at i-1.
    let open = i - 1;
    let rest = &bytes[i..];
    let close_rel = rest.iter().position(|&b| b == PASTE_MARK as u8)?;
    let close = i + close_rel;
    if cursor > close {
        return None;
    }
    let digits = std::str::from_utf8(&bytes[i..close]).ok()?;
    let idx = digits.parse::<usize>().ok()?;
    Some((open, close + 1, idx))
}

/// If `pos` falls strictly inside a marker block `(start, end)`, return
/// `start` (so cursor motion moves *before* the block). Otherwise return
/// `pos` unchanged.
fn skip_left_over_marker(s: &str, pos: usize) -> usize {
    for (start, end, _) in marker_blocks(s) {
        if pos > start && pos < end {
            return start;
        }
    }
    pos
}

/// If `pos` falls strictly inside a marker block `(start, end)`, return
/// `end` (so cursor motion moves *after* the block). Otherwise return
/// `pos` unchanged.
fn skip_right_over_marker(s: &str, pos: usize) -> usize {
    for (start, end, _) in marker_blocks(s) {
        if pos > start && pos < end {
            return end;
        }
    }
    pos
}

/// Move one cursor step left, treating any marker block as a single unit.
fn prev_pos(s: &str, cursor: usize) -> usize {
    skip_left_over_marker(s, prev_char_boundary(s, cursor))
}

/// Move one cursor step right, treating any marker block as a single unit.
fn next_pos(s: &str, cursor: usize) -> usize {
    skip_right_over_marker(s, next_char_boundary(s, cursor))
}

/// Word-skip left, but never land mid-marker. `prev_word_boundary` is
/// marker-blind (it sees `\x01` as punctuation and would happily split the
/// marker open), so we post-process with `skip_left_over_marker` to round any
/// in-marker landing back to the marker's left edge.
fn prev_word_pos(s: &str, cursor: usize) -> usize {
    skip_left_over_marker(s, prev_word_boundary(s, cursor))
}

/// Word-skip right, with the symmetric marker-safety post-process.
fn next_word_pos(s: &str, cursor: usize) -> usize {
    skip_right_over_marker(s, next_word_boundary(s, cursor))
}

/// What range a backspace at `cursor` should remove. If the character to the
/// left is the closing mark of a placeholder, return the whole block;
/// otherwise return a single char.
fn backspace_range(s: &str, cursor: usize) -> Option<(usize, usize)> {
    if cursor == 0 {
        return None;
    }
    if let Some((start, end, _)) = marker_containing(s, cursor.saturating_sub(1))
        && cursor == end
    {
        return Some((start, end));
    }
    Some((prev_char_boundary(s, cursor), cursor))
}

/// What range a delete at `cursor` should remove. If the cursor sits at the
/// opening of a placeholder, return the whole block; otherwise a single char.
fn delete_range(s: &str, cursor: usize) -> Option<(usize, usize)> {
    if cursor >= s.len() {
        return None;
    }
    if let Some((start, end, _)) = marker_containing(s, cursor + 1)
        && cursor == start
    {
        return Some((start, end));
    }
    Some((cursor, next_char_boundary(s, cursor)))
}

/// Scan `s` and return each marker block as `(start, end, index)` in order.
fn marker_blocks(s: &str) -> Vec<(usize, usize, usize)> {
    let bytes = s.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == PASTE_MARK as u8 {
            let start = i;
            let body_start = i + 1;
            if let Some(rel) = bytes[body_start..]
                .iter()
                .position(|&b| b == PASTE_MARK as u8)
            {
                let close = body_start + rel;
                if let Ok(digits) = std::str::from_utf8(&bytes[body_start..close])
                    && let Ok(idx) = digits.parse::<usize>()
                {
                    out.push((start, close + 1, idx));
                    i = close + 1;
                    continue;
                }
            }
        }
        i += 1;
    }
    out
}

/// Compute the placeholder display string for a paste body.
fn placeholder_display(text: &str) -> String {
    let lines = text.matches('\n').count() + 1;
    format!("[{} lines pasted]", lines)
}

impl InputEditor {
    pub fn new() -> Self {
        InputEditor {
            buffer: CompactString::new(""),
            cursor: 0,
            history: Vec::new(),
            history_pos: None,
            history_draft: None,
            picker: None,
            kill_ring: Vec::new(),
            last_action_was_kill: false,
            yank_state: None,
            pastes: Vec::new(),
            #[cfg(feature = "slash-completion")]
            completion: None,
            wrap_w: 0,
            search_mode: false,
            search_query: CompactString::new(""),
            search_match_idx: None,
            search_draft: None,
        }
    }

    /// Push the current display wrap width (from the renderer) so Up/Down
    /// can move by SOFT-wrapped display rows, not just hard newlines.
    pub fn set_wrap_width(&mut self, wrap_w: usize) {
        self.wrap_w = wrap_w;
    }

    /// Insert pasted text. If it spans `PASTE_COLLAPSE_LINES` or more lines,
    /// store it and insert a `[N lines pasted]` placeholder; otherwise insert
    /// raw. If the same content was already pasted and is still represented
    /// by a placeholder, expand that placeholder inline instead (so a second
    /// paste of the same content reveals the body).
    /// Replace the entire buffer with `text` and move the cursor to
    /// the end. Used by `/fork` to restore the original user prompt
    /// into the editor for re-editing.
    pub fn set_text(&mut self, text: &str) {
        self.buffer = CompactString::new(text);
        self.cursor = self.buffer.len();
        self.pastes.clear();
        // Reset kill ring state so a subsequent yank doesn't paste
        // text from before the set_text (which would be jarring —
        // the editor was just rewritten by /fork). History position
        // also resets so Up/Down navigation starts from the new
        // baseline instead of mid-history. Drop the history draft
        // too — the user just got a /fork-restored prompt; that IS
        // the new draft.
        self.kill_ring.clear();
        self.yank_state = None;
        self.history_pos = None;
        self.history_draft = None;
    }

    pub fn handle_paste(&mut self, text: &str) {
        // The file picker (`@query`) maintains its own filter state. A paste
        // landing here would write marker bytes into the buffer that the
        // picker doesn't know about, leaving a stale/corrupt query. Easiest
        // to just ignore pastes while the picker is active — the user can
        // close the picker (Esc) and re-paste.
        if self.picker.as_ref().is_some_and(|p| p.active) {
            return;
        }
        // Normalize line endings to `\n`. macOS-era clipboards and some
        // terminal paste streams deliver `\r` or `\r\n`. Without this the
        // line count comes out as 1, the collapse threshold isn't reached,
        // and the raw text gets inserted — with embedded `\r` chars that
        // the terminal then renders as carriage-returns, garbling the line.
        let normalized: String = text.replace("\r\n", "\n").replace('\r', "\n");
        // Strip PASTE_MARK so it can never appear in paste content and confuse
        // the marker parser.
        let cleaned: String = normalized.chars().filter(|&c| c != PASTE_MARK).collect();
        if cleaned.is_empty() {
            return;
        }
        // UI-6: reject pastes over ~1MB. Multi-MB pastes accumulate in
        // the buffer, allocate for line wrapping, and bloat re-renders.
        // The terminal is for text, not binary blobs — truncate with a
        // visible warning so the user knows.
        const MAX_PASTE_BYTES: usize = 1_048_576; // 1 MB
        if cleaned.len() > MAX_PASTE_BYTES {
            let truncated: String = cleaned.chars().take(MAX_PASTE_BYTES).collect();
            self.insert_str(&truncated);
            // Append a truncation notice so it's clear the paste was cut.
            self.insert_str(&format!(
                "\n\n[paste truncated: {} chars → 1 MB limit]",
                cleaned.len()
            ));
            return;
        }
        let line_count = cleaned.matches('\n').count() + 1;
        if line_count < PASTE_COLLAPSE_LINES {
            self.insert_str(&cleaned);
            return;
        }
        // Auto-expand on repeat: if this body matches an existing placeholder
        // in the buffer, expand it inline rather than inserting another
        // placeholder.
        if let Some((start, end, idx)) =
            marker_blocks(&self.buffer).into_iter().find(|(_, _, idx)| {
                self.pastes
                    .get(*idx)
                    .and_then(|opt| opt.as_ref())
                    .map(|s| s.as_str() == cleaned.as_str())
                    .unwrap_or(false)
            })
        {
            let body = self.pastes[idx].take().unwrap();
            self.buffer.replace_range(start..end, body.as_str());
            // Place cursor at end of expanded text.
            self.cursor = start + body.len();
            self.history_pos = None;
            self.reset_kill_accumulation();
            return;
        }
        let idx = self.pastes.len();
        self.pastes.push(Some(CompactString::from(cleaned)));
        let marker = format!("{}{}{}", PASTE_MARK, idx, PASTE_MARK);
        self.insert_str(&marker);
    }

    fn insert_str(&mut self, s: &str) {
        self.buffer.insert_str(self.cursor, s);
        self.cursor += s.len();
        self.history_pos = None;
        self.reset_kill_accumulation();
    }

    /// Remove a byte range from the buffer and place the cursor at `start`.
    /// If the range fully contains a placeholder marker block, the
    /// corresponding `pastes` slot is tombstoned so its body can be GC'd
    /// (idempotent — repeat removes are fine).
    fn remove_range(&mut self, start: usize, end: usize) {
        // Detect any marker block fully contained in the removed range and
        // free its stored body.
        for (mstart, mend, idx) in marker_blocks(&self.buffer) {
            if mstart >= start
                && mend <= end
                && let Some(slot) = self.pastes.get_mut(idx)
            {
                *slot = None;
            }
        }
        self.buffer.replace_range(start..end, "");
        self.cursor = start;
    }

    /// Return the buffer with all placeholder markers expanded to their
    /// original paste bodies. Used at submit time so the agent receives the
    /// real text.
    pub fn expanded(&self) -> CompactString {
        Self::expand_with_pastes(&self.buffer, &self.pastes).into()
    }

    /// Render the buffer for the input box display: each
    /// `\x01<idx>\x01` marker block is replaced with the
    /// `[N lines pasted]` placeholder so the user sees a compact
    /// representation rather than a bare digit between invisible
    /// SOH bytes. Returns `(display_text, cursor_byte_in_display)`
    /// so the renderer can place the cursor correctly.
    ///
    /// Cursor mapping: marker blocks are atomic for cursor motion
    /// (see `prev_pos` / `next_pos`), so the cursor only ever sits
    /// at the open boundary, the close boundary, or outside any
    /// marker. For each marker block whose close is at or before
    /// the cursor, shift the displayed cursor by
    /// `placeholder.len() - marker_len`.
    pub fn display(&self) -> (String, usize) {
        let buf = self.buffer.as_str();
        let blocks = marker_blocks(buf);
        if blocks.is_empty() {
            return (buf.to_string(), self.cursor.min(buf.len()));
        }
        let cursor = self.cursor.min(buf.len());
        let mut out = String::with_capacity(buf.len());
        let mut cursor_display = cursor;
        let mut last_end = 0usize;
        for (start, end, idx) in &blocks {
            out.push_str(&buf[last_end..*start]);
            let placeholder = self
                .pastes
                .get(*idx)
                .and_then(|o| o.as_ref())
                .map(|s| placeholder_display(s.as_str()))
                .unwrap_or_default();
            let marker_len = end - start;
            if cursor >= *end {
                // Cursor is past the marker — shift by delta.
                cursor_display = cursor_display
                    .saturating_sub(marker_len)
                    .saturating_add(placeholder.len());
            } else if cursor > *start {
                // Defensive: cursor inside the marker (shouldn't
                // happen via normal motion). Clamp to end of
                // placeholder in the display.
                cursor_display = out.len() + placeholder.len();
            }
            out.push_str(&placeholder);
            last_end = *end;
        }
        out.push_str(&buf[last_end..]);
        (out, cursor_display)
    }

    /// Expand markers in `s` using `pastes` for bodies. Free-function form
    /// so it can also be used to flatten markers in kill-ring entries
    /// before we clear `pastes`.
    fn expand_with_pastes(s: &str, pastes: &[Option<CompactString>]) -> String {
        let blocks = marker_blocks(s);
        if blocks.is_empty() {
            return s.to_string();
        }
        let mut out = String::with_capacity(s.len());
        let mut cur = 0;
        for (start, end, idx) in blocks {
            out.push_str(&s[cur..start]);
            if let Some(Some(body)) = pastes.get(idx) {
                out.push_str(body);
            }
            cur = end;
        }
        out.push_str(&s[cur..]);
        out
    }

    /// Return (display_text, display_cursor_col) for a logical line of the
    /// buffer with placeholders rendered as `[N lines pasted]`. Used by the
    /// renderer so the input bar shows a compact representation.
    #[allow(dead_code)]
    pub fn render_line(&self, line: &str, cursor_in_line: usize) -> (String, usize) {
        let blocks = marker_blocks(line);
        if blocks.is_empty() {
            return (line.to_string(), cursor_in_line);
        }
        let mut out = String::with_capacity(line.len());
        let mut display_cursor = cursor_in_line;
        let mut cur = 0;
        for (start, end, idx) in blocks {
            // Carry plain text before the block.
            if cur < start {
                out.push_str(&line[cur..start]);
            }
            let placeholder = self
                .pastes
                .get(idx)
                .and_then(|o| o.as_ref())
                .map(|s| placeholder_display(s))
                .unwrap_or_else(|| "[expanded]".to_string());
            // Adjust the displayed cursor position if it lies after this block.
            if cursor_in_line >= end {
                let block_len = end - start;
                display_cursor = display_cursor - block_len + placeholder.len();
            } else if cursor_in_line > start && cursor_in_line < end {
                // Cursor logically inside a marker — pin it to the placeholder
                // boundary so it never appears mid-marker.
                display_cursor = out.len() + placeholder.len();
            }
            out.push_str(&placeholder);
            cur = end;
        }
        if cur < line.len() {
            out.push_str(&line[cur..]);
        }
        (out, display_cursor)
    }

    pub fn start_picker(&mut self) {
        let picker = self.picker.get_or_insert_with(FilePicker::new);
        picker.activate();
    }

    fn reset_kill_accumulation(&mut self) {
        self.last_action_was_kill = false;
        self.yank_state = None;
        #[cfg(feature = "slash-completion")]
        {
            self.completion = None;
        }
    }

    fn push_kill(&mut self, text: CompactString, direction: KillDir) {
        if text.is_empty() {
            return;
        }
        if self.last_action_was_kill && !self.kill_ring.is_empty() {
            let entry = &mut self.kill_ring[0];
            match direction {
                KillDir::Prepend => {
                    let mut new = text;
                    new.push_str(entry);
                    *entry = new;
                }
                KillDir::Append => {
                    entry.push_str(&text);
                }
            }
        } else {
            self.kill_ring.insert(0, text);
            if self.kill_ring.len() > KILL_RING_MAX {
                self.kill_ring.pop();
            }
        }
        self.last_action_was_kill = true;
    }

    pub fn handle_picker_key(&mut self, key: KeyEvent) -> bool {
        let picker = match self.picker.as_mut() {
            Some(p) if p.active => p,
            _ => return false,
        };

        match key.code {
            KeyCode::Char(c)
                if c == '\x08' || (c == 'h' && key.modifiers.contains(KeyModifiers::CONTROL)) =>
            {
                if picker.cursor > 0 {
                    picker.backspace();
                    self.cursor = prev_char_boundary(&self.buffer, self.cursor);
                    self.buffer.remove(self.cursor);
                } else {
                    // `rfind` returns a *byte* offset and `self.cursor`
                    // is a byte offset (see line below where we add
                    // `c.len_utf8()`). The previous version mixed byte
                    // offsets with `chars().take(N)` which counts chars
                    // — corrupted any buffer containing multi-byte
                    // text before the `@`. Use byte-level slicing
                    // throughout.
                    if let Some(at) = self.buffer.rfind('@') {
                        let before = &self.buffer[..at];
                        let after = self.buffer.get(at + 1..).unwrap_or("");
                        let new_buf = format!("{}{}", before, after);
                        self.cursor = at;
                        self.buffer = new_buf.into();
                    }
                    picker.deactivate();
                }
                true
            }
            KeyCode::Char(c) => {
                picker.char_input(c);
                self.buffer.insert(self.cursor, c);
                self.cursor += c.len_utf8();
                true
            }
            KeyCode::Backspace => {
                if picker.cursor > 0 {
                    picker.backspace();
                    self.cursor = prev_char_boundary(&self.buffer, self.cursor);
                    self.buffer.remove(self.cursor);
                    true
                } else {
                    // Same byte-vs-char fix as the Esc branch above.
                    if let Some(at) = self.buffer.rfind('@') {
                        let before = &self.buffer[..at];
                        let after = self.buffer.get(at + 1..).unwrap_or("");
                        let new_buf = format!("{}{}", before, after);
                        self.cursor = at;
                        self.buffer = new_buf.into();
                    }
                    picker.deactivate();
                    true
                }
            }
            KeyCode::Tab => {
                if key
                    .modifiers
                    .contains(crossterm::event::KeyModifiers::SHIFT)
                {
                    picker.select_prev();
                } else {
                    picker.select_next();
                }
                true
            }
            KeyCode::Up => {
                picker.select_prev();
                true
            }
            KeyCode::Down => {
                picker.select_next();
                true
            }
            KeyCode::Enter => {
                if let Some(path) = picker.selected_path() {
                    let path_str = path.to_string_lossy().to_string();
                    // Byte-level slicing — `rfind`, `picker.query.len()`,
                    // and `self.cursor` are all byte offsets. Previous
                    // version mixed byte indices with `chars()` iters
                    // and corrupted the buffer on multi-byte input.
                    if let Some(at) = self.buffer.rfind('@') {
                        let before = &self.buffer[..at];
                        let after_byte = at + 1 + picker.query.len();
                        let after = self.buffer.get(after_byte..).unwrap_or("");
                        let new_cursor = before.len() + path_str.len();
                        let new_buf = format!("{}{}{}", before, path_str, after);
                        self.cursor = new_cursor;
                        self.buffer = new_buf.into();
                    }
                }
                picker.deactivate();
                true
            }
            KeyCode::Esc => {
                // Use BYTE-level slicing here, matching the Enter
                // path above. `rfind('@')` returns a byte offset;
                // the previous implementation used `chars().take(at)`
                // and `chars().skip(at + ...)` which mixed byte
                // offsets with char counts and corrupted the buffer
                // for any input containing multi-byte UTF-8 chars
                // before the `@` (accented letters, emoji, CJK, …).
                if let Some(at) = self.buffer.rfind('@') {
                    let before = &self.buffer[..at];
                    let after_byte = at + 1 + picker.query.len();
                    let after = self.buffer.get(after_byte..).unwrap_or("");
                    let new_buf = format!("{}{}", before, after);
                    self.cursor = at;
                    self.buffer = new_buf.into();
                }
                picker.deactivate();
                true
            }
            _ => false,
        }
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> Option<CompactString> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);

        // Ctrl+J is a portable newline trigger — many terminals never send
        // Shift+Enter as a distinct keystroke, but Ctrl+J always arrives.
        // Handled here before the Enter arm so it works even when the
        // terminal collapses Ctrl+J onto KeyCode::Enter. NOT in reverse-i-search
        // — there `self.buffer` holds the displayed match, so inserting a raw
        // `\n` would corrupt it and desync the search; let search-mode handle it.
        if ctrl && matches!(key.code, KeyCode::Char('j')) && !self.search_mode {
            if !self.picker.as_ref().is_some_and(|p| p.active) {
                self.buffer.insert(self.cursor, '\n');
                self.cursor += 1;
                self.history_pos = None;
                self.reset_kill_accumulation();
            }
            return None;
        }

        // ── search-mode dispatch ───────────────────────────
        if self.search_mode {
            return self.handle_search_key(key);
        }

        match key.code {
            KeyCode::Enter => {
                if self.picker.as_ref().is_some_and(|p| p.active) {
                    return None;
                }
                // Meta+Enter or Shift+Enter inserts newline
                if has_shift || alt {
                    self.buffer.insert(self.cursor, '\n');
                    self.cursor += 1;
                    self.history_pos = None;
                    return None;
                }
                // Plain Enter → submit. Expand any paste placeholders so the
                // agent receives the original text. Store the expanded form in
                // history too — history navigation can't rely on paste-index
                // continuity across turns.
                let submitted = self.expanded();
                if !submitted.is_empty() {
                    // Dedup against the most recent entry (bash/Emacs
                    // convention — pressing Enter on the same prompt
                    // twice shouldn't fill history with duplicates).
                    // Also cap history at 500 entries so a long-lived
                    // session doesn't grow it unboundedly.
                    const HISTORY_MAX: usize = 500;
                    let is_dupe = self
                        .history
                        .last()
                        .map(|prev| prev.as_str() == submitted.as_str())
                        .unwrap_or(false);
                    if !is_dupe {
                        self.history.push(submitted.clone());
                        if self.history.len() > HISTORY_MAX {
                            // Drop the oldest entries in batches so we
                            // aren't doing a shift on every submit
                            // once we hit the cap.
                            let drain_to = self.history.len() - HISTORY_MAX;
                            self.history.drain(..drain_to);
                        }
                    }
                }
                self.history_pos = None;
                self.history_draft = None;
                self.buffer.clear();
                self.cursor = 0;
                // Flatten markers in kill-ring entries to their raw bodies
                // before dropping pastes — otherwise a later Ctrl+Y would
                // yank back marker bytes referencing indices we just
                // cleared, and `expanded()` would silently omit them.
                for entry in self.kill_ring.iter_mut() {
                    if entry.contains(PASTE_MARK) {
                        let expanded = Self::expand_with_pastes(entry, &self.pastes);
                        *entry = expanded.into();
                    }
                }
                self.pastes.clear();
                self.reset_kill_accumulation();
                if submitted.is_empty() {
                    None
                } else {
                    Some(submitted)
                }
            }

            // Ctrl+A → start of line
            KeyCode::Char('a') if ctrl => {
                self.cursor = 0;
                self.reset_kill_accumulation();
                None
            }

            // Ctrl+E → end of line
            KeyCode::Char('e') if ctrl => {
                self.cursor = self.buffer.len();
                self.reset_kill_accumulation();
                None
            }

            // Ctrl+B → left one char
            KeyCode::Char('b') if ctrl => {
                if self.cursor > 0 {
                    self.cursor = prev_pos(&self.buffer, self.cursor);
                }
                self.reset_kill_accumulation();
                None
            }

            // Ctrl+F → reverse-i-search
            KeyCode::Char('f') if ctrl => {
                self.enter_search();
                None
            }

            // Ctrl+K → kill to end of line
            KeyCode::Char('k') if ctrl => {
                if self.cursor < self.buffer.len() {
                    let killed: CompactString = self.buffer[self.cursor..].into();
                    self.buffer.truncate(self.cursor);
                    self.push_kill(killed, KillDir::Append);
                }
                None
            }

            // Ctrl+U → kill to start of line
            KeyCode::Char('u') if ctrl => {
                if self.cursor > 0 {
                    let killed: CompactString = self.buffer[..self.cursor].into();
                    self.buffer = self.buffer[self.cursor..].into();
                    self.cursor = 0;
                    self.push_kill(killed, KillDir::Prepend);
                }
                None
            }

            // Ctrl+W → kill word before
            KeyCode::Char('w') if ctrl => {
                if self.cursor > 0 {
                    let start = prev_word_pos(&self.buffer, self.cursor);
                    let killed: CompactString = self.buffer[start..self.cursor].into();
                    self.buffer.replace_range(start..self.cursor, "");
                    self.cursor = start;
                    self.push_kill(killed, KillDir::Prepend);
                }
                None
            }

            // Ctrl+H or Backspace (plain)
            KeyCode::Char('h') if ctrl => {
                if let Some((start, end)) = backspace_range(&self.buffer, self.cursor) {
                    self.remove_range(start, end);
                }
                self.reset_kill_accumulation();
                None
            }

            // Ctrl+Y → yank
            KeyCode::Char('y') if ctrl => {
                if let Some(text) = self.kill_ring.first() {
                    let text = text.clone();
                    let len = text.len();
                    self.buffer.insert_str(self.cursor, &text);
                    self.yank_state = Some(YankState {
                        index: 0,
                        cursor: self.cursor,
                        len,
                    });
                    self.cursor += len;
                }
                self.last_action_was_kill = false;
                None
            }

            // Ctrl+N → history down
            KeyCode::Char('n') if ctrl => {
                self.history_down();
                self.reset_kill_accumulation();
                None
            }

            // Ctrl+P → history up
            KeyCode::Char('p') if ctrl => {
                self.history_up();
                self.reset_kill_accumulation();
                None
            }

            // Meta+Y → yank-pop (cycle kill ring)
            KeyCode::Char('y') if alt => {
                if let Some(ref state) = self.yank_state {
                    let range_end = state.cursor + state.len;
                    if self.kill_ring.len() > 1 && range_end <= self.buffer.len() {
                        let next = (state.index + 1) % self.kill_ring.len();
                        if let Some(text) = self.kill_ring.get(next) {
                            let text = text.clone();
                            self.buffer.replace_range(state.cursor..range_end, "");
                            self.buffer.insert_str(state.cursor, &text);
                            self.cursor = state.cursor + text.len();
                            self.yank_state = Some(YankState {
                                index: next,
                                cursor: state.cursor,
                                len: text.len(),
                            });
                        }
                    }
                }
                None
            }

            // Meta+D → delete word after
            KeyCode::Char('d') if alt => {
                if self.cursor < self.buffer.len() {
                    let end = next_word_pos(&self.buffer, self.cursor);
                    self.buffer.replace_range(self.cursor..end, "");
                }
                self.reset_kill_accumulation();
                None
            }

            // Meta+B → prev word (Emacs style)
            KeyCode::Char('b') if alt => {
                if self.cursor > 0 {
                    self.cursor = prev_word_pos(&self.buffer, self.cursor);
                }
                self.reset_kill_accumulation();
                None
            }

            // Meta+F → next word (Emacs style)
            KeyCode::Char('f') if alt => {
                if self.cursor < self.buffer.len() {
                    self.cursor = next_word_pos(&self.buffer, self.cursor);
                } else {
                    self.cursor = self.buffer.len();
                }
                self.reset_kill_accumulation();
                None
            }

            // Meta+Left → prev word
            KeyCode::Left if alt => {
                if self.cursor > 0 {
                    self.cursor = prev_word_pos(&self.buffer, self.cursor);
                }
                self.reset_kill_accumulation();
                None
            }

            // Meta+Right → next word
            KeyCode::Right if alt => {
                if self.cursor < self.buffer.len() {
                    self.cursor = next_word_pos(&self.buffer, self.cursor);
                } else {
                    self.cursor = self.buffer.len();
                }
                self.reset_kill_accumulation();
                None
            }

            // Meta+Backspace → delete word before
            KeyCode::Backspace if alt => {
                if self.cursor > 0 {
                    let start = prev_word_pos(&self.buffer, self.cursor);
                    self.buffer.replace_range(start..self.cursor, "");
                    self.cursor = start;
                }
                self.reset_kill_accumulation();
                None
            }

            // Plain char: only if not ctrl/alt-modified
            KeyCode::Char(c) if !ctrl && !alt => {
                if c == '@' {
                    let at_word_start = self.cursor == 0
                        || self.buffer.as_bytes().get(self.cursor - 1) == Some(&b' ');
                    if at_word_start {
                        self.start_picker();
                    }
                }
                self.buffer.insert(self.cursor, c);
                self.cursor += c.len_utf8();
                self.history_pos = None;
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Backspace => {
                if let Some((start, end)) = backspace_range(&self.buffer, self.cursor) {
                    self.remove_range(start, end);
                }
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Delete => {
                if let Some((start, end)) = delete_range(&self.buffer, self.cursor) {
                    self.remove_range(start, end);
                }
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Left => {
                if self.cursor > 0 {
                    self.cursor = prev_pos(&self.buffer, self.cursor);
                }
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Right => {
                // At end-of-line with a slash-command ghost completion
                // showing, Right accepts it (fills in the suffix) instead
                // of just moving the cursor.
                #[cfg(feature = "slash-completion")]
                {
                    if self.cursor == self.buffer.len()
                        && let Some(suffix) = crate::ui::slash::ghost_suffix(self.buffer.as_str())
                    {
                        self.buffer.push_str(&suffix);
                        self.cursor = self.buffer.len();
                        self.reset_kill_accumulation();
                        return None;
                    }
                }
                if self.cursor < self.buffer.len() {
                    self.cursor = next_pos(&self.buffer, self.cursor);
                }
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Home => {
                self.cursor = 0;
                self.reset_kill_accumulation();
                None
            }

            KeyCode::End => {
                self.cursor = self.buffer.len();
                self.reset_kill_accumulation();
                None
            }

            KeyCode::Up => {
                self.reset_kill_accumulation();
                // If already navigating history, continue.
                if self.history_pos.is_some() {
                    self.history_up();
                    return None;
                }
                // Wrap-aware vertical motion: move by displayed (soft-
                // wrapped) rows when the width is known and the buffer
                // has no paste placeholders (display == raw). At the top
                // display row, fall through to history (dirge-5w9v).
                if self.wrap_w > 0 && marker_blocks(&self.buffer).is_empty() {
                    if let Some(pos) =
                        wrap_vertical_target(&self.buffer, self.cursor, self.wrap_w, true)
                    {
                        self.cursor = pos;
                    } else {
                        self.history_up();
                    }
                    return None;
                }
                // Fallback (markers present / width unknown): hard-newline
                // motion, then history.
                if let Some(pos) = prev_line_start(&self.buffer, self.cursor) {
                    let line_start = cursor_line_start(&self.buffer, self.cursor);
                    // H-batch1-2 (audit fix): map by CHAR column, not
                    // byte column. Adding `cursor - line_start` (a
                    // byte distance) to `pos` could land mid-codepoint
                    // when either line has multi-byte chars — the
                    // next `replace_range`/slice would panic with
                    // "byte index N is not a char boundary."
                    let char_col = self.buffer[line_start..self.cursor].chars().count();
                    let target_line_end = self.buffer[pos..]
                        .find('\n')
                        .map(|p| pos + p)
                        .unwrap_or(self.buffer.len());
                    self.cursor = byte_at_char_col(&self.buffer, pos, target_line_end, char_col);
                    return None;
                }
                // At top of buffer → fall through to history.
                self.history_up();
                None
            }

            KeyCode::Down => {
                self.reset_kill_accumulation();
                // If already navigating history, continue.
                if self.history_pos.is_some() {
                    self.history_down();
                    return None;
                }
                // Wrap-aware vertical motion (see KeyCode::Up). At the
                // bottom display row, fall through to history (dirge-5w9v).
                if self.wrap_w > 0 && marker_blocks(&self.buffer).is_empty() {
                    if let Some(pos) =
                        wrap_vertical_target(&self.buffer, self.cursor, self.wrap_w, false)
                    {
                        self.cursor = pos;
                    } else {
                        self.history_down();
                    }
                    return None;
                }
                // Fallback (markers present / width unknown): hard-newline
                // motion, then history.
                if let Some(pos) = next_line_start(&self.buffer, self.cursor) {
                    let line_start = cursor_line_start(&self.buffer, self.cursor);
                    // H-batch1-2 (audit fix) — see KeyCode::Up.
                    let char_col = self.buffer[line_start..self.cursor].chars().count();
                    let target_line_end = self.buffer[pos..]
                        .find('\n')
                        .map(|p| pos + p)
                        .unwrap_or(self.buffer.len());
                    self.cursor = byte_at_char_col(&self.buffer, pos, target_line_end, char_col);
                    return None;
                }
                // At bottom of buffer → fall through to history.
                self.history_down();
                None
            }

            KeyCode::Tab => {
                #[cfg(feature = "slash-completion")]
                {
                    // Don't grab Tab while the `@`-file-picker is
                    // active — that path has its own keystroke
                    // handling. The buffer wouldn't start with `/`
                    // in practice, but guard explicitly so future
                    // changes can't accidentally race the picker —
                    // mirrors the Enter / Ctrl+J guards above.
                    let picker_active = self.picker.as_ref().is_some_and(|p| p.active);
                    if !picker_active
                        && self.buffer.starts_with('/')
                        && let Some(cr) = try_complete(&self.buffer, self.cursor)
                    {
                        self.buffer = cr.new_buffer.clone().into();
                        self.cursor = cr.new_cursor;
                        self.reset_kill_accumulation();
                        self.completion = Some(cr);
                        return None;
                    }
                }
                self.buffer.insert_str(self.cursor, "  ");
                self.cursor += 2;
                self.reset_kill_accumulation();
                None
            }

            _ => None,
        }
    }

    fn history_up(&mut self) {
        let hist_len = self.history.len();
        if hist_len == 0 {
            return;
        }
        // Stash whatever the user was typing when they first start
        // navigating history. Restored by `history_down` when they
        // pass back beyond the most-recent entry.
        if self.history_pos.is_none() {
            self.history_draft = Some((self.buffer.clone(), self.cursor));
        }
        let pos = match self.history_pos {
            Some(p) if p > 0 => p - 1,
            Some(_) => 0,
            None => hist_len - 1,
        };
        self.history_pos = Some(pos);
        self.buffer = self.history[pos].clone();
        self.cursor = self.buffer.len();
    }

    fn history_down(&mut self) {
        match self.history_pos {
            Some(pos) if pos + 1 < self.history.len() => {
                let new_pos = pos + 1;
                self.history_pos = Some(new_pos);
                self.buffer = self.history[new_pos].clone();
                self.cursor = self.buffer.len();
            }
            Some(_) => {
                // Past the most-recent history entry → return to
                // whatever the user was typing before they started
                // browsing history (empty if there was no draft).
                self.history_pos = None;
                if let Some((draft, cursor)) = self.history_draft.take() {
                    self.buffer = draft;
                    self.cursor = cursor.min(self.buffer.len());
                } else {
                    self.buffer.clear();
                    self.cursor = 0;
                }
            }
            None => {}
        }
    }

    // ── Ctrl+F reverse-i-search ─────────────────────────────

    pub fn is_in_search(&self) -> bool {
        self.search_mode
    }

    #[allow(dead_code)]
    pub fn search_query(&self) -> &str {
        self.search_query.as_str()
    }

    #[allow(dead_code)]
    pub fn search_match_text(&self) -> &str {
        match self.search_match_idx {
            Some(idx) => self.history.get(idx).map(|s| s.as_str()).unwrap_or(""),
            None => "",
        }
    }

    pub fn search_display(&self) -> (String, usize) {
        // Route through display() so paste markers are collapsed
        // to placeholders (same as the normal editor buffer).
        let (matched, matched_cursor) = self.display();
        let prefix = format!("(reverse-i-search)`{}': ", self.search_query);
        let full = format!("{}{}", prefix, matched);
        (full, prefix.len() + matched_cursor)
    }

    fn enter_search(&mut self) {
        if self.history.is_empty() {
            return;
        }
        self.search_draft = Some((self.buffer.clone(), self.cursor));
        self.search_mode = true;
        self.search_query.clear();
        self.search_match_idx = Some(self.history.len() - 1);
        self.buffer = self.history[self.history.len() - 1].clone();
        self.cursor = self.buffer.len();
    }

    fn search_find(&self, query: &str) -> Option<usize> {
        if query.is_empty() {
            if self.history.is_empty() {
                return None;
            }
            return Some(self.history.len() - 1);
        }
        let lower = query.to_lowercase();
        for (i, entry) in self.history.iter().enumerate().rev() {
            let entry_lower = entry.to_lowercase();
            if entry_lower.contains(lower.as_str()) {
                return Some(i);
            }
        }
        None
    }

    /// Narrow from the current match position backward so typing
    /// after cycling doesn't teleport to the newest match.
    fn search_refine(&self, query: &str) -> Option<usize> {
        if query.is_empty() {
            if self.history.is_empty() {
                return None;
            }
            return Some(self.history.len() - 1);
        }
        let start = self.search_match_idx.unwrap_or(self.history.len() - 1);
        let lower = query.to_lowercase();
        for (i, entry) in self.history[..=start].iter().enumerate().rev() {
            if entry.to_lowercase().contains(lower.as_str()) {
                return Some(i);
            }
        }
        None
    }

    fn search_cycle_next(&mut self) {
        let query = self.search_query.clone();
        let start = self.search_match_idx.unwrap_or(self.history.len());
        let lower = query.to_lowercase();
        let next = if start == 0 {
            self.history
                .iter()
                .enumerate()
                .rev()
                .find(|(_, entry)| {
                    if query.is_empty() {
                        true
                    } else {
                        entry.to_lowercase().contains(lower.as_str())
                    }
                })
                .map(|(i, _)| i)
        } else {
            let range = &self.history[..start];
            range
                .iter()
                .enumerate()
                .rev()
                .find(|(_, entry)| {
                    if query.is_empty() {
                        true
                    } else {
                        entry.to_lowercase().contains(lower.as_str())
                    }
                })
                .map(|(i, _)| i)
                .or_else(|| {
                    self.history
                        .iter()
                        .enumerate()
                        .rev()
                        .find(|(_, entry)| {
                            if query.is_empty() {
                                true
                            } else {
                                entry.to_lowercase().contains(lower.as_str())
                            }
                        })
                        .map(|(i, _)| i)
                })
        };
        if let Some(idx) = next {
            self.search_match_idx = Some(idx);
            self.buffer = self.history[idx].clone();
            self.cursor = self.buffer.len();
        }
    }

    fn exit_search_accept(&mut self) {
        if self.search_match_idx.is_none() {
            if let Some((draft, cursor)) = self.search_draft.take() {
                self.buffer = draft;
                self.cursor = cursor.min(self.buffer.len());
            }
        }
        self.search_mode = false;
        self.search_query.clear();
        self.search_match_idx = None;
        self.search_draft = None;
    }

    fn exit_search_cancel(&mut self) {
        self.search_mode = false;
        self.search_query.clear();
        self.search_match_idx = None;
        if let Some((draft, cursor)) = self.search_draft.take() {
            self.buffer = draft;
            self.cursor = cursor.min(self.buffer.len());
        } else {
            self.buffer.clear();
            self.cursor = 0;
        }
    }

    pub fn cancel_search(&mut self) {
        self.exit_search_cancel();
    }

    pub fn load_history_entry(&mut self, content: &str) {
        if content.is_empty() {
            return;
        }
        let is_dupe = self
            .history
            .last()
            .map(|prev| prev.as_str() == content)
            .unwrap_or(false);
        if !is_dupe {
            self.history.push(CompactString::new(content));
        }
    }

    fn handle_search_key(&mut self, key: KeyEvent) -> Option<CompactString> {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        match key.code {
            KeyCode::Char('f') if ctrl => {
                self.search_cycle_next();
                None
            }

            KeyCode::Char('c') if ctrl => {
                self.exit_search_cancel();
                None
            }
            KeyCode::Esc => {
                self.exit_search_cancel();
                None
            }

            KeyCode::Enter => {
                self.exit_search_accept();
                None
            }

            KeyCode::Backspace => {
                if !self.search_query.is_empty() {
                    self.search_query.pop();
                }
                // Widening (shorter query) — find newest match.
                if let Some(idx) = self.search_find(&self.search_query) {
                    self.search_match_idx = Some(idx);
                    self.buffer = self.history[idx].clone();
                    self.cursor = self.buffer.len();
                } else {
                    self.search_match_idx = None;
                    self.buffer.clear();
                    self.cursor = 0;
                }
                None
            }

            KeyCode::Char(c) if !ctrl => {
                self.search_query.push(c);
                if let Some(idx) = self.search_refine(&self.search_query) {
                    self.search_match_idx = Some(idx);
                    self.buffer = self.history[idx].clone();
                    self.cursor = self.buffer.len();
                } else {
                    self.search_match_idx = None;
                    self.buffer.clear();
                    self.cursor = 0;
                }
                None
            }

            _ => None,
        }
    }
}

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

    // dirge-5w9v: vertical motion moves by SOFT-wrapped display rows.
    // "abcdefghij" at wrap_w=4 wraps to ["abcd","efgh","ij"].
    #[test]
    fn wrap_vertical_target_moves_by_display_rows() {
        let s = "abcdefghij";
        let w = 4;
        // From end (row 2, col 2), Up lands on row 1 at the same column
        // ('g' = byte 6).
        assert_eq!(wrap_vertical_target(s, s.len(), w, true), Some(6));
        // From there (row 1, col 2), Down returns to row 2, column
        // clamped to its length (end = byte 10).
        assert_eq!(wrap_vertical_target(s, 6, w, false), Some(10));
        // Top display row → None (caller falls through to history).
        assert_eq!(wrap_vertical_target(s, 1, w, true), None);
        // Bottom display row → None.
        assert_eq!(wrap_vertical_target(s, 9, w, false), None);
    }

    #[test]
    fn test_prev_word_boundary_basic() {
        assert_eq!(prev_word_boundary("hello world", 11), 6);
        assert_eq!(prev_word_boundary("hello world", 6), 0);
        assert_eq!(prev_word_boundary("hello world", 5), 0);
    }

    #[test]
    fn test_prev_word_from_middle() {
        assert_eq!(prev_word_boundary("hello world", 9), 6); // middle of "world"
    }

    #[test]
    fn test_prev_word_at_start() {
        assert_eq!(prev_word_boundary("hello", 0), 0);
    }

    #[test]
    fn test_prev_word_punctuation() {
        assert_eq!(prev_word_boundary("foo.bar", 7), 4); // start of "bar"
        assert_eq!(prev_word_boundary("foo.bar", 4), 0); // start of "foo"
    }

    #[test]
    fn test_next_word_boundary_basic() {
        // "hello world foo" = 15 bytes
        assert_eq!(next_word_boundary("hello world foo", 0), 6);
        assert_eq!(next_word_boundary("hello world foo", 6), 12);
        assert_eq!(next_word_boundary("hello world foo", 12), 15);
    }

    #[test]
    fn test_next_word_at_end() {
        assert_eq!(next_word_boundary("hello", 5), 5);
    }

    #[test]
    fn test_next_word_punctuation() {
        // With updated logic: from start, skip "foo" + "." → land at "bar_baz" (byte 4)
        assert_eq!(next_word_boundary("foo.bar_baz", 0), 4);
        assert_eq!(next_word_boundary("foo.bar_baz", 3), 4); // from '.', skip it → byte 4
        assert_eq!(next_word_boundary("foo.bar_baz", 4), 11); // skip "bar_baz" → end
    }

    #[test]
    fn test_prev_word_multibyte() {
        // "hå bør": h(0) å(1,2→3) sp(3) b(4) ø(5,6→7) r(7→8)
        assert_eq!(prev_word_boundary("hå bør", 7), 4); // from after 'ø' → start of "bør" at 4
        assert_eq!(prev_word_boundary("hå bør", 4), 0); // from start of "bør" → start of "hå" at 0
    }

    #[test]
    fn test_next_word_multibyte() {
        // "hå bør": 8 bytes. h(0) å(1-2=3) sp(3) b(4) ø(5-6=7) r(7→8)
        assert_eq!(next_word_boundary("hå bør", 0), 4); // skip "hå ", land at "b" (byte 4)
        assert_eq!(next_word_boundary("hå bør", 4), 8); // skip "bør", land at end
    }

    #[test]
    fn test_cursor_line_start() {
        assert_eq!(cursor_line_start("hello\nworld", 10), 6);
        assert_eq!(cursor_line_start("hello\nworld", 3), 0);
        assert_eq!(cursor_line_start("single", 6), 0);
    }

    #[test]
    fn test_prev_line_start() {
        assert_eq!(prev_line_start("hello\nworld", 10), Some(0));
        assert_eq!(prev_line_start("hello\nworld", 3), None);
    }

    #[test]
    fn test_next_line_start() {
        assert_eq!(next_line_start("hello\nworld", 0), Some(6));
        assert_eq!(next_line_start("hello\nworld", 10), None);
    }

    // --- H-batch1-2: byte_at_char_col panic-defence ----------------

    #[test]
    fn byte_at_char_col_ascii_round_trip() {
        // "hello\nworld" — moving from col 3 on "world" (target line)
        let s = "hello\nworld";
        assert_eq!(byte_at_char_col(s, 6, 11, 3), 9);
    }

    #[test]
    fn byte_at_char_col_handles_multibyte_target() {
        // Source line has 4 ASCII chars; target line has 2 emoji
        // chars. Moving "col 3" to a 2-char target → clamp to end.
        let s = "abcd\n🦀🚀";
        // col 0 on "🦀🚀" lands at start byte (just after \n = 5)
        assert_eq!(byte_at_char_col(s, 5, s.len(), 0), 5);
        // col 1 = start of 🚀 (after 4-byte 🦀)
        assert_eq!(byte_at_char_col(s, 5, s.len(), 1), 9);
        // col 2 = end-of-line
        assert_eq!(byte_at_char_col(s, 5, s.len(), 2), s.len());
        // col 3 (past EOL) clamps to end
        assert_eq!(byte_at_char_col(s, 5, s.len(), 3), s.len());
    }

    /// History navigation must preserve the user's in-progress draft.
    /// Up stashes it; Down past the newest entry restores it.
    #[test]
    fn history_up_stashes_in_progress_draft() {
        let mut e = InputEditor::new();
        e.history.push("first".into());
        e.history.push("second".into());
        e.insert_str("working on this");
        let saved_cursor = e.cursor;

        e.history_up();
        assert_eq!(e.buffer.as_str(), "second");
        // The in-progress text is stashed, not lost.
        assert_eq!(
            e.history_draft.as_ref().map(|(s, c)| (s.as_str(), *c)),
            Some(("working on this", saved_cursor))
        );

        e.history_up();
        assert_eq!(e.buffer.as_str(), "first");

        e.history_down();
        assert_eq!(e.buffer.as_str(), "second");

        // Down past the most-recent entry restores the draft.
        e.history_down();
        assert_eq!(e.buffer.as_str(), "working on this");
        assert_eq!(e.cursor, saved_cursor);
        assert!(e.history_draft.is_none());
    }

    #[test]
    fn history_up_with_empty_draft_still_returns_empty_on_restore() {
        let mut e = InputEditor::new();
        e.history.push("only".into());

        e.history_up();
        assert_eq!(e.buffer.as_str(), "only");

        e.history_down();
        assert_eq!(e.buffer.as_str(), "");
        assert!(e.history_draft.is_none());
    }

    #[cfg(feature = "slash-completion")]
    #[test]
    fn right_arrow_accepts_slash_ghost_completion() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        let mut e = InputEditor::new();
        e.insert_str("/disp");
        let out = e.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
        assert!(out.is_none());
        assert_eq!(e.buffer.as_str(), "/display");
        assert_eq!(e.cursor, e.buffer.len());
    }

    #[test]
    fn right_arrow_without_ghost_moves_cursor() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        let mut e = InputEditor::new();
        e.insert_str("hello");
        e.cursor = 0; // not at end, and not a slash command
        e.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
        assert_eq!(e.cursor, 1);
        assert_eq!(e.buffer.as_str(), "hello");
    }

    #[test]
    fn history_down_with_no_navigation_is_noop() {
        let mut e = InputEditor::new();
        e.insert_str("draft");
        let before = e.buffer.clone();
        e.history_down();
        assert_eq!(e.buffer, before);
        assert!(e.history_draft.is_none());
    }

    #[test]
    fn set_text_clears_history_draft() {
        let mut e = InputEditor::new();
        e.history.push("h".into());
        e.insert_str("draft");
        e.history_up();
        assert!(e.history_draft.is_some());
        e.set_text("fork-restored");
        assert!(e.history_draft.is_none());
    }

    #[test]
    fn byte_at_char_col_handles_multibyte_source_for_history_up() {
        // Regression: source line had emoji; col was previously
        // counted in BYTES (4 per emoji). Moving up to a shorter
        // ASCII line landed mid-codepoint or past EOL of the
        // target — the next replace_range panicked.
        let s = "🦀🦀🦀\nabc";
        // The source line is "🦀🦀🦀" — 3 chars, 12 bytes. From
        // byte-cursor 12 (end of source), char_col should be 3.
        // Moving "up" to ... well there's no line above the source,
        // but as the target-side helper: col 3 on "abc" (3-char
        // line) lands at end (byte 3 relative to target start = 13).
        // Target line is &s[13..16] = "abc".
        assert_eq!(byte_at_char_col(s, 13, s.len(), 3), s.len());
    }

    /// User-reported bug: a multi-line paste inserted a marker like
    /// `\x01<idx>\x01` into the buffer; the renderer printed the raw
    /// bytes, so the user only saw the bare digit between two
    /// invisible SOH characters instead of the intended
    /// `[N lines pasted]` placeholder. `display()` is the fix —
    /// these tests pin the projection AND the cursor mapping.
    #[test]
    fn display_no_marker_passes_through() {
        let mut e = InputEditor::new();
        e.insert_str("hello world");
        e.cursor = 5;
        let (s, c) = e.display();
        assert_eq!(s, "hello world");
        assert_eq!(c, 5);
    }

    #[test]
    fn display_marker_renders_as_placeholder() {
        let mut e = InputEditor::new();
        // 5 lines triggers the collapse threshold.
        e.handle_paste("a\nb\nc\nd\ne");
        let (s, _) = e.display();
        assert_eq!(s, "[5 lines pasted]");
    }

    #[test]
    fn display_cursor_maps_to_end_of_placeholder() {
        let mut e = InputEditor::new();
        e.handle_paste("a\nb\nc\nd\ne");
        // handle_paste leaves the cursor at the end of the marker
        // (after the closing \x01). Verify display maps it to the
        // end of the placeholder string.
        let (s, c) = e.display();
        assert_eq!(s, "[5 lines pasted]");
        assert_eq!(c, s.len());
    }

    #[test]
    fn display_cursor_before_marker_unchanged() {
        let mut e = InputEditor::new();
        e.insert_str("pre ");
        e.handle_paste("a\nb\nc\nd\ne");
        // Cursor is currently at end (after the marker). Reset to
        // before "pre" and confirm the display cursor matches.
        e.cursor = 0;
        let (s, c) = e.display();
        assert!(
            s.starts_with("pre [") && s.contains("lines pasted]"),
            "got {s:?}",
        );
        assert_eq!(c, 0);
    }

    #[test]
    fn display_text_after_marker_offset_correctly() {
        let mut e = InputEditor::new();
        e.handle_paste("a\nb\nc\nd\ne");
        e.insert_str(" suffix");
        // Cursor sits at end of " suffix" — verify display maps it
        // to the end of `[N lines pasted] suffix`.
        let (s, c) = e.display();
        assert_eq!(s, "[5 lines pasted] suffix");
        assert_eq!(c, s.len());
    }
}