1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
//! Editor component for multi-line text editing.
//!
//! Provides a text editor with cursor positioning, selection, and keyboard input.
use std::any::Any;
use std::collections::HashMap;
use std::sync::OnceLock;
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyModifiers};
use unicode_width::UnicodeWidthStr;
use super::component::{Component, Focusable};
use super::keybindings::Keybindings;
use crate::ansi::CURSOR_MARKER;
use crate::kill_ring::{KillRing, PushOptions};
use crate::theme::Color;
use crate::undo_stack::UndoStack;
/// Editor style configuration.
#[derive(Debug, Clone)]
pub struct EditorStyle {
pub prompt: String,
pub placeholder: String,
}
impl Default for EditorStyle {
fn default() -> Self {
Self {
prompt: "> ".to_string(),
placeholder: String::new(),
}
}
}
/// Editor options.
#[derive(Debug, Clone, Default)]
pub struct EditorOptions {
/// Padding on left and right.
pub padding_x: usize,
/// Maximum visible lines for autocomplete.
pub autocomplete_max_visible: usize,
/// Placeholder text when empty.
pub placeholder: Option<String>,
/// Initial text content.
pub initial_text: Option<String>,
}
/// Editor state.
#[derive(Debug, Clone)]
struct EditorState {
/// Lines of text.
lines: Vec<String>,
/// Cursor row (line index).
cursor_row: usize,
/// Cursor column (character index within line).
cursor_col: usize,
/// Selection anchor (row, col) if any.
selection_anchor: Option<(usize, usize)>,
/// Scroll offset for multi-line.
#[allow(dead_code)]
scroll_offset: usize,
/// Whether the editor is focused.
focused: bool,
/// History of submitted lines.
history: Vec<String>,
/// History index for navigation.
history_index: usize,
}
impl Default for EditorState {
fn default() -> Self {
Self {
lines: vec![String::new()],
cursor_row: 0,
cursor_col: 0,
selection_anchor: None,
scroll_offset: 0,
focused: false,
history: Vec::new(),
history_index: 0,
}
}
}
/// Greatest char-boundary byte index in `s` that is `<= idx` (clamped to
/// `s.len()`). The editor tracks `cursor_col` as a **byte** index and keeps it
/// on a char boundary; this helper restores that invariant when a caller
/// supplies a column that may be mid-character (e.g. clamping after moving
/// across lines of differing widths) and when converting external char counts.
///
/// Why byte indices: every `String` mutation the editor performs
/// (`insert`, `remove`, `truncate`, `drain`) and the `len()` comparisons used
/// for clamping are byte-indexed in `std`. Treating `cursor_col` as a byte
/// offset (advanced by `ch.len_utf8()`, never `+1`) keeps all of those sound
/// for multibyte input. Movement ops use this helper to step by *character*
/// while storing bytes.
fn snap_boundary(s: &str, idx: usize) -> usize {
let idx = idx.min(s.len());
// A valid char boundary (including the END of the string) is kept as-is —
// the old `take_while(b <= idx)` returned the START of the char AT `idx`
// for boundary positions, so a caret placed exactly after the last char
// (e.g. autocomplete accept: `set_cursor(0, len)`) snapped one char EARLY
// and the terminal showed "/mode|l" with the final char dangling past the
// caret. Mid-character positions snap DOWN to the char start instead.
if s.is_char_boundary(idx) {
return idx;
}
s.char_indices()
.take_while(|(b, _)| *b < idx)
.last()
.map(|(b, _)| b)
.unwrap_or(0)
}
/// A folded store of a large paste, keyed by the id rendered in its marker.
/// The document (`EditorState::lines`) only ever carries the short
/// `[paste #id …]` marker; the real text lives here until the draft is
/// submitted, at which point [`Editor::get_expanded_text`] splices it back in.
#[derive(Debug, Clone)]
struct PasteEntry {
content: String,
}
/// Matches a whole `[paste #id …]` marker (group 1 = id).
fn paste_marker_regex() -> &'static regex::Regex {
static RE: OnceLock<regex::Regex> = OnceLock::new();
RE.get_or_init(|| regex::Regex::new(r"\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]").unwrap())
}
/// The byte length of the `[paste #id …]` marker ending exactly at `end`
/// (`end` is a byte offset in `line`), or `0` when no marker ends there.
fn paste_marker_len_ending_at(line: &str, end: usize) -> usize {
for m in paste_marker_regex().find_iter(line) {
if m.end() == end {
return m.as_str().len();
}
}
0
}
/// A paste folds when it exceeds either threshold (native pi's `handlePaste`).
const PASTE_FOLD_LINE_THRESHOLD: usize = 10;
const PASTE_FOLD_CHAR_THRESHOLD: usize = 1000;
/// Replace every `[paste #id …]` marker in `document` with its stashed body
/// (native pi's `expandPasteMarkers`). Markers whose id is absent from
/// `pastes` are left as-is so a stray marker never silently vanishes.
fn expand_paste_markers(document: &str, pastes: &HashMap<u32, PasteEntry>) -> String {
if pastes.is_empty() || !document.contains("[paste #") {
return document.to_string();
}
paste_marker_regex()
.replace_all(document, |caps: ®ex::Captures| {
let id: u32 = caps[1].parse().unwrap_or(0);
match pastes.get(&id) {
Some(entry) => entry.content.clone(),
None => caps[0].to_string(),
}
})
.into_owned()
}
/// Decode the kitty CSI-u form a client may emit for `Ctrl+<letter>`
/// (`ESC[<code>;5u`), which native pi decodes before folding
/// (`handlePaste`). Scalars that are not a `Ctrl+letter` chord are left as-is.
fn decode_csi_u_ctrl(text: &str) -> String {
if !text.contains("\x1b[") {
return text.to_string();
}
static RE: OnceLock<regex::Regex> = OnceLock::new();
let re = RE.get_or_init(|| regex::Regex::new(r"\x1b\[(\d+);5u").unwrap());
re.replace_all(text, |caps: ®ex::Captures| {
let code: u32 = caps[1].parse().unwrap_or(0);
let lower = 0x61..=0x7a;
let upper = 0x41..=0x5a;
if lower.contains(&code) {
char::from_u32(code - 96)
.map(String::from)
.unwrap_or_default()
} else if upper.contains(&code) {
char::from_u32(code - 64)
.map(String::from)
.unwrap_or_default()
} else {
caps[0].to_string()
}
})
.into_owned()
}
/// Split a logical editor line into terminal-width chunks. The editor keeps
/// logical lines for editing and cursor movement; wrapping is strictly a
/// rendering concern so a long draft cannot escape the bordered input box.
fn wrap_line_ranges(line: &str, max_width: usize) -> Vec<(usize, usize)> {
if line.is_empty() {
return vec![(0, 0)];
}
let max_width = max_width.max(1);
let mut ranges = Vec::new();
let mut start = 0;
let mut width = 0;
for (idx, ch) in line.char_indices() {
let char_width = UnicodeWidthStr::width(ch.to_string().as_str());
if idx > start && width + char_width > max_width {
ranges.push((start, idx));
start = idx;
width = 0;
}
width += char_width;
}
ranges.push((start, line.len()));
ranges
}
/// Insert the zero-width cursor marker at a visible column without slicing
/// through ANSI escape sequences added for selection/placeholder styling.
fn insert_cursor_marker(text: &str, column: usize) -> String {
let mut out = String::with_capacity(text.len() + CURSOR_MARKER.len());
let mut visible = 0;
let mut chars = text.char_indices().peekable();
let mut inserted = false;
while let Some((idx, ch)) = chars.next() {
if ch == '\x1b' {
out.push(ch);
while let Some((_, esc)) = chars.next() {
out.push(esc);
if esc == '\x07' || ('@'..='~').contains(&esc) {
break;
}
}
continue;
}
if !inserted && visible >= column {
out.push_str(CURSOR_MARKER);
inserted = true;
}
out.push(ch);
visible += UnicodeWidthStr::width(ch.to_string().as_str());
let _ = idx;
}
if !inserted {
out.push_str(CURSOR_MARKER);
}
out
}
/// Editor - A multi-line text editor component.
pub struct Editor {
state: Mutex<EditorState>,
options: EditorOptions,
#[allow(dead_code)]
style: EditorStyle,
#[allow(dead_code)]
keybindings: Arc<Keybindings>,
on_submit: Mutex<Option<Arc<dyn Fn(&str) + Send + Sync>>>,
on_change: Mutex<Option<Arc<dyn Fn(&str) + Send + Sync>>>,
/// Undo history (text + caret snapshots). Pushed before each mutation;
/// consecutive character insertions coalesce into one entry.
undo_stack: Mutex<UndoStack<EditorSnapshot>>,
/// Popped undo entries, for Ctrl+R redo.
redo_stack: Mutex<Vec<EditorSnapshot>>,
/// Emacs-style kill ring for Ctrl+K/U/W kills; Ctrl+Y yanks.
kill_ring: Mutex<KillRing>,
/// The last mutation kind, for undo coalescing + kill accumulation.
last_action: Mutex<Option<&'static str>>,
/// Character-jump mode (pi `jumpForward`/`jumpBackward`): `Some(1)` waits
/// for the next printable char to jump forward to, `Some(-1)` backward.
/// The next character input consumes it instead of inserting.
jump_mode: Mutex<Option<i32>>,
/// Explicit top/bottom border color. `None` ⇒ the theme's default border
/// color. Native pi's `editor.borderColor` (used for bash mode and thinking
/// levels via `updateEditorBorderColor`).
border_color: Mutex<Option<Color>>,
/// Working indicator text shown inside the top border. `None` means idle.
/// When `Some`, the top border line renders the spinner + elapsed + message
/// instead of plain `─` characters (pi's working-inside-input-border style).
working: Mutex<Option<WorkingState>>,
/// Folded pastes: `id -> content`, referenced by a `[paste #id …]` marker
/// in `state.lines`. Mirrors native pi's `pastes` map.
pastes: Mutex<HashMap<u32, PasteEntry>>,
/// Monotonic id source for [`Self::pastes`] (native pi's `pasteCounter`).
paste_counter: Mutex<u32>,
}
/// State for the working indicator embedded in the editor's top border.
#[derive(Debug, Clone)]
pub struct WorkingState {
/// Spinner animation frame index.
pub frame: usize,
/// When the working state started (for elapsed time display).
pub started_at: std::time::Instant,
/// The message to display (e.g. "Working…").
pub message: String,
}
/// A restorable editor state snapshot (text + caret, plus the folded paste
/// store so undo can resurrect a marker's content). Selection/scroll/focus
/// are not part of undo (mirrors the TS `EditorSnapshot`).
#[derive(Clone)]
struct EditorSnapshot {
lines: Vec<String>,
cursor_row: usize,
cursor_col: usize,
pastes: HashMap<u32, PasteEntry>,
paste_counter: u32,
}
impl Editor {
/// Create a new editor with options.
pub fn new(options: EditorOptions, style: EditorStyle, keybindings: Arc<Keybindings>) -> Self {
let mut state = EditorState::default();
if let Some(text) = &options.initial_text {
state.lines = text.split('\n').map(|s| s.to_string()).collect();
if state.lines.is_empty() {
state.lines.push(String::new());
}
}
Self {
state: Mutex::new(state),
options,
style,
keybindings,
on_submit: Mutex::new(None),
on_change: Mutex::new(None),
undo_stack: Mutex::new(UndoStack::with_max_size(200)),
redo_stack: Mutex::new(Vec::new()),
kill_ring: Mutex::new(KillRing::new()),
last_action: Mutex::new(None),
jump_mode: Mutex::new(None),
border_color: Mutex::new(None),
working: Mutex::new(None),
pastes: Mutex::new(HashMap::new()),
paste_counter: Mutex::new(0),
}
}
/// Create a new editor with default options.
pub fn simple() -> Self {
Self::new(
EditorOptions::default(),
EditorStyle::default(),
Arc::new(Keybindings::new()),
)
}
/// Set the text content.
pub fn set_text(&self, text: &str) {
if let Ok(mut state) = self.state.lock() {
state.lines = if text.is_empty() {
vec![String::new()]
} else {
text.split('\n').map(|s| s.to_string()).collect()
};
if state.lines.is_empty() {
state.lines.push(String::new());
}
state.cursor_row = 0;
state.cursor_col = 0;
}
// A programmatic replacement discards any folded pastes: the new text
// is the whole truth (mirrors native pi's `setText` clearing `pastes`).
self.reset_pastes();
// Mirrors native `setTextInternal`: programmatic replacement is a change.
self.notify_change();
}
/// Get the text content **as shown**: folded large pastes appear as their
/// `[paste #id …]` marker, not their full body. This is the right source
/// for UI state that reasons about what is on screen (autocomplete,
/// empty-checks). Use [`Self::get_expanded_text`] for anything that must
/// see the user's real content.
pub fn get_text(&self) -> String {
self.state
.lock()
.map(|s| s.lines.join("\n"))
.unwrap_or_default()
}
/// Get the text content **with folded pastes expanded** (native pi's
/// `getExpandedText`): every `[paste #id …]` marker is replaced by the full
/// pasted body. Submission, the external editor and extension reads all go
/// through here so a folded paste is never sent truncated.
pub fn get_expanded_text(&self) -> String {
let document = self.get_text();
let pastes = self.pastes.lock().map(|p| p.clone()).unwrap_or_default();
expand_paste_markers(&document, &pastes)
}
/// Clear the folded-paste store and reset the id counter.
fn reset_pastes(&self) {
if let Ok(mut pastes) = self.pastes.lock() {
pastes.clear();
}
if let Ok(mut counter) = self.paste_counter.lock() {
*counter = 0;
}
}
/// The folded-paste id whose marker starts exactly at byte offset
/// `start` on line `row`, if any.
fn paste_id_at_marker_start(&self, row: usize, start: usize) -> Option<u32> {
let state = self.state.lock().ok()?;
let line = state.lines.get(row)?;
paste_marker_regex()
.captures_iter(line)
.find(|caps| caps.get(0).unwrap().start() == start)
.and_then(|caps| caps[1].parse::<u32>().ok())
}
/// Drop a folded paste and renumber the higher ids down by one so the
/// markers left in the document stay contiguous (native pi renumbers in
/// `handleBackspace`). Also rewrites the surviving markers in place.
fn remove_paste(&self, id: u32) {
{
let mut pastes = self.pastes.lock().unwrap();
if pastes.remove(&id).is_none() {
return;
}
let higher: Vec<u32> = pastes.keys().copied().filter(|k| *k > id).collect();
for old in higher {
if let Some(entry) = pastes.remove(&old) {
pastes.insert(old - 1, entry);
}
}
}
{
let mut counter = self.paste_counter.lock().unwrap();
*counter = counter.saturating_sub(1);
}
// Rewrite the markers still in the document: ids above the removed one
// shift down by one, matching the renumbered store.
if let Ok(mut state) = self.state.lock() {
for line in state.lines.iter_mut() {
*line = paste_marker_regex()
.replace_all(line, |caps: ®ex::Captures| {
let n: u32 = caps[1].parse().unwrap_or(0);
if n <= id {
caps[0].to_string()
} else {
// Group 2 already carries the leading space + suffix.
let suffix = caps.get(2).map(|m| m.as_str()).unwrap_or("");
format!("[paste #{}{suffix}]", n - 1)
}
})
.into_owned();
}
}
}
/// Fold a pasted block: short pastes are inserted verbatim; a block over
/// the size threshold is stashed and replaced by a `[paste #id …]` marker
/// so the input box stays readable. Mirrors native pi's `handlePaste`
/// (fold when `>10` lines or `>1000` chars).
///
/// A single-line pasted file path is special-cased by the caller (image
/// attachment), so this only handles text.
pub fn handle_paste(&self, text: &str) {
// Decode the CSI-u `Ctrl+<letter>` form a client may hand us, and
// normalize line endings + tabs (native pi's `normalizeText`).
let decoded = decode_csi_u_ctrl(text)
.replace("\r\n", "\n")
.replace('\r', "\n")
.replace('\t', " ");
// Drop control characters, keeping newlines (native pi filters
// `char === "\n" || char.charCodeAt(0) >= 32`).
let filtered: String = decoded
.chars()
.filter(|c| *c == '\n' || (*c as u32) >= 32)
.collect();
if filtered.is_empty() {
return;
}
let line_count = filtered.split('\n').count();
let char_count = filtered.chars().count();
if line_count > PASTE_FOLD_LINE_THRESHOLD || char_count > PASTE_FOLD_CHAR_THRESHOLD {
self.push_undo("insert");
if self.has_selection() {
self.delete_selection_no_undo();
}
let (id, by_lines, count) = {
let mut counter = self.paste_counter.lock().unwrap();
*counter += 1;
let id = *counter;
if line_count > PASTE_FOLD_LINE_THRESHOLD {
(id, true, line_count)
} else {
(id, false, char_count)
}
};
if let Ok(mut pastes) = self.pastes.lock() {
pastes.insert(id, PasteEntry { content: filtered });
}
let marker = if by_lines {
format!("[paste #{id} +{count} lines]")
} else {
format!("[paste #{id} {count} chars]")
};
self.insert_no_undo(&marker);
*self.last_action.lock().unwrap() = Some("insert");
} else {
self.insert(&filtered);
}
}
/// Clear the editor.
pub fn clear(&self) {
if let Ok(mut state) = self.state.lock() {
state.lines = vec![String::new()];
state.cursor_row = 0;
state.cursor_col = 0;
state.selection_anchor = None;
}
self.reset_pastes();
// Native pi's editor notifies change observers for programmatic clears
// (`setTextInternal`), so derived UI state (bash-mode border color,
// autocomplete) drops the stale draft. `submit()` relies on this to
// reset the border after routing a `!command`.
self.notify_change();
}
/// Set callback for when text is submitted (Enter pressed).
pub fn on_submit(&self, callback: Arc<dyn Fn(&str) + Send + Sync>) {
if let Ok(mut cb) = self.on_submit.lock() {
*cb = Some(callback);
}
}
/// Set callback for when text changes.
pub fn on_change(&self, callback: Arc<dyn Fn(&str) + Send + Sync>) {
if let Ok(mut cb) = self.on_change.lock() {
*cb = Some(callback);
}
}
/// Get cursor position.
pub fn cursor_position(&self) -> (usize, usize) {
self.state
.lock()
.map(|s| (s.cursor_row, s.cursor_col))
.unwrap_or((0, 0))
}
/// Set the cursor position (clamped to text bounds), clearing any
/// in-progress selection. Used by autocomplete to place the caret after
/// accepting a suggestion (`set_text` resets the caret to the start).
///
/// `col` is interpreted as a **byte** offset (callers in the autocomplete
/// path pass byte indices from `String::len`/`char_indices`) and snapped to
/// the nearest preceding char boundary so multibyte input never lands
/// mid-character.
pub fn set_cursor(&self, row: usize, col: usize) {
if let Ok(mut state) = self.state.lock() {
let row = row.min(state.lines.len().saturating_sub(1));
let col = snap_boundary(&state.lines[row], col);
state.cursor_row = row;
state.cursor_col = col;
state.selection_anchor = None;
}
}
/// Snapshot the current text + caret state (for undo/redo), including the
/// folded-paste store so undo can bring a dropped paste back.
fn snapshot_state(&self) -> EditorSnapshot {
let state = self.state.lock().unwrap();
EditorSnapshot {
lines: state.lines.clone(),
cursor_row: state.cursor_row,
cursor_col: state.cursor_col,
pastes: self.pastes.lock().map(|p| p.clone()).unwrap_or_default(),
paste_counter: self.paste_counter.lock().map(|c| *c).unwrap_or(0),
}
}
/// Restore a snapshot, notifying change observers.
fn restore_state(&self, snap: &EditorSnapshot) {
if let Ok(mut state) = self.state.lock() {
state.lines = snap.lines.clone();
state.cursor_row = snap.cursor_row;
state.cursor_col = snap.cursor_col;
// Snapshots don't carry the selection; undo/redo ends it.
state.selection_anchor = None;
}
if let Ok(mut pastes) = self.pastes.lock() {
*pastes = snap.pastes.clone();
}
if let Ok(mut counter) = self.paste_counter.lock() {
*counter = snap.paste_counter;
}
self.notify_change();
}
/// Record an undo snapshot before a mutation. `action` names the mutation
/// kind: consecutive `"insert"` actions coalesce into a single undo entry
/// (typing a word undoes as one step, mirroring the TS coalescing); any
/// other mutation starts a fresh entry. A new mutation clears the redo
/// stack (the classic undo/redo semantics).
fn push_undo(&self, action: &'static str) {
let coalesce = action == "insert" && *self.last_action.lock().unwrap() == Some("insert");
if !coalesce {
let snap = self.snapshot_state();
if let Ok(mut stack) = self.undo_stack.lock() {
stack.push(snap);
}
if let Ok(mut redo) = self.redo_stack.lock() {
redo.clear();
}
}
*self.last_action.lock().unwrap() = Some(action);
}
/// Undo the last mutation (Ctrl+-). Restores the prior snapshot; the
/// undone state moves to the redo stack for Ctrl+R.
pub fn undo(&self) {
let popped = self.undo_stack.lock().unwrap().pop();
let Some(snap) = popped else { return };
// The current state is the redo target.
self.redo_stack.lock().unwrap().push(self.snapshot_state());
self.restore_state(&snap);
*self.last_action.lock().unwrap() = None;
}
/// Redo the last undone mutation (Ctrl+R).
pub fn redo(&self) {
let popped = self.redo_stack.lock().unwrap().pop();
let Some(snap) = popped else { return };
self.undo_stack.lock().unwrap().push(self.snapshot_state());
self.restore_state(&snap);
*self.last_action.lock().unwrap() = None;
}
/// Push killed (deleted) text onto the kill ring, accumulating consecutive
/// kills into one entry (mirrors the TS kill-ring semantics).
fn kill(&self, text: String, prepend: bool) {
if text.is_empty() {
return;
}
let accumulate = *self.last_action.lock().unwrap() == Some("kill");
if let Ok(mut ring) = self.kill_ring.lock() {
ring.push(
&text,
PushOptions {
prepend,
accumulate,
},
);
}
*self.last_action.lock().unwrap() = Some("kill");
}
/// Yank (paste) the most recent kill at the cursor (Ctrl+Y). Replaces an
/// active selection.
pub fn yank(&self) {
let text = self.kill_ring.lock().unwrap().peek().map(str::to_string);
let Some(text) = text else { return };
self.push_undo("yank");
if self.has_selection() {
self.delete_selection_no_undo();
}
self.insert_no_undo(&text);
*self.last_action.lock().unwrap() = Some("yank");
}
/// Yank-pop: rotate the kill ring and yank the next entry (Alt+Y).
pub fn yank_pop(&self) {
if self.kill_ring.lock().unwrap().len() <= 1 {
return;
}
self.kill_ring.lock().unwrap().rotate();
self.yank();
}
// -------------------------------------------------------------------
// Selection (Shift+arrows select, Ctrl+X/C/V cut/copy/paste).
// -------------------------------------------------------------------
/// Whether a selection is active.
pub fn has_selection(&self) -> bool {
self.state.lock().unwrap().selection_anchor.is_some()
}
/// The ordered selection span `(start_row, start_col, end_row, end_col)`
/// with start <= end (byte offsets, both on char boundaries).
fn selection_ordered(&self) -> Option<(usize, usize, usize, usize)> {
let state = self.state.lock().unwrap();
let (ar, ac) = state.selection_anchor?;
let (br, bc) = (state.cursor_row, state.cursor_col);
Some(if (ar, ac) <= (br, bc) {
(ar, ac, br, bc)
} else {
(br, bc, ar, ac)
})
}
/// The selected text ("\n"-joined across rows), if any.
pub fn selected_text(&self) -> Option<String> {
let (sr, sc, er, ec) = self.selection_ordered()?;
let lines = self.state.lock().unwrap().lines.clone();
if sr == er {
Some(lines[sr][sc..ec].to_string())
} else {
let mut out = String::new();
out.push_str(&lines[sr][sc..]);
for r in sr + 1..er {
out.push('\n');
out.push_str(&lines[r]);
}
out.push('\n');
out.push_str(&lines[er][..ec]);
Some(out)
}
}
/// The selection span on `row`, as `(start_col, end_col)` byte offsets,
/// for render-time highlighting. `None` when the row is outside the span.
fn selection_span_on_row(&self, state: &EditorState, row: usize) -> Option<(usize, usize)> {
let (ar, ac) = state.selection_anchor?;
let (br, bc) = (state.cursor_row, state.cursor_col);
let (sr, sc, er, ec) = if (ar, ac) <= (br, bc) {
(ar, ac, br, bc)
} else {
(br, bc, ar, ac)
};
if row < sr || row > er {
return None;
}
if sr == er {
(sc != ec).then_some((sc, ec))
} else if row == sr {
(sc < state.lines[row].len()).then_some((sc, state.lines[row].len()))
} else if row == er {
(ec > 0).then_some((0, ec))
} else {
(!state.lines[row].is_empty()).then_some((0, state.lines[row].len()))
}
}
/// Seed the selection anchor at the current caret (Shift+direction start).
fn begin_selection(&self) {
let mut state = self.state.lock().unwrap();
if state.selection_anchor.is_none() {
state.selection_anchor = Some((state.cursor_row, state.cursor_col));
}
}
/// Clear the active selection (plain cursor movement / edits).
fn clear_selection(&self) {
self.state.lock().unwrap().selection_anchor = None;
}
/// Delete the selected span, leaving the caret at its start. Pushes an
/// undo snapshot; no-op without a selection.
fn delete_selection(&self) {
if !self.has_selection() {
return;
}
self.push_undo("edit");
self.delete_selection_no_undo();
}
/// Delete the selected span WITHOUT an undo snapshot (caller pushed one,
/// e.g. a replace-through-insert coalesced with the insertion).
fn delete_selection_no_undo(&self) {
let (sr, sc, er, ec) = match self.selection_ordered() {
Some(s) => s,
None => return,
};
let mut state = self.state.lock().unwrap();
if sr == er {
state.lines[sr].replace_range(sc..ec, "");
state.cursor_row = sr;
state.cursor_col = sc;
} else {
let mut joined = state.lines[sr][..sc].to_string();
joined.push_str(&state.lines[er][ec..]);
state.lines.drain(sr + 1..=er);
state.lines[sr] = joined;
state.cursor_row = sr;
state.cursor_col = sc;
}
state.selection_anchor = None;
drop(state);
self.notify_change();
}
/// Copy the selection onto the kill ring (Ctrl+C). No-op without one.
pub fn copy_selection(&self) -> bool {
let Some(text) = self.selected_text() else {
return false;
};
if text.is_empty() {
return false;
}
if let Ok(mut ring) = self.kill_ring.lock() {
ring.push(&text, PushOptions::default());
}
true
}
/// Cut the selection (copy + delete, Ctrl+X). Returns whether anything
/// was cut.
pub fn cut_selection(&self) -> bool {
if !self.copy_selection() {
return false;
}
self.delete_selection();
true
}
/// Insert text at cursor position. Replaces an active selection (one undo
/// step: the snapshot is taken before the selection is deleted).
pub fn insert(&self, text: &str) {
self.push_undo("insert");
if self.has_selection() {
self.delete_selection_no_undo();
}
self.insert_no_undo(text);
}
/// Insert without an undo snapshot (caller pushed one — yank/replace
/// paths). Notifies change observers.
///
/// Line endings are normalized: `\r\n` and a lone `\r` are treated as one
/// newline. Pasted Windows text (and the `Event::Paste` payload on Unix,
/// which preserves CRLF) would otherwise insert literal carriage returns
/// into the line buffer — they render as garbage and break `cursor_col`
/// arithmetic on the next edit.
fn insert_no_undo(&self, text: &str) {
let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
if let Ok(mut state) = self.state.lock() {
for ch in normalized.chars() {
if ch == '\n' {
// Split line at cursor
let row = state.cursor_row;
let col = state.cursor_col;
let current_line = &mut state.lines[row];
let after = current_line.split_off(col);
state.lines.insert(row + 1, after);
state.cursor_row += 1;
state.cursor_col = 0;
} else {
let row = state.cursor_row;
let col = state.cursor_col;
state.lines[row].insert(col, ch);
// Advance by the BYTE length of the inserted char so
// `cursor_col` stays a valid char boundary (and a sound
// byte index for the next `String` mutation). The old
// `+= 1` was a char count and panicked on multibyte input
// the moment a second keystroke landed mid-character.
state.cursor_col += ch.len_utf8();
}
}
}
self.notify_change();
}
/// Delete character before cursor (Backspace). With a selection, deletes
/// the selection instead.
fn backspace(&self) {
if self.has_selection() {
self.delete_selection();
return;
}
// Backspacing over a `[paste #id …]` marker deletes the whole marker
// (and drops / renumbers the folded pastes). The marker is one atomic
// unit — the user cannot nibble it into an orphaned placeholder.
let deleted_marker = {
let state = self.state.lock().unwrap();
let row = state.cursor_row;
(state.cursor_col > 0)
.then(|| paste_marker_len_ending_at(&state.lines[row], state.cursor_col))
.filter(|len| *len > 0)
.map(|len| (row, state.cursor_col - len, len))
};
if let Some((row, start, len)) = deleted_marker {
// Snapshot FIRST: `remove_paste` mutates the paste store and
// renumbers the surviving markers, so undo must capture the
// pre-deletion state to be able to bring them all back.
self.push_undo("edit");
let id = self.paste_id_at_marker_start(row, start);
// Delete the marker text BEFORE renumbering, so the renumber pass
// (which can change a marker's byte length when an id crosses
// `#10 -> #9`) never has to keep a stale `start..start+len` valid.
if let Ok(mut state) = self.state.lock() {
state.lines[row].replace_range(start..start + len, "");
state.cursor_col = start;
}
if let Some(id) = id {
self.remove_paste(id);
}
self.notify_change();
return;
}
self.push_undo("edit");
if let Ok(mut state) = self.state.lock() {
if state.cursor_col > 0 {
let row = state.cursor_row;
// Step back by the byte length of the char immediately
// before the cursor, then remove that char. (`remove` takes
// a byte index and must land on a boundary.) Compute the
// length through a shared borrow first so the mutable borrow
// for `remove` is the only outstanding alias.
let prev_len = state.lines[row][..state.cursor_col]
.chars()
.last()
.map(|c| c.len_utf8())
.unwrap_or(0);
let col = state.cursor_col - prev_len;
state.lines[row].remove(col);
state.cursor_col = col;
} else if state.cursor_row > 0 {
// Join with previous line
let row = state.cursor_row;
let current = state.lines.remove(row);
state.cursor_row -= 1;
let prev_row = state.cursor_row;
state.cursor_col = state.lines[prev_row].len();
state.lines[prev_row].push_str(¤t);
}
}
self.notify_change();
}
/// Delete character at cursor (Delete). With a selection, deletes the
/// selection instead.
fn delete(&self) {
if self.has_selection() {
self.delete_selection();
return;
}
self.push_undo("edit");
if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let line_len = state.lines[row].len();
if state.cursor_col < line_len {
let col = state.cursor_col;
state.lines[row].remove(col);
} else if row < state.lines.len() - 1 {
// Join with next line
let next = state.lines.remove(row + 1);
state.lines[row].push_str(&next);
}
}
self.notify_change();
}
/// Move cursor left.
fn cursor_left(&self) {
if let Ok(mut state) = self.state.lock() {
if state.cursor_col > 0 {
let row = state.cursor_row;
let line = &state.lines[row];
// A folded paste marker is atomic: step the whole marker.
let marker = paste_marker_len_ending_at(line, state.cursor_col);
if marker > 0 {
state.cursor_col -= marker;
return;
}
// Retrear by the byte length of the preceding char so the
// caret stays on a char boundary.
let prev_len = line[..state.cursor_col]
.chars()
.last()
.map(|c| c.len_utf8())
.unwrap_or(0);
state.cursor_col -= prev_len;
} else if state.cursor_row > 0 {
state.cursor_row -= 1;
state.cursor_col = state.lines[state.cursor_row].len();
}
}
}
/// Move cursor right.
fn cursor_right(&self) {
if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let line = &state.lines[row];
if state.cursor_col < line.len() {
// A folded paste marker is atomic: step the whole marker.
for m in paste_marker_regex().find_iter(line) {
if m.start() == state.cursor_col {
state.cursor_col = m.end();
return;
}
}
// Advance by the byte length of the char at the cursor.
let ch_len = line[state.cursor_col..]
.chars()
.next()
.map(|c| c.len_utf8())
.unwrap_or(0);
state.cursor_col += ch_len;
} else if row < state.lines.len() - 1 {
state.cursor_row += 1;
state.cursor_col = 0;
}
}
}
/// Move cursor up.
fn cursor_up(&self) {
if let Ok(mut state) = self.state.lock() {
if state.cursor_row > 0 {
state.cursor_row -= 1;
let new_row = state.cursor_row;
let max = state.lines[new_row].len();
// The byte column may fall mid-character in the new (shorter
// or differently-encoded) line; snap to a boundary.
state.cursor_col = snap_boundary(&state.lines[new_row], state.cursor_col.min(max));
}
}
}
/// Move cursor down.
fn cursor_down(&self) {
if let Ok(mut state) = self.state.lock() {
if state.cursor_row < state.lines.len() - 1 {
state.cursor_row += 1;
let new_row = state.cursor_row;
let max = state.lines[new_row].len();
state.cursor_col = snap_boundary(&state.lines[new_row], state.cursor_col.min(max));
}
}
}
/// Move cursor to start of line.
fn cursor_home(&self) {
if let Ok(mut state) = self.state.lock() {
state.cursor_col = 0;
}
}
/// Move cursor to end of line.
fn cursor_end(&self) {
if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
state.cursor_col = state.lines[row].len();
}
}
/// Kill the word before the cursor (Ctrl+W / Alt+Backspace): Emacs
/// backward-kill-word — skip the current word, then the intervening
/// delimiters, landing on the previous word's start.
fn kill_word_backward(&self) {
self.push_undo("kill");
let killed = if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let col = state.cursor_col;
let start = crate::word_navigation::find_word_backward(&state.lines[row], col);
let dead: String = state.lines[row].drain(start..col).collect();
state.cursor_col = start;
dead
} else {
String::new()
};
self.kill(killed, true);
self.notify_change();
}
/// Kill the word after the cursor (Alt+D / Alt+Delete).
fn kill_word_forward(&self) {
self.push_undo("kill");
let killed = if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let col = state.cursor_col;
// Kill only the current word (not the trailing delimiter) —
// `find_word_end` stops at the last word char.
let end = crate::word_navigation::find_word_end(&state.lines[row], col);
let dead: String = state.lines[row].drain(col..end).collect();
dead
} else {
String::new()
};
self.kill(killed, false);
self.notify_change();
}
/// Jump to the previous word boundary (Alt+Left).
fn cursor_word_left(&self) {
if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
state.cursor_col =
crate::word_navigation::find_word_backward(&state.lines[row], state.cursor_col);
}
}
/// Jump to the next word boundary (Alt+Right).
fn cursor_word_right(&self) {
if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
state.cursor_col =
crate::word_navigation::find_word_forward(&state.lines[row], state.cursor_col);
}
}
/// Page-scroll the editor caret up/down by a page (pi `tui.editor.pageUp/
/// pageDown`): move the cursor row by a page and clamp the column to the
/// target line (page = 10 rows; a terminal-height-aware version would need
/// the viewport, which the component doesn't own).
fn page_scroll(&self, dir: i32) {
const PAGE: usize = 10;
if let Ok(mut state) = self.state.lock() {
let target = if dir > 0 {
(state.cursor_row + PAGE).min(state.lines.len().saturating_sub(1))
} else {
state.cursor_row.saturating_sub(PAGE)
};
state.cursor_row = target;
let max = state.lines[target].len();
state.cursor_col = snap_boundary(&state.lines[target], state.cursor_col.min(max));
}
}
/// Jump the caret to the next/previous occurrence of `target` (pi
/// `jumpToChar`): scan the current line from after/before the caret, then
/// onward/backward line by line. Byte-safe: `find`/`rfind` return char
/// boundaries and all search offsets start on one.
fn jump_to_char(&self, target: char, dir: i32) {
let forward = dir > 0;
let mut state = self.state.lock().unwrap();
let start_row = state.cursor_row;
let mut row = start_row;
let step: isize = if forward { 1 } else { -1 };
loop {
let line = &state.lines[row];
let search_from = if row == start_row {
if forward {
(state.cursor_col + target.len_utf8()).min(line.len())
} else {
state.cursor_col.saturating_sub(target.len_utf8())
}
} else if forward {
0
} else {
line.len()
};
let found = if forward {
line[search_from..].find(target).map(|i| search_from + i)
} else {
line[..search_from].rfind(target)
};
if let Some(idx) = found {
state.cursor_row = row;
state.cursor_col = idx;
return;
}
let next = row as isize + step;
if next < 0 || next >= state.lines.len() as isize {
return;
}
row = next as usize;
}
}
/// Set an explicit top/bottom border color. `None` restores the theme's
/// default border color. Mirrors native pi's `editor.borderColor`.
pub fn set_border_color(&self, color: Option<Color>) {
if let Ok(mut guard) = self.border_color.lock() {
*guard = color;
}
}
/// The current explicit border color, if any.
pub fn border_color(&self) -> Option<Color> {
self.border_color.lock().ok().and_then(|guard| *guard)
}
/// Set the working state. When Some, shows a spinner + elapsed time + message
/// inside the top border. When None, shows the normal border.
pub fn set_working(&self, working: Option<WorkingState>) {
if let Ok(mut guard) = self.working.lock() {
*guard = working;
}
}
/// Get the current working state, if any.
pub fn working(&self) -> Option<WorkingState> {
self.working.lock().ok().and_then(|guard| guard.clone())
}
/// Submit current text (Enter).
fn submit(&self) {
// Send the EXPANDED draft: a folded `[paste #id …]` marker must reach
// the model as the user's real content, not the placeholder.
let text = self.get_expanded_text();
if let Ok(mut state) = self.state.lock() {
if !text.is_empty() {
state.history.push(text.clone());
state.history_index = state.history.len();
}
}
// Submitted text is committed — don't let Ctrl+- resurrect it.
self.undo_stack.lock().unwrap().clear();
self.redo_stack.lock().unwrap().clear();
*self.last_action.lock().unwrap() = None;
if let Ok(cb) = self.on_submit.lock() {
if let Some(callback) = cb.as_ref() {
callback(&text);
}
}
self.clear();
}
/// Notify change callback.
fn notify_change(&self) {
if let Ok(cb) = self.on_change.lock() {
if let Some(callback) = cb.as_ref() {
let text = self.get_text();
callback(&text);
}
}
}
/// Handle keyboard input.
pub fn handle_key(&self, key: crossterm::event::KeyEvent) -> bool {
match (key.modifiers, key.code) {
// Navigation — plain movement clears any active selection;
// Shift+movement extends it.
(KeyModifiers::NONE, KeyCode::Left) => {
self.clear_selection();
self.cursor_left();
}
(KeyModifiers::NONE, KeyCode::Right) => {
self.clear_selection();
self.cursor_right();
}
(KeyModifiers::NONE, KeyCode::Up) => {
self.clear_selection();
self.cursor_up();
}
(KeyModifiers::NONE, KeyCode::Down) => {
self.clear_selection();
self.cursor_down();
}
(KeyModifiers::NONE, KeyCode::Home) => {
self.clear_selection();
self.cursor_home();
}
(KeyModifiers::NONE, KeyCode::End) => {
self.clear_selection();
self.cursor_end();
}
(KeyModifiers::SHIFT, KeyCode::Left) => {
self.begin_selection();
self.cursor_left();
}
(KeyModifiers::SHIFT, KeyCode::Right) => {
self.begin_selection();
self.cursor_right();
}
(KeyModifiers::SHIFT, KeyCode::Up) => {
self.begin_selection();
self.cursor_up();
}
(KeyModifiers::SHIFT, KeyCode::Down) => {
self.begin_selection();
self.cursor_down();
}
(KeyModifiers::SHIFT, KeyCode::Home) => {
self.begin_selection();
self.cursor_home();
}
(KeyModifiers::SHIFT, KeyCode::End) => {
self.begin_selection();
self.cursor_end();
}
// Editing
(KeyModifiers::NONE, KeyCode::Backspace) => self.backspace(),
(KeyModifiers::NONE, KeyCode::Delete) => self.delete(),
(KeyModifiers::NONE, KeyCode::Enter)
| (KeyModifiers::NONE, KeyCode::Char('\n'))
| (KeyModifiers::NONE, KeyCode::Char('\r')) => {
// Submit on Enter (mirrors TS `tui.input.submit`). The
// `Char('\n')`/`Char('\r')` forms cover a client whose terminal
// hands us the codepoint directly (e.g. the kitty keyboard
// protocol's CSI-u path); they used to fall through to the
// generic char arm and insert a literal newline.
self.submit();
}
// Shift+Enter inserts a newline (mirrors `tui.input.newLine`).
(KeyModifiers::SHIFT, KeyCode::Enter) => self.insert("\n"),
// Ctrl shortcuts
(KeyModifiers::CONTROL, KeyCode::Char('a')) => self.cursor_home(),
(KeyModifiers::CONTROL, KeyCode::Char('e')) => self.cursor_end(),
(KeyModifiers::CONTROL, KeyCode::Char('k')) => {
// Kill to end of line (push the killed text onto the ring).
self.push_undo("kill");
let killed = if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let col = state.cursor_col;
let dead: String = state.lines[row].drain(col..).collect();
state.lines[row].truncate(col);
dead
} else {
String::new()
};
self.kill(killed, false);
self.notify_change();
}
(KeyModifiers::CONTROL, KeyCode::Char('u')) => {
// Kill to start of line (killed text prepends to the ring entry
// so Ctrl+Y pastes it back in the same order).
self.push_undo("kill");
let killed = if let Ok(mut state) = self.state.lock() {
let row = state.cursor_row;
let col = state.cursor_col;
let before: String = state.lines[row].drain(..col).collect();
state.cursor_col = 0;
before
} else {
String::new()
};
self.kill(killed, true);
self.notify_change();
}
// Undo / redo (pi binds undo to Ctrl+-; Ctrl+R redo is a Rust port
// convenience since pi has no redo binding).
(KeyModifiers::CONTROL, KeyCode::Char('-')) => self.undo(),
(KeyModifiers::CONTROL, KeyCode::Char('r')) => self.redo(),
// Selection cut/copy/paste (Ctrl+X / Ctrl+C / Ctrl+V).
(KeyModifiers::CONTROL, KeyCode::Char('x')) => {
self.cut_selection();
}
(KeyModifiers::CONTROL, KeyCode::Char('c')) => {
self.copy_selection();
}
(KeyModifiers::CONTROL, KeyCode::Char('v')) => {
self.yank();
}
// Kill-ring yank (Ctrl+Y) / yank-pop (Alt+Y).
(KeyModifiers::CONTROL, KeyCode::Char('y')) => self.yank(),
(KeyModifiers::ALT, KeyCode::Char('y')) => self.yank_pop(),
// Delete the word before the cursor, killing it (Alt+Backspace).
(KeyModifiers::CONTROL, KeyCode::Char('w')) => self.kill_word_backward(),
(KeyModifiers::ALT, KeyCode::Backspace) => self.kill_word_backward(),
(KeyModifiers::ALT, KeyCode::Char('d')) | (KeyModifiers::ALT, KeyCode::Delete) => {
self.kill_word_forward();
}
// Word navigation (Alt+Left / Alt+Right — pi's word-jump bindings).
(KeyModifiers::ALT, KeyCode::Left) => self.cursor_word_left(),
(KeyModifiers::ALT, KeyCode::Right) => self.cursor_word_right(),
// Ctrl+J inserts a newline (pi tui.input.newLine alongside
// Shift+Enter). Ctrl+D deletes the char forward (deleteCharForward).
(KeyModifiers::CONTROL, KeyCode::Char('j')) => self.insert_no_undo(
"
",
),
(KeyModifiers::CONTROL, KeyCode::Char('d')) => self.delete(),
// Editor page scroll (pi tui.editor.pageUp/pageDown — the
// unmodified PageUp/Down are the alt-screen transcript scroll).
(KeyModifiers::CONTROL, KeyCode::PageUp) => self.page_scroll(-1),
(KeyModifiers::CONTROL, KeyCode::PageDown) => self.page_scroll(1),
// Character jump mode (pi jumpForward/jumpBackward): Ctrl+] jumps
// forward to the next typed char, Ctrl+Alt+] backward. NB: a
// CONTROL|ALT pattern in a match arm is an or-pattern (matches
// EITHER modifier), so the backward arm uses a guard.
(_, KeyCode::Char(']')) if key.modifiers.contains(KeyModifiers::CONTROL) => {
// Ctrl+Alt+] jumps backward, Ctrl+] forward. A bare CONTROL
// arm wouldn't match the CONTROL|ALT combination.
if key.modifiers.contains(KeyModifiers::ALT) {
*self.jump_mode.lock().unwrap() = Some(-1);
} else {
*self.jump_mode.lock().unwrap() = Some(1);
}
}
// Regular character input — unless a character jump is pending
// (Ctrl+] / Ctrl+Alt+] consumed the key as the jump target).
(KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(c)) => {
let jump = self.jump_mode.lock().unwrap().take();
match jump {
Some(dir) => self.jump_to_char(c, dir),
None => self.insert(&c.to_string()),
}
}
_ => return false,
}
true
}
}
impl Component for Editor {
fn render(&self, width: usize) -> Vec<String> {
let state = self.state.lock().map(|s| s.clone()).unwrap_or_default();
let mut content_lines = Vec::new();
let pad = " ".repeat(self.options.padding_x);
// `prompt` is no longer rendered (mirrors the TS editor, which draws a
// bordered box with padding-only lines and no `> ` prefix — see
// `editor.ts:539-578`). The `EditorStyle.prompt` field is retained for
// API compatibility but unread here.
let content_width = width.saturating_sub(self.options.padding_x).max(1);
// Leave one cell for the cursor marker on the active logical line so
// the terminal never performs an implicit wrap at the right border.
let active_width = content_width.saturating_sub(1).max(1);
for (row_idx, line) in state.lines.iter().enumerate() {
let ranges = wrap_line_ranges(
line,
if row_idx == state.cursor_row {
active_width
} else {
content_width
},
);
for (chunk_start, chunk_end) in ranges {
let chunk = &line[chunk_start..chunk_end];
// Placeholder (dim) only on the single empty line at the cursor —
// honors callers that set `placeholder`; production drops it.
let content =
if chunk.is_empty() && row_idx == state.cursor_row && state.lines.len() == 1 {
if let Some(placeholder) = &self.options.placeholder {
format!("\x1b[2m{}\x1b[22m", placeholder)
} else {
String::new()
}
} else {
chunk.to_string()
};
// Selection highlight: inverse-video the span on this row (byte
// offsets are char boundaries — both anchor and caret always sit
// on one).
let mut content = content;
if let Some((sc, ec)) = self.selection_span_on_row(&state, row_idx) {
let local_start = sc.max(chunk_start).min(chunk_end);
let local_end = ec.max(chunk_start).min(chunk_end);
if local_start < local_end {
let before = &line[chunk_start..local_start];
let sel = &line[local_start..local_end];
let after = &line[local_end..chunk_end];
content = format!("{before}\x1b[7m{sel}\x1b[27m{after}");
}
}
let visible_w = crate::ansi::visible_width(&content);
// Pad the line out to the full width (left padding + content +
// right padding) so the border box has a uniform interior width
// (mirrors editor.ts:522-578).
let right_pad = " ".repeat(
width
.saturating_sub(self.options.padding_x)
.saturating_sub(visible_w),
);
let right_pad_cursor = if state.focused && row_idx == state.cursor_row {
right_pad
.get(..right_pad.len().saturating_sub(1))
.unwrap_or("")
.to_string()
} else {
right_pad
};
let mut rendered = format!("{pad}{content}{right_pad_cursor}");
// Cursor marker if this focused row holds the cursor. `cursor_col`
// is a byte offset into `line`; the rendered prefix up to the caret
// is `pad` (ASCII, `padding_x` bytes) + `line[..cursor_col]`.
// Because `content` may carry ANSI escapes (placeholder branch),
// and the prefix length is computed in *bytes* of the source line,
// snap the insertion point to the nearest preceding char boundary
// in `rendered` before byte-slicing — never slice mid-character.
if state.focused
&& row_idx == state.cursor_row
&& state.cursor_col >= chunk_start
&& state.cursor_col <= chunk_end
{
let cursor_col = UnicodeWidthStr::width(
line[chunk_start..state.cursor_col.min(chunk_end)]
.to_string()
.as_str(),
);
rendered = insert_cursor_marker(&rendered, self.options.padding_x + cursor_col);
}
content_lines.push(rendered);
}
}
// Guard against an empty `lines` vector (the invariant is `[""]`, but
// be defensive): emit one blank interior row so the box still renders.
if content_lines.is_empty() {
content_lines.push(format!(
"{pad}{}",
" ".repeat(width.saturating_sub(self.options.padding_x))
));
}
// Full-width top + bottom border, colored via the theme border color
// (mirrors editor.ts:494,530,587). The global `theme()` is read-only
// after OnceLock init; `Color::fg` wraps the `─` run in the escape.
// An explicit `border_color` (bash mode) wins over the theme default.
let border_color = self
.border_color
.lock()
.ok()
.and_then(|guard| *guard)
.unwrap_or(crate::theme::theme().colors.border);
// Check if we have a working state to display in the top border.
//
// The frame advances once per render, mirroring `Loader::render`: the
// spinner is therefore driven by *repaints*, so it visibly speeds up
// while the model is streaming (each token schedules a frame) and falls
// back to the render tick's cadence when nothing is being produced. A
// timer-only animation looked constant-speed and unrelated to output.
let working_state = self.working.lock().ok().and_then(|mut guard| {
guard.as_mut().map(|state| {
let snapshot = state.clone();
state.frame = state.frame.wrapping_add(1);
snapshot
})
});
let top_border = if let Some(ref working) = working_state {
// Working indicator embedded in the top border: spinner + message +
// elapsed time, with the remaining width filled by border glyphs.
// The frame set is shared with `Loader` so the two never drift.
let frames = crate::loader::SPINNER_FRAMES;
let spinner_char = frames[working.frame % frames.len()];
let colors = crate::theme::theme().colors;
let elapsed = working.started_at.elapsed();
let elapsed_str = if elapsed.as_secs() >= 60 {
format!("{}m{}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
} else {
format!("{}s", elapsed.as_secs())
};
let plain = format!(" {} {} {} ", spinner_char, working.message, elapsed_str);
let indicator_width = crate::ansi::visible_width(&plain);
if width >= indicator_width + 1 {
let colored = format!(
" {} {} {} ",
colors.accent.fg(&spinner_char.to_string()),
colors.muted.fg(&working.message),
colors.muted.fg(&elapsed_str),
);
let right = border_color.fg(&"─".repeat(width - indicator_width - 1));
format!("{}{}{}", border_color.fg("─"), colored, right)
} else {
border_color.fg(&"─".repeat(width))
}
} else {
border_color.fg(&"─".repeat(width))
};
let bottom_border = {
let horizontal = "─".repeat(width);
border_color.fg(&horizontal)
};
let mut lines = Vec::with_capacity(content_lines.len() + 2);
lines.push(top_border);
lines.extend(content_lines);
lines.push(bottom_border);
lines
}
fn invalidate(&self) {
// Editor doesn't have external cache
}
fn handle_input(&self, _data: &str) -> bool {
// Parse key event from crossterm format
// This is a simplified version - in real usage, you'd receive KeyEvent directly
false
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Focusable for Editor {
fn set_focused(&self, focused: bool) {
if let Ok(mut state) = self.state.lock() {
state.focused = focused;
}
}
fn is_focused(&self) -> bool {
self.state.lock().map(|s| s.focused).unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn working_spinner_advances_per_render_not_per_timer() {
use crate::component::Component;
let editor = Editor::simple();
editor.set_working(Some(WorkingState {
frame: 0,
started_at: std::time::Instant::now(),
message: "Working…".to_string(),
}));
// The indicator lives in the top border and reports the message.
let first = crate::strip_ansi(&editor.render(60)[0]);
assert!(first.contains("Working"), "top border: {first}");
// Each render steps the frame, so repaints driven by streamed output
// visibly advance the spinner; no timer is required for that.
let frame_after_first = editor.working().expect("working state").frame;
assert_eq!(frame_after_first, 1, "render must advance the frame once");
let _ = editor.render(60);
assert_eq!(editor.working().expect("working state").frame, 2);
// Two renders of the same state differ on screen (spinner char moves).
let a = crate::strip_ansi(&editor.render(60)[0]);
let b = crate::strip_ansi(&editor.render(60)[0]);
let spinner_of = |line: &str| line.chars().find(|c| "⠋⠘⠹⠸⠼⠴⠦⠧⠇⠏".contains(*c));
assert_ne!(
spinner_of(&a),
spinner_of(&b),
"consecutive renders must show different spinner frames: {a:?} vs {b:?}"
);
// Idle editors have no indicator.
editor.set_working(None);
let idle = crate::strip_ansi(&editor.render(60)[0]);
assert!(!idle.contains("Working"), "idle border: {idle}");
}
#[test]
fn working_spinner_uses_native_pi_frames_and_cadence() {
// The editor used to hand-copy the frame list and drifted (`⠘` where
// native pi has `⠙`), so the two indicators animated differently. Both
// now share `SPINNER_FRAMES`.
assert_eq!(crate::loader::SPINNER_FRAMES.len(), 10);
assert_eq!(
crate::loader::SPINNER_FRAMES.iter().collect::<String>(),
"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
);
// 10 frames at 80ms = the 800ms full cycle native pi animates at.
assert_eq!(crate::loader::SPINNER_FRAME_MS, 80);
// The rendered indicator steps through exactly that list, in order.
use crate::component::Component;
let editor = Editor::simple();
editor.set_working(Some(WorkingState {
frame: 0,
started_at: std::time::Instant::now(),
message: "Working…".to_string(),
}));
let spinner_of = |line: &str| {
let plain = crate::strip_ansi(line);
crate::loader::SPINNER_FRAMES
.iter()
.copied()
.find(|c| plain.contains(*c))
};
let mut seen = Vec::new();
for _ in 0..10 {
seen.push(spinner_of(&editor.render(60)[0]).expect("a spinner glyph"));
}
// The snapshot is taken before the advance, so the first paint shows
// frame 0 — exactly native pi, whose `start()` paints frame 0 and then
// steps on each interval. Ten paints therefore cover the whole cycle in
// order and wrap back to the start.
let expected: Vec<char> = crate::loader::SPINNER_FRAMES.to_vec();
assert_eq!(seen, expected);
assert_eq!(
editor.working().expect("working").frame % crate::loader::SPINNER_FRAMES.len(),
0,
"ten paints must land back on the first frame"
);
}
#[test]
fn idle_cadence_matches_native_pi() {
// One frame per `SPINNER_FRAME_MS` of wall clock when nothing else is
// repainting. This is the property the tick task relies on: it only
// requests a repaint, and the repaint advances exactly one frame. The
// tick used to *also* advance the frame, which made the idle spinner
// run at 40ms/frame — twice native pi's rate.
use crate::component::Component;
assert_eq!(crate::loader::SPINNER_FRAME_MS, 80);
assert_eq!(
crate::loader::SPINNER_FRAME_MS * crate::loader::SPINNER_FRAMES.len() as u64,
800,
"a full cycle should take 800ms, like native pi"
);
let editor = Editor::simple();
editor.set_working(Some(WorkingState {
frame: 0,
started_at: std::time::Instant::now(),
message: "Working…".to_string(),
}));
// One repaint == one frame, i.e. one tick advances the spinner once.
let before = editor.working().expect("working").frame;
let _ = editor.render(60);
assert_eq!(editor.working().expect("working").frame, before + 1);
}
#[test]
fn explicit_border_color_overrides_the_theme_border() {
use crate::component::Component;
let editor = Editor::simple();
editor.set_focused(true);
editor.insert("echo hi");
let default_border = crate::theme::theme().colors.border.fg(&"─".repeat(20));
assert!(editor.render(20).contains(&default_border));
assert_eq!(editor.border_color(), None);
// Bash mode sets an explicit accent; the border line changes and the
// theme default is gone.
editor.set_border_color(Some(crate::theme::theme().colors.bash_mode));
let bash_border = crate::theme::theme().colors.bash_mode.fg(&"─".repeat(20));
assert_eq!(
editor.border_color(),
Some(crate::theme::theme().colors.bash_mode)
);
let rendered = editor.render(20);
assert!(rendered.contains(&bash_border), "{rendered:?}");
assert!(!rendered.contains(&default_border));
// Clearing restores the theme default (what `updateEditorBorderColor`
// does once the draft no longer starts with `!`).
editor.set_border_color(None);
assert!(editor.render(20).contains(&default_border));
}
#[test]
fn clear_and_set_text_notify_change_observers() {
// Native pi's `setTextInternal` fires onChange for programmatic edits;
// the bash-mode border and autocomplete rely on it to drop stale state.
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let calls_cb = calls.clone();
let editor = Editor::simple();
editor.on_change(Arc::new(move |_text: &str| {
calls_cb.fetch_add(1, Ordering::SeqCst);
}));
editor.set_text("!ls");
assert_eq!(calls.load(Ordering::SeqCst), 1);
editor.clear();
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[test]
fn snap_boundary_keeps_char_boundaries_including_end() {
// The regression: a caret placed exactly at the END of the text (what
// autocomplete accept does — `set_cursor(0, text.len())`) used to snap
// one char EARLY, rendering "/mode|l" instead of "/model|".
assert_eq!(snap_boundary("/mo", 3), 3);
assert_eq!(snap_boundary("/model", 6), 6);
assert_eq!(snap_boundary("hello", 5), 5);
// Interior boundaries are kept as-is.
assert_eq!(snap_boundary("/model", 0), 0);
assert_eq!(snap_boundary("/model", 2), 2);
// Out-of-range clamps to the end (a valid boundary).
assert_eq!(snap_boundary("/mo", 99), 3);
}
#[test]
fn snap_boundary_mid_multibyte_snaps_down_to_char_start() {
// "你" occupies bytes 0..3: a position inside it must snap to 0.
assert_eq!(snap_boundary("你", 1), 0);
assert_eq!(snap_boundary("你", 2), 0);
// Position after it (end of string) stays 3.
assert_eq!(snap_boundary("你", 3), 3);
// Mixed: "a你b" — 你 is bytes 1..4; end of string is 5.
assert_eq!(snap_boundary("a你b", 5), 5);
assert_eq!(snap_boundary("a你b", 2), 1);
}
#[test]
fn left_arrow_keeps_text_in_render() {
use crate::component::Component;
use crossterm::event::{KeyCode, KeyModifiers};
let mk = |m, c| crossterm::event::KeyEvent::new(c, m);
let editor = Editor::simple();
editor.set_focused(true);
editor.insert("hello world");
editor.handle_key(mk(KeyModifiers::NONE, KeyCode::Left));
let rendered = editor.render(40).join(
"
",
);
assert!(
rendered.contains("hello"),
"text must survive Left, got: {rendered:?}"
);
}
#[test]
fn test_char_jump_and_page_scroll() {
use crossterm::event::{KeyCode, KeyModifiers};
let mk = |m, c| crossterm::event::KeyEvent::new(c, m);
let editor = Editor::simple();
// Character jump: from the end, Ctrl+Alt+] then 'x' jumps backward to
// the previous 'x' ("alpha xray xray" — the second "xray" starts at 11).
editor.insert("alpha xray xray");
editor.handle_key(mk(KeyModifiers::CONTROL | KeyModifiers::ALT, KeyCode::End)); // caret at end
editor.handle_key(mk(
KeyModifiers::CONTROL | KeyModifiers::ALT,
KeyCode::Char(']'),
));
// The next printable char is consumed as the jump target.
editor.handle_key(mk(KeyModifiers::NONE, KeyCode::Char('x')));
assert_eq!(editor.cursor_position(), (0, 11));
// Page scroll on a multi-line buffer clamps to the last row.
editor.set_text(
"l0
l1
l2
l3
l4
l5
l6
l7
l8
l9
l10
l11
l12",
);
editor.set_cursor(0, 2);
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::PageDown));
let (row, _) = editor.cursor_position();
assert!(row >= 10, "page-down moves ~10 rows, got {row}");
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::PageUp));
let (row2, _) = editor.cursor_position();
assert!(row2 <= 2, "page-up returns near the start, got {row2}");
}
#[test]
fn test_word_ops_and_new_keys() {
use crossterm::event::{KeyCode, KeyModifiers};
let mk = |m, c| crossterm::event::KeyEvent::new(c, m);
let editor = Editor::simple();
editor.insert("alpha beta gamma");
// Ctrl+W kills the word before the cursor.
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::End));
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::Char('w')));
assert_eq!(editor.get_text(), "alpha beta ");
// Alt+Left jumps back a word; Alt+D kills the word after.
editor.handle_key(mk(KeyModifiers::ALT, KeyCode::Left));
assert_eq!(editor.cursor_position(), (0, 6));
editor.handle_key(mk(KeyModifiers::ALT, KeyCode::Char('d')));
assert_eq!(editor.get_text(), "alpha ");
// Ctrl+J inserts a newline.
editor.set_text("a");
editor.set_cursor(0, 1);
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::Char('j')));
assert_eq!(
editor.get_text(),
"a
"
);
// Ctrl+D deletes the char forward (deleteCharForward).
editor.set_text("abc");
editor.set_cursor(0, 1);
editor.handle_key(mk(KeyModifiers::CONTROL, KeyCode::Char('d')));
assert_eq!(editor.get_text(), "ac");
}
#[test]
fn test_selection_cut_copy_paste() {
let editor = Editor::simple();
editor.insert("hello world");
// Caret to the start, then Shift+Right ×5 selects "hello".
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Home,
crossterm::event::KeyModifiers::NONE,
));
let shift_right = || {
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Right,
crossterm::event::KeyModifiers::SHIFT,
))
};
for _ in 0..5 {
shift_right();
}
assert!(editor.has_selection());
assert_eq!(editor.selected_text().as_deref(), Some("hello"));
// Ctrl+C copies (selection intact), then plain Right clears it.
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('c'),
crossterm::event::KeyModifiers::CONTROL,
));
assert_eq!(editor.get_text(), "hello world");
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Right,
crossterm::event::KeyModifiers::NONE,
));
assert!(!editor.has_selection(), "plain movement clears selection");
// Move to the end and yank the copied text.
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::End,
crossterm::event::KeyModifiers::NONE,
));
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('v'),
crossterm::event::KeyModifiers::CONTROL,
));
assert_eq!(editor.get_text(), "hello worldhello");
}
#[test]
fn test_selection_replace_and_cut() {
let editor = Editor::simple();
editor.insert("abcdef");
// Caret to the start, then Shift+Right ×4 selects "abcd".
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Home,
crossterm::event::KeyModifiers::NONE,
));
for _ in 0..4 {
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Right,
crossterm::event::KeyModifiers::SHIFT,
));
}
// Backspace deletes the selection ("abcd" → "ef").
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Backspace,
crossterm::event::KeyModifiers::NONE,
));
assert_eq!(editor.get_text(), "ef", "backspace deletes the selection");
// Undo restores it.
editor.undo();
assert_eq!(editor.get_text(), "abcdef");
// Cut: return to the start, select "ab", Ctrl+X removes + kills it.
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Home,
crossterm::event::KeyModifiers::NONE,
));
for _ in 0..2 {
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Right,
crossterm::event::KeyModifiers::SHIFT,
));
}
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('x'),
crossterm::event::KeyModifiers::CONTROL,
));
assert_eq!(editor.get_text(), "cdef");
// Type over a selection replaces it.
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Right,
crossterm::event::KeyModifiers::SHIFT,
));
editor.insert("Z");
assert_eq!(editor.get_text(), "Zdef", "typing replaces the selection");
}
#[test]
fn test_undo_redo_roundtrip() {
let editor = Editor::simple();
editor.insert("hello");
editor.insert(" world");
// Consecutive inserts coalesce: one undo restores the empty state.
assert_eq!(editor.get_text(), "hello world");
editor.undo();
assert_eq!(editor.get_text(), "", "coalesced inserts undo as one step");
// Redo restores everything.
editor.redo();
assert_eq!(editor.get_text(), "hello world");
// A fresh edit after undo clears redo.
editor.undo();
editor.insert("hi");
editor.redo();
assert_eq!(editor.get_text(), "hi", "new edit clears the redo stack");
}
#[test]
fn test_kill_ring_yank() {
let editor = Editor::simple();
editor.insert("alpha beta gamma");
// Ctrl+K kills to end of line.
editor.set_cursor(0, 6); // after "alpha "
let key = |m, c| crossterm::event::KeyEvent::new(c, m);
editor.handle_key(key(
crossterm::event::KeyModifiers::CONTROL,
crossterm::event::KeyCode::Char('k'),
));
assert_eq!(editor.get_text(), "alpha ");
// Ctrl+Y yanks it back.
editor.handle_key(key(
crossterm::event::KeyModifiers::CONTROL,
crossterm::event::KeyCode::Char('y'),
));
assert_eq!(editor.get_text(), "alpha beta gamma");
}
#[test]
fn test_undo_after_kill() {
let editor = Editor::simple();
editor.insert("hello world");
editor.set_cursor(0, 5);
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('k'),
crossterm::event::KeyModifiers::CONTROL,
));
assert_eq!(editor.get_text(), "hello");
editor.undo();
assert_eq!(editor.get_text(), "hello world", "kill is undoable");
}
#[test]
fn test_submit_clears_undo() {
let editor = Editor::simple();
editor.insert("committed");
editor.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Enter,
crossterm::event::KeyModifiers::NONE,
));
editor.undo();
assert_eq!(
editor.get_text(),
"",
"submit clears undo so committed text stays committed"
);
}
/// Regression: a remote/mobile client (SSH, soft keyboard) that encodes
/// its Enter key as LF (0x0A) or CR (0x0D) sends it as a bare character
/// event in raw mode. Those used to fall through to the generic char arm
/// and insert a literal newline — "回车变成了换行,无法发送内容". They must
/// submit just like `KeyCode::Enter`.
#[test]
fn test_remote_lf_cr_enter_submits() {
use std::sync::atomic::{AtomicUsize, Ordering};
for code in [
crossterm::event::KeyCode::Char('\n'),
crossterm::event::KeyCode::Char('\r'),
] {
let editor = Editor::simple();
let submits = Arc::new(AtomicUsize::new(0));
let submits_for_cb = submits.clone();
editor.on_submit(Arc::new(move |_text: &str| {
submits_for_cb.fetch_add(1, Ordering::SeqCst);
}));
editor.insert("hello");
editor.handle_key(crossterm::event::KeyEvent::new(
code,
crossterm::event::KeyModifiers::NONE,
));
assert_eq!(submits.load(Ordering::SeqCst), 1, "{code:?} must submit");
assert_eq!(editor.get_text(), "", "editor cleared after submit");
}
}
#[test]
fn test_editor_text() {
let editor = Editor::simple();
editor.set_text("Hello");
assert_eq!(editor.get_text(), "Hello");
}
#[test]
fn test_editor_insert() {
let editor = Editor::simple();
editor.insert("Hello");
assert_eq!(editor.get_text(), "Hello");
editor.insert(" World");
assert_eq!(editor.get_text(), "Hello World");
}
#[test]
fn test_editor_clear() {
let editor = Editor::simple();
editor.set_text("Test");
editor.clear();
assert_eq!(editor.get_text(), "");
}
#[test]
fn test_editor_render_has_borders() {
// The editor renders a native-pi bordered box: a full-width `─` line
// above and below the content, with no `> ` prompt prefix on the text
// lines (mirrors TS editor.ts:525-588).
let editor = Editor::new(
EditorOptions {
padding_x: 1,
..Default::default()
},
EditorStyle::default(),
Arc::new(Keybindings::new()),
);
editor.set_text("hi");
let lines = editor.render(20);
assert_eq!(lines.len(), 3, "expected [border, content, border]");
// Both borders are a 20-wide `─` run (visible width, ANSI stripped).
let top = crate::ansi::strip_ansi(&lines[0]);
let bottom = crate::ansi::strip_ansi(lines.last().unwrap());
assert_eq!(
top.chars().filter(|c| *c == '─').count(),
20,
"top border not full width: {top:?}"
);
assert_eq!(
bottom.chars().filter(|c| *c == '─').count(),
20,
"bottom border not full width: {bottom:?}"
);
// The content line carries the text with no `> ` prompt.
let content = crate::ansi::strip_ansi(&lines[1]);
assert!(
content.contains("hi"),
"content line missing text: {content:?}"
);
assert!(
!content.contains("> "),
"content line should not have a prompt prefix: {content:?}"
);
}
#[test]
fn test_editor_multibyte_no_panic() {
// Inserting a multibyte char (读 = 3 bytes) and then a second char
// used to panic: `cursor_col += 1` left the caret at byte 1, inside
// '读', so the next `String::insert(1, …)` hit a char boundary. This
// exercises the byte-cursor fix across insert + render + a second
// keystroke.
let editor = Editor::simple();
editor.set_focused(true);
editor.insert("读");
editor.insert("a");
editor.insert("书");
assert_eq!(editor.get_text(), "读a书");
// cursor_col should be at the end (byte offset 7: 读=3 + a=1 + 书=3).
assert_eq!(editor.cursor_position(), (0, 7));
// Render must not panic when placing the cursor marker on the row.
let lines = editor.render(20);
assert_eq!(
lines.len(),
3,
"bordered box keeps [border, content, border]"
);
// Backspace / left/right must also stay on boundaries.
editor.backspace(); // remove 书
assert_eq!(editor.get_text(), "读a");
editor.cursor_left(); // left of 'a'
assert_eq!(editor.cursor_position(), (0, 3));
editor.insert("b"); // insert between 读 and a
assert_eq!(editor.get_text(), "读ba");
}
#[test]
fn test_editor_wraps_long_draft_inside_width() {
let editor = Editor::new(
EditorOptions {
padding_x: 1,
..Default::default()
},
EditorStyle::default(),
Arc::new(Keybindings::new()),
);
editor.set_focused(true);
editor.set_text("12345678901234567890");
let lines = editor.render(10);
assert_eq!(lines.len(), 5, "two wrapped content rows plus borders");
for line in &lines {
assert!(
crate::ansi::visible_width(line) <= 10,
"line escaped editor width: {line:?}"
);
}
let rendered = crate::ansi::strip_ansi(&lines.join("\n"));
assert!(rendered.contains("1234567"));
assert!(rendered.contains("90123456"));
}
#[test]
fn test_editor_preserves_trailing_newline() {
let editor = Editor::simple();
editor.set_text("first\n");
assert_eq!(editor.get_text(), "first\n");
assert_eq!(editor.cursor_position(), (0, 0));
}
#[test]
fn test_autocomplete_cursor_origin() {
// Origin of the autocomplete panic (autocomplete.rs:279, before the
// fix): the editor handed back a byte `cursor_col` for multibyte
// text, and the slash-command provider sliced `&input[..cursor]`
// mid-character. A multibyte editor line must still round-trip
// through `get_suggestions` without panicking.
use crate::autocomplete::AutocompleteManager;
let editor = Editor::simple();
editor.set_text("读");
editor.set_cursor(0, 3); // byte end of line
let text = editor.get_text();
let (_r, col) = editor.cursor_position();
let cursor = col.min(text.len());
let mgr = AutocompleteManager::new();
// No slash prefix → None; must not panic on the multibyte slice.
assert!(mgr.get_suggestions(&text, cursor).is_none());
// And the slash path with a char-count overshoot also must not panic.
editor.set_text("/读");
editor.set_cursor(0, 4);
let text2 = editor.get_text();
let mgr2 = AutocompleteManager::new();
let _ = mgr2.get_suggestions(&text2, 9); // overshoot past end
}
#[test]
fn insert_normalizes_crlf_and_lone_cr_to_newlines() {
// Pasted Windows text (and the Unix `Event::Paste` payload, which keeps
// CRLF) used to insert literal `\r` bytes into the line buffer: they
// render as garbage and desync `cursor_col` from the string length.
let editor = Editor::simple();
editor.insert("line1\r\nline2\rline3");
assert_eq!(editor.get_text(), "line1\nline2\nline3");
// The buffer is 3 lines and the cursor sits at the end of the last.
let (row, col) = editor.cursor_position();
assert_eq!((row, col), (2, "line3".len()));
// Editing after a normalized paste stays sound (no mid-char split).
editor.insert("!");
assert_eq!(editor.get_text(), "line1\nline2\nline3!");
}
#[test]
fn insert_of_a_lone_crlf_makes_exactly_one_newline() {
let editor = Editor::simple();
editor.insert("a\r\nb");
assert_eq!(editor.get_text().matches('\n').count(), 1);
assert_eq!(editor.get_text(), "a\nb");
}
// ---- Folded pastes (native pi `handlePaste` / `expandPasteMarkers`) ----
#[test]
fn short_paste_is_inserted_verbatim() {
let editor = Editor::simple();
editor.handle_paste("hello\nworld\nthird");
assert_eq!(editor.get_text(), "hello\nworld\nthird");
assert_eq!(editor.get_expanded_text(), "hello\nworld\nthird");
}
#[test]
fn many_line_paste_folds_to_a_marker() {
let editor = Editor::simple();
let payload = (1..=12)
.map(|i| format!("line {i}"))
.collect::<Vec<_>>()
.join("\n");
editor.handle_paste(&payload);
// The document shows only the marker; the body is stashed.
assert_eq!(editor.get_text(), "[paste #1 +12 lines]");
// Submitting reveals the real content.
assert_eq!(editor.get_expanded_text(), payload);
}
#[test]
fn long_single_line_paste_folds_by_char_count() {
let editor = Editor::simple();
let payload = "x".repeat(2000);
editor.handle_paste(&payload);
assert_eq!(editor.get_text(), "[paste #1 2000 chars]");
assert_eq!(editor.get_expanded_text(), payload);
}
#[test]
fn pasted_crlf_and_tabs_are_normalized_before_folding() {
let editor = Editor::simple();
let payload = (1..=12)
.map(|i| format!("a\tb{i}"))
.collect::<Vec<_>>()
.join("\r\n");
editor.handle_paste(&payload);
let expanded = editor.get_expanded_text();
assert!(!expanded.contains('\r'), "CR must be normalized away");
assert!(!expanded.contains('\t'), "tab must expand to spaces");
assert!(expanded.contains("a b1"), "tab becomes four spaces");
assert_eq!(expanded.split('\n').count(), 12);
}
#[test]
fn two_folded_pastes_get_distinct_ids_and_both_expand() {
let editor = Editor::simple();
let first = "1\n".repeat(11);
let second = "2\n".repeat(11);
editor.handle_paste(&first);
editor.handle_paste(&second);
assert_eq!(
editor.get_text(),
"[paste #1 +12 lines][paste #2 +12 lines]"
);
assert_eq!(editor.get_expanded_text(), format!("{first}{second}"));
}
#[test]
fn backspace_over_a_folded_marker_drops_it_and_renumbers() {
let editor = Editor::simple();
let first = "a\n".repeat(11);
let second = "b\n".repeat(11);
editor.handle_paste(&first);
editor.handle_paste(&second);
assert_eq!(
editor.get_text(),
"[paste #1 +12 lines][paste #2 +12 lines]"
);
// Delete the FIRST marker: one step left lands the caret right after
// marker #1 (markers are adjacent), and Backspace eats it whole.
let _ = editor.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Left,
KeyModifiers::NONE,
));
let _ = editor.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Backspace,
KeyModifiers::NONE,
));
// Only the second survives, renumbered to #1, and it still expands.
assert_eq!(editor.get_text(), "[paste #1 +12 lines]");
assert_eq!(editor.get_expanded_text(), second);
}
#[test]
fn undo_restores_a_backspaced_folded_paste() {
let editor = Editor::simple();
let payload = "line\n".repeat(11);
editor.handle_paste(&payload);
assert_eq!(editor.get_text(), "[paste #1 +12 lines]");
let _ = editor.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Backspace,
KeyModifiers::NONE,
));
assert_eq!(editor.get_text(), "", "marker deleted");
// Undo must resurrect both the marker AND its stashed body.
editor.undo();
assert_eq!(editor.get_text(), "[paste #1 +12 lines]");
assert_eq!(editor.get_expanded_text(), payload);
}
#[test]
fn cursor_arrows_step_over_a_marker_atomically() {
let editor = Editor::simple();
let payload = "z\n".repeat(11);
editor.handle_paste(&payload);
// Caret is after the marker; one step left must land BEFORE it.
let _ = editor.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Left,
KeyModifiers::NONE,
));
assert_eq!(
editor.cursor_position(),
(0, 0),
"left jumps the whole marker"
);
// And one step right must jump back over the whole marker.
let _ = editor.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Right,
KeyModifiers::NONE,
));
assert_eq!(
editor.cursor_position(),
(0, "[paste #1 +12 lines]".len()),
"right jumps the whole marker"
);
}
#[test]
fn clear_and_set_text_forget_folded_pastes() {
let editor = Editor::simple();
editor.handle_paste(&"m\n".repeat(11));
editor.clear();
assert_eq!(editor.get_text(), "");
assert_eq!(editor.get_expanded_text(), "");
editor.handle_paste(&"n\n".repeat(11));
editor.set_text("fresh");
// A programmatic replacement drops the store; a leftover marker would
// otherwise expand against a stale body.
assert_eq!(editor.get_text(), "fresh");
assert_eq!(editor.get_expanded_text(), "fresh");
}
#[test]
fn csi_u_ctrl_sequences_decode_then_drop_like_native_pi() {
// `ESC[104;5u` is kitty CSI-u for Ctrl+H. Native pi decodes it to the
// control char (104 - 96 = 8) and then its `charCode >= 32` filter
// drops it, so a stream of them folds to nothing.
let editor = Editor::simple();
editor.handle_paste(&"\x1b[104;5u".repeat(1200));
assert_eq!(editor.get_text(), "");
assert_eq!(editor.get_expanded_text(), "");
}
}