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
use anyhow::Result;
use crossterm::{
cursor::SetCursorStyle,
event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
execute,
};
use hjkl_engine::{CursorShape, Host, VimMode};
use hjkl_keymap::{Chord as KmChord, KeyEvent as KmKeyEvent};
use ratatui::{Terminal, backend::CrosstermBackend};
use std::io::Stdout;
use std::time::Duration;
use super::{App, STATUS_LINE_HEIGHT, prompt_cursor_shape};
use crate::render;
/// How long the mouse must rest on a Code zone before the LSP hover RPC fires.
const HOVER_DELAY: Duration = Duration::from_millis(500);
/// Outcome returned by [`App::handle_keypress`].
pub(crate) enum KeyOutcome {
/// Continue the event loop (equivalent to `continue`).
Continue,
/// Break out of the event loop (equivalent to `break`).
Break,
/// Key was not consumed by any overlay/prefix handler; fall through to
/// the engine (Insert or Normal/Visual via hjkl_vim_tui::handle_key).
FallThrough,
}
/// Outcome returned by [`App::handle_mouse`].
pub(crate) enum MouseOutcome {
/// Continue the event loop.
Continue,
/// Fall through (no explicit `continue` needed but loop iterates).
FallThrough,
}
/// Translate a crossterm `KeyEvent` to a `hjkl_keymap::KeyEvent`.
/// Returns `None` for release events or unsupported key codes.
fn to_km_event(key: KeyEvent) -> Option<KmKeyEvent> {
crate::keymap_translate::from_crossterm(&key)
}
/// Replay a slice of `hjkl_keymap::KeyEvent`s to the engine via crossterm
/// `KeyEvent`s. Thin wrapper delegating to `App::replay_to_engine`; kept
/// for callers inside this file that pass `app` as a plain `&mut App` arg.
fn replay_to_engine(app: &mut App, events: &[KmKeyEvent]) {
app.replay_to_engine(events);
}
/// Map a [`hjkl_vim::OperatorKind`] (reducer-side) to a
/// [`hjkl_engine::Operator`] (engine-side). All nine reducer-side operators
/// have a corresponding engine variant.
pub(crate) fn op_kind_to_operator(k: hjkl_vim::OperatorKind) -> hjkl_engine::Operator {
match k {
hjkl_vim::OperatorKind::Delete => hjkl_engine::Operator::Delete,
hjkl_vim::OperatorKind::Yank => hjkl_engine::Operator::Yank,
hjkl_vim::OperatorKind::Change => hjkl_engine::Operator::Change,
hjkl_vim::OperatorKind::Indent => hjkl_engine::Operator::Indent,
hjkl_vim::OperatorKind::Outdent => hjkl_engine::Operator::Outdent,
hjkl_vim::OperatorKind::Uppercase => hjkl_engine::Operator::Uppercase,
hjkl_vim::OperatorKind::Lowercase => hjkl_engine::Operator::Lowercase,
hjkl_vim::OperatorKind::ToggleCase => hjkl_engine::Operator::ToggleCase,
hjkl_vim::OperatorKind::Reflow => hjkl_engine::Operator::Reflow,
hjkl_vim::OperatorKind::ReflowKeepCursor => hjkl_engine::Operator::ReflowKeepCursor,
hjkl_vim::OperatorKind::AutoIndent => hjkl_engine::Operator::AutoIndent,
hjkl_vim::OperatorKind::Filter => hjkl_engine::Operator::Filter,
hjkl_vim::OperatorKind::Comment => hjkl_engine::Operator::Comment,
}
}
impl App {
/// Insert-mode key dispatcher. Calls `Editor::insert_*` primitives
/// directly, bypassing the engine FSM for Insert-mode keys.
///
/// This is called from the main event loop whenever the editor is in
/// `VimMode::Insert` and the key has not been consumed by an overlay
/// (completion popup, etc.). Normal / Visual modes still route through
/// `hjkl_vim_tui::handle_key`.
///
/// ### `Ctrl-R {reg}` — register paste
/// `insert_ctrl_r_arm()` sets an internal flag (`insert_pending_register`).
/// The NEXT printable character names the register; we detect this via
/// `editor.is_insert_register_pending()` and call
/// `insert_paste_register(c)` instead of `insert_char(c)`.
///
/// ### `Ctrl-O` — one-shot normal
/// `insert_ctrl_o_arm()` flips `vim.mode` to Normal (and syncs
/// `current_mode`). The NEXT key therefore reads `vim_mode() == Normal`
/// and is dispatched as a Normal-mode key naturally — no extra flag needed
/// here. After that single normal command the engine's end-of-step hook
/// flips back to Insert.
pub(crate) fn dispatch_insert_key(&mut self, key: KeyEvent) {
use crossterm::event::{KeyCode, KeyModifiers};
use hjkl_engine::InsertDir;
// Macro recording for keys that reach this dispatcher happens upstream
// in `handle_keypress`'s Insert-mode block (the single hook there
// covers consume-and-return Continue paths AND fall-through paths so
// we don't double-record). Don't add a hook here.
// `Ctrl-R` two-key sequence: the previous key armed the register
// selector. The next printable char names the register to paste.
// Any non-printable key cancels (mirrors vim behaviour).
if self.active_editor().is_insert_register_pending() {
// Clear the flag first (mirrors step_insert which clears before
// calling insert_paste_register_bridge).
self.active_editor_mut().clear_insert_register_pending();
if let (KeyCode::Char(c), mods) = (key.code, key.modifiers)
&& !mods.contains(KeyModifiers::CONTROL)
{
self.active_editor_mut().insert_paste_register(c);
}
// Non-char key: flag already cleared; just drop the key.
return;
}
match (key.code, key.modifiers) {
// Printable characters (including shifted variants like 'A', '!', …).
// Crossterm sets SHIFT for capital letters but the char `c` already
// contains the upper-cased glyph, so we just forward `c` directly.
(KeyCode::Char(c), mods)
if mods == KeyModifiers::NONE || mods == KeyModifiers::SHIFT =>
{
self.active_editor_mut().insert_char(c);
}
// Navigation / editing keys
(KeyCode::Backspace, _) => self.active_editor_mut().insert_backspace(),
(KeyCode::Enter, _) => self.active_editor_mut().insert_newline(),
(KeyCode::Tab, _) => self.active_editor_mut().insert_tab(),
(KeyCode::Esc, _) => self.active_editor_mut().leave_insert_to_normal(),
(KeyCode::Delete, _) => self.active_editor_mut().insert_delete(),
(KeyCode::Home, _) => self.active_editor_mut().insert_home(),
(KeyCode::End, _) => self.active_editor_mut().insert_end(),
// Arrow keys
(KeyCode::Left, _) => self.active_editor_mut().insert_arrow(InsertDir::Left),
(KeyCode::Right, _) => self.active_editor_mut().insert_arrow(InsertDir::Right),
(KeyCode::Up, _) => self.active_editor_mut().insert_arrow(InsertDir::Up),
(KeyCode::Down, _) => self.active_editor_mut().insert_arrow(InsertDir::Down),
// Page keys — need the current viewport height.
(KeyCode::PageUp, _) => {
let h = self.active_editor().viewport_height_value();
self.active_editor_mut().insert_pageup(h);
}
(KeyCode::PageDown, _) => {
let h = self.active_editor().viewport_height_value();
self.active_editor_mut().insert_pagedown(h);
}
// Ctrl-prefixed insert shortcuts
(KeyCode::Char('w'), KeyModifiers::CONTROL) => self.active_editor_mut().insert_ctrl_w(),
(KeyCode::Char('u'), KeyModifiers::CONTROL) => self.active_editor_mut().insert_ctrl_u(),
(KeyCode::Char('h'), KeyModifiers::CONTROL) => self.active_editor_mut().insert_ctrl_h(),
// `Ctrl-O`: flip to one-shot Normal; the next key routes as Normal.
(KeyCode::Char('o'), KeyModifiers::CONTROL) => {
self.active_editor_mut().insert_ctrl_o_arm()
}
// `Ctrl-R`: arm register selector; next char calls insert_paste_register.
(KeyCode::Char('r'), KeyModifiers::CONTROL) => {
self.active_editor_mut().insert_ctrl_r_arm()
}
(KeyCode::Char('t'), KeyModifiers::CONTROL) => self.active_editor_mut().insert_ctrl_t(),
(KeyCode::Char('d'), KeyModifiers::CONTROL) => self.active_editor_mut().insert_ctrl_d(),
// Silently drop unrecognised keys (function keys, Alt combos, etc.).
_ => {}
}
}
/// Handle a terminal bracketed-paste (`Event::Paste`) — the whole pasted
/// blob arrives as one atomic string with real newlines.
///
/// Insert mode inserts the text verbatim at the cursor: `insert_str` splits
/// embedded `\n` into lines and applies **no** autoindent, which is correct
/// paste behaviour (no cascading-indent like `:set paste`). CRLF/CR are
/// normalised to LF so Windows-clipboard line endings split lines too.
///
/// In any non-Insert mode the paste is dropped: feeding pasted bytes to the
/// Normal-mode FSM would interpret them as commands, which is worse than a
/// no-op. (Pasting into the `:`/`/` command line is future work.)
pub(crate) fn handle_paste(&mut self, text: String) {
if text.is_empty() {
return;
}
self.last_input_at = std::time::Instant::now();
if self.active_editor().vim_mode() != VimMode::Insert {
return;
}
let normalised = if text.contains('\r') {
text.replace("\r\n", "\n").replace('\r', "\n")
} else {
text
};
self.active_editor_mut().insert_str(&normalised);
self.sync_after_engine_mutation();
self.pending_recompute = true;
}
/// Poll in-flight grammar loads, git signs, format results, and anvil jobs.
/// Called once per event loop tick before the poll wait.
pub(crate) fn drain_async_polls(&mut self) {
// Poll any in-flight async grammar loads each tick so a freshly
// compiled grammar installs without needing a keypress.
if self.poll_grammar_loads() {
self.recompute_and_install();
}
// Install any git diff-sign / blame results that arrived from workers.
// When either poll returns true (new data arrived), set pending_recompute
// so the top-of-loop flush redraws the updated column/signs on the next
// iteration — without this the blame column stays blank until the next
// keypress because drain_async_polls runs AFTER terminal.draw.
if self.poll_git_signs() | self.poll_blame() {
self.pending_recompute = true;
}
// Install any completed async format results (#118).
let _ = self.poll_format_results();
// Poll any in-flight anvil install jobs and surface status toasts.
let _ = self.poll_anvil_jobs();
// Event-driven autoreload (#242): reconcile any external file changes
// the fs-watch surfaced. Like the git/blame polls above, this runs AFTER
// terminal.draw, so request a repaint when a buffer was reloaded.
if self.drain_fs_watch_events() {
self.pending_recompute = true;
}
}
/// Compute how long to wait for the next event.
///
/// Normally 120 ms (splash animation cadence), but shortened to the soonest
/// of (a) which-key popup deadline, (b) chord-timeout deadline (Ambiguous →
/// timeout_resolve), (c) active indent-flash so each 75 ms phase paints.
pub(crate) fn compute_poll_timeout(&self) -> Duration {
let base = Duration::from_millis(120);
let now = std::time::Instant::now();
let mut t = base;
if let Some(prefix_at) = self.pending_prefix_at {
if self.which_key_enabled && !self.which_key_active {
let deadline = prefix_at + self.which_key_delay;
t = t.min(deadline.saturating_duration_since(now));
}
if !self.which_key_active
&& !self
.app_keymap
.pending(crate::app::keymap::HjklMode::Normal)
.is_empty()
{
let deadline = prefix_at + self.app_keymap.timeout_duration();
t = t.min(deadline.saturating_duration_since(now));
}
}
if self.indent_flash.is_some() {
t = t.min(Duration::from_millis(30));
}
// Wake at `updatetime` after the last keystroke so the idle swap-write
// fires promptly. Gated on swap_pending (gen changed since last swap),
// NOT bare `dirty` — otherwise the deadline stays in the past after the
// swap is written and the poll timeout collapses to 0 (busy loop).
if self.active_swap_pending() {
let ut_ms = self.active_editor().settings().updatetime;
let deadline = self.last_input_at + Duration::from_millis(ut_ms as u64);
t = t.min(deadline.saturating_duration_since(now));
}
if self.scroll_anim.is_some() {
t = t.min(std::time::Duration::from_millis(16));
}
t
}
/// Handle a single key event. Returns a [`KeyOutcome`] that tells `run()`
/// whether to `continue`, `break`, or fall through to the engine dispatch.
///
/// All overlay handling, Normal-mode pre-routing (count prefix, Esc,
/// which-key Backspace), and keymap chord routing live here.
pub(crate) fn handle_keypress(&mut self, key: KeyEvent) -> KeyOutcome {
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
if self.command_field.is_some() {
self.command_field = None;
return KeyOutcome::Continue;
}
if self.search_field.is_some() {
self.cancel_search_prompt();
return KeyOutcome::Continue;
}
// <C-c> in the cmdline window closes it.
if self.is_cmdline_win_focused() {
self.close_cmdline_window();
return KeyOutcome::Continue;
}
return KeyOutcome::Break;
}
// ── Hop / easymotion overlay (#197) ──────────────────────
// Must run BEFORE all other overlay checks so hop owns every key
// while active. Any non-char key cancels (Esc explicitly, others
// via the None path in hop_handle_key).
if self.hop.is_some() {
match key.code {
KeyCode::Esc => self.hop_handle_key(None, true),
KeyCode::Char(c)
if key.modifiers == KeyModifiers::NONE
|| key.modifiers == KeyModifiers::SHIFT =>
{
self.hop_handle_key(Some(c), false)
}
_ => self.hop_handle_key(None, true),
}
return KeyOutcome::Continue;
}
// ── Quickfix popup (#184) ─────────────────────────────────
// While `:copen` is up, the popup owns navigation keys. `<CR>` jumps to
// the highlighted entry (popup stays open, vim-style); Esc/q close.
if self.quickfix_open {
match key.code {
KeyCode::Esc => self.quickfix_open = false,
KeyCode::Char('q') if key.modifiers == KeyModifiers::NONE => {
self.quickfix_open = false
}
KeyCode::Char('j') | KeyCode::Down => self.quickfix_popup_down(),
KeyCode::Char('k') | KeyCode::Up => self.quickfix_popup_up(),
KeyCode::Enter => self.quickfix_jump_to_current(),
_ => {}
}
return KeyOutcome::Continue;
}
// ── Location-list popup (#184 phase 3) ────────────────────
// Same key handling as the quickfix popup, against the location list.
if self.loclist_open {
match key.code {
KeyCode::Esc => self.loclist_open = false,
KeyCode::Char('q') if key.modifiers == KeyModifiers::NONE => {
self.loclist_open = false
}
KeyCode::Char('j') | KeyCode::Down => self.loclist_popup_down(),
KeyCode::Char('k') | KeyCode::Up => self.loclist_popup_up(),
KeyCode::Enter => self.loclist_jump_to_current(),
_ => {}
}
return KeyOutcome::Continue;
}
// ── BLAME mode ────────────────────────────────────────────
// BLAME is now an FSM-owned read-only view (`Editor::view_mode`). The
// engine handles every transition out of it natively: `Esc` (hjkl-vim
// normal dispatch), mode-entering keys (i/v/… via the mode funnels),
// and mouse-drag-into-Visual (the visual bridge) all auto-exit BLAME.
// No host-side key interception or per-tick invariant is needed.
// ── Cmdline window <CR> intercept (issue #37) ─────────────
// Must run BEFORE normal-mode routing so `<Enter>` in the
// cmdline window commits the line rather than opening a new line
// below (o) or doing nothing in Normal mode.
if self.is_cmdline_win_focused()
&& key.code == KeyCode::Enter
&& key.modifiers == KeyModifiers::NONE
{
self.commit_cmdline_window();
if self.exit_requested {
return KeyOutcome::Break;
}
return KeyOutcome::Continue;
}
// Dismiss the start screen on any non-Ctrl-C keypress and
// let the key fall through to normal handling so `:`,
// `/`, `i`, etc. take effect on the same press.
if self.start_screen.is_some() {
self.start_screen = None;
}
// Any keypress clears the which-key popup immediately. The
// prefix resolution branches below call note_prefix_set() again
// when chaining into a sub-prefix, which re-arms the timer.
self.which_key_active = false;
// ── Info popup dismissal ──────────────────────────────────
if self.info_popup.is_some() {
self.info_popup = None;
return KeyOutcome::Continue;
}
// ── Crash-recovery prompt (issue #185) ───────────────────
// Intercept BEFORE normal engine routing so y/N/q reach the
// recovery handler.
if self.pending_recovery.is_some() {
self.handle_recovery_key(key);
return KeyOutcome::Continue;
}
// ── Dirty-buffer disk-change prompt (issue #241) ──────────
// Intercept BEFORE engine routing so k/r/d reach the handler.
if self.pending_disk_change.is_some() {
self.handle_disk_change_key(key);
return KeyOutcome::Continue;
}
// ── Confirm-substitute prompt (:s/pat/rep/c) ──────────────
// Intercept BEFORE normal engine routing so y/n/a/q/l reach
// the confirm handler rather than the vim FSM.
if self.confirming_substitute.is_some() {
self.handle_confirm_substitute_key(key);
return KeyOutcome::Continue;
}
// ── Hover popup dismissal (Phase 5 mouse support) ─────────
if self.hover_popup.is_some() {
self.hover_popup = None;
self.hover_timer = None;
// fall through — key still takes effect
}
// ── Context menu keyboard navigation (Phase 2, Round A) ───
if self.context_menu.is_some() {
let consumed = self.handle_context_menu_key(key);
if consumed {
return KeyOutcome::Continue;
}
// Any non-nav key dismisses the menu and falls through.
self.context_menu = None;
}
// ── Explorer git-discard confirm ──────────────────────────
if self.explorer_git_discard_confirm.is_some() {
self.handle_explorer_git_discard_confirm_key(key);
return KeyOutcome::Continue;
}
// ── Command palette (`:` prompt) ─────────────────────────
if self.command_field.is_some() {
self.handle_command_field_key(key);
if self.exit_requested {
return KeyOutcome::Break;
}
return KeyOutcome::Continue;
}
// ── Filter prompt (`!` operator) ──────────────────────────
if self.filter_field.is_some() {
self.handle_filter_field_key(key);
return KeyOutcome::Continue;
}
// ── Search prompt (`/` `?`) ──────────────────────────────
if self.search_field.is_some() {
self.handle_search_field_key(key);
if self.exit_requested {
return KeyOutcome::Break;
}
return KeyOutcome::Continue;
}
// ── Picker overlay ────────────────────────────────────────
if self.picker.is_some() {
self.handle_picker_key(key);
if self.exit_requested {
return KeyOutcome::Break;
}
return KeyOutcome::Continue;
}
// ── File-explorer buffer (#55) ────────────────────────────
// Explorer keys are routed through `explorer_keymap` in
// `route_chord_key_inner` (step 2b) so they surface in the which-key
// popup. `u` (undo) and `<C-r>` (redo) are handled here because
// they are position-dependent or state-dependent.
if self.explorer_buf_focused()
&& self.active_editor().vim_mode() == VimMode::Normal
&& self.pending_state.is_none()
&& key.modifiers == KeyModifiers::NONE
{
// `u` — undo the last explorer fs transaction (journal-based,
// not vim buffer undo; the buffer is set_content-reset after
// each reconcile so vim undo is meaningless here).
if let KeyCode::Char('u') = key.code {
self.explorer_undo();
return KeyOutcome::Continue;
}
// `o` on a DIRECTORY → create the new entry INSIDE the dir (child
// indent, line below). `O` is left as the normal open-line-above,
// which autoindents to the current line's depth = a sibling. On a
// file, `o` also falls through to the normal open-line-below.
if key.code == KeyCode::Char('o') && self.explorer_open_in_dir() {
return KeyOutcome::Continue;
}
// `p` on a DIRECTORY → paste the cut/yanked entries INSIDE the dir
// (re-indented as children), so `dd` a dir then `p` on another dir
// MOVES it into that dir. On a file (or empty register) it falls
// through to the normal sibling paste.
if key.code == KeyCode::Char('p') && self.explorer_paste_in_dir() {
return KeyOutcome::Continue;
}
}
// <C-r> in the explorer while in Normal mode and no pending: redo.
if self.explorer_buf_focused()
&& self.active_editor().vim_mode() == VimMode::Normal
&& self.pending_state.is_none()
&& key.code == KeyCode::Char('r')
&& key.modifiers.contains(KeyModifiers::CONTROL)
{
self.explorer_redo();
return KeyOutcome::Continue;
}
// ── Visual-mode `:` → command prompt prefilled with '<,'> ─
// Must run BEFORE route_chord_key so a pending_state from a
// prior chord (e.g. first `g` in Visual mode) does not eat
// the `:` key. Visual `:` is not a chord continuation.
if key.code == KeyCode::Char(':')
&& key.modifiers == KeyModifiers::NONE
&& matches!(
self.active_editor().vim_mode(),
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock
)
{
// Exit visual mode by feeding Esc to the engine. The
// visual-exit hook in hjkl-engine sets the `<` / `>`
// marks so :'<,'> resolves.
hjkl_vim_tui::handle_key(
self.active_editor_mut(),
KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
);
self.open_command_prompt_with("'<,'>");
return KeyOutcome::Continue;
}
// ── Normal-mode app-level pre-routing ────────────────────
// These run BEFORE route_chord_key below. They may return Continue
// (consuming the key) or fall through to route_chord_key.
// Out of scope for route_chord_key: count-prefix, Esc, which-key BS.
// Migrated to keymap (issue #120):
// Phase 2: Ctrl-^, K, `:`, `/`, `?`
// Phase 3: H/L buffer cycle (BufferCycleH/L),
// Ctrl-h/j/k/l window focus + tmux (TmuxNavigate)
if self.active_editor().vim_mode() == VimMode::Normal {
// ── App-level count prefix buffering ─────────────────
// Buffer digit keys so that count-aware chords (Ngt,
// N<C-w>+) can consume the count. When the non-digit key
// is not a chord-starter, replay digits to the engine.
//
// Chord-starters: any key that the app_keymap might
// consume as the first key of a chord. We check
// has_prefix heuristically by attempting a feed of the
// raw key and rewinding if it returns Unbound immediately
// without any buffered prefix — but that's complex.
// Instead we keep the same explicit list as before:
// digits are buffered and replayed if the next key doesn't
// match a chord prefix.
//
// Skip count-prefix buffering entirely when a pending_state
// chord is active (e.g. SelectRegister after `"a`). In that
// case the next key is consumed by the reducer (not the count
// accumulator), and flushing digits to the engine would corrupt
// the engine's internal count state. route_chord_key below owns
// the key in that situation.
if self.pending_state.is_none() && key.modifiers == KeyModifiers::NONE {
if let KeyCode::Char(d @ '0'..='9') = key.code {
// try_accumulate returns false for '0' with empty buffer
// (vim's LineStart quirk); in that case fall through to keymap.
if self.pending_count.try_accumulate(d) {
return KeyOutcome::Continue;
}
// '0' with empty pending_count → start-of-line; fall through.
} else if !self.pending_count.is_empty() {
// Non-digit with buffered count.
// If it could start a chord, keep count alive.
// Otherwise replay digits now.
//
// Query the trie rather than a static char-set:
// ask whether this key is a root-level key in
// the Normal-mode bindings (i.e. a valid first
// key of any chord). `children_all` with an
// empty prefix returns all root entries without
// mutating the pending-chord state.
use crate::app::keymap::HjklMode as Mode;
let could_start_chord = !self.app_keymap.pending(Mode::Normal).is_empty()
|| to_km_event(key).is_some_and(|km_ev| {
let root = self
.app_keymap
.children_all(Mode::Normal, &KmChord::from_events(vec![]));
root.iter().any(|(k, _)| *k == km_ev)
});
if !could_start_chord {
self.flush_pending_count_to_engine();
}
}
} else if self.pending_state.is_none() {
// Modifier key. For Ctrl+Char keys the keymap may
// match (e.g. <C-d>/<C-u>/<C-f>/<C-b> from Phase 3g)
// and should receive the buffered count. Keep
// pending_count alive so dispatch_keymap sees it.
// If the keymap misses, the "Unbound" path below
// drains the digits to the engine before replaying.
// For non-Ctrl modifier keys (Alt, etc.) flush now as
// before — they are not keymap-bound count consumers.
let is_ctrl_char =
key.modifiers == KeyModifiers::CONTROL && matches!(key.code, KeyCode::Char(_));
if !is_ctrl_char && !self.pending_count.is_empty() {
self.flush_pending_count_to_engine();
}
}
// ── Escape: cancel any pending chord, else toggle which-key ─────────
if key.code == KeyCode::Esc {
// BLAME is a Normal-only read-only view; Esc must leave it. The
// engine's normal-mode Esc handler does exit_blame + force_normal,
// but the which-key toggle below returns before Esc ever reaches
// the engine — so exit BLAME here explicitly (mirroring the
// engine) and clear any pending state, as Esc otherwise would.
if self.active_editor().is_blame() {
self.active_editor_mut().exit_blame();
self.active_editor_mut().force_normal();
self.cancel_all_pending();
self.chord_history.clear();
self.which_key_sticky = false;
self.which_key_active = false;
return KeyOutcome::Continue;
}
let had_pending = self.any_chord_pending() || !self.pending_count.is_empty();
// Cancel across all three pending owners (trie, app pending_state,
// engine pending) + reset count. This restores Esc-cancels-chord
// behaviour that the which-key toggle would otherwise swallow.
self.cancel_all_pending();
self.chord_history.clear();
if had_pending {
self.which_key_sticky = false;
self.which_key_active = false;
return KeyOutcome::Continue;
}
// Nothing pending → toggle the top-level which-key display.
// Repeated Esc flips it on/off (Normal mode only).
if self.which_key_sticky {
self.which_key_sticky = false;
self.which_key_active = false;
} else {
self.which_key_sticky = true;
self.which_key_active = true;
self.note_prefix_set();
}
return KeyOutcome::Continue;
}
// ── Backspace: pop one chord level, else toggle which-key ───────────
if key.code == KeyCode::Backspace
&& key.modifiers == KeyModifiers::NONE
&& self.active_editor().vim_mode() == VimMode::Normal
{
if self.any_chord_pending() {
// Pop one level across ALL pending owners (trie, app
// pending_state, engine pending): cancel everything, then
// replay the chord's keys minus the last. This makes engine
// chords poppable too — e.g. `gc<BS>cc` resolves to `gcc`.
let mut hist = std::mem::take(&mut self.chord_history);
hist.pop();
self.cancel_all_pending();
for ev in hist {
self.chord_history.push(ev);
self.route_chord_key(ev);
}
if self.chord_history.is_empty() {
// Popped to root — keep the popup showing root entries.
self.which_key_sticky = true;
}
self.which_key_active = true;
self.note_prefix_set();
return KeyOutcome::Continue;
}
// Nothing pending → toggle the top-level which-key display,
// mirroring Esc. Backspace no longer moves left in Normal mode;
// it is the which-key navigate-up / toggle key.
if self.which_key_sticky {
self.which_key_sticky = false;
self.which_key_active = false;
} else {
self.which_key_sticky = true;
self.which_key_active = true;
self.note_prefix_set();
}
return KeyOutcome::Continue;
} else {
// Any non-Backspace key clears sticky which-key.
self.which_key_sticky = false;
}
// Fall through to route_chord_key below.
} else if matches!(
self.active_editor().vim_mode(),
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock
) {
// ── Visual-mode count prefix ─────────────────────────
// Clear stale Normal-mode chord state but PRESERVE the pending
// count so visual-mode counts accumulate (`2j`, `2>`, `3<`),
// mirroring the Normal-mode buffering above. Without this the
// digit was dropped (and the count reset every key), so every
// visual op / motion ran with count 1.
self.app_keymap.reset(crate::app::keymap::HjklMode::Normal);
self.explorer_keymap
.reset(crate::app::keymap::HjklMode::Normal);
self.clear_prefix_state();
if key.code == KeyCode::Esc {
// Cancel a half-typed count; the engine still receives Esc
// below to exit visual mode.
self.pending_count.reset();
} else if self.pending_state.is_none()
&& key.modifiers == KeyModifiers::NONE
&& let KeyCode::Char(d @ '0'..='9') = key.code
{
// try_accumulate buffers the digit; `0` with an empty buffer
// returns false (LineStart motion) and falls through.
if self.pending_count.try_accumulate(d) {
return KeyOutcome::Continue;
}
}
} else {
// Insert / other modes: reset any pending Normal-mode chord state.
self.app_keymap.reset(crate::app::keymap::HjklMode::Normal);
self.explorer_keymap
.reset(crate::app::keymap::HjklMode::Normal);
self.pending_count.reset();
self.clear_prefix_state();
}
// ── Canonical chord routing ───────────────────────────────
// Handles:
// (1) pending_state reducer (all modes, pending_state.is_some())
// (2) Non-Normal trie dispatch (mode != Normal, pending_state.is_none())
// (3) Normal-mode keymap dispatch (mode == Normal, pending_state.is_none())
// count-prefix, engine-pending bypass, and replay logic are encapsulated
// inside route_chord_key for step (3).
//
// Record Normal-mode keys into `chord_history` so Backspace can pop one
// chord level. Push before routing, then reconcile: keep the key only
// while a chord is still pending afterwards, otherwise the chord
// committed/cancelled and the history resets.
let track_chord = self.active_editor().vim_mode() == VimMode::Normal
&& !matches!(key.code, KeyCode::Backspace | KeyCode::Esc);
if track_chord {
self.chord_history.push(key);
}
if self.route_chord_key(key) {
if track_chord && !self.any_chord_pending() {
self.chord_history.clear();
}
if self.exit_requested {
return KeyOutcome::Break;
}
return KeyOutcome::Continue;
}
if track_chord {
self.chord_history.clear();
}
// ── Insert-mode completion key handling ──────────────────
// This block intercepts specific keys in insert mode to
// manage the completion popup, before forwarding to the engine.
if self.active_editor().vim_mode() == VimMode::Insert {
// Recorder hook for Insert-mode keys that this block consumes
// (printable chars routed to insert_char, popup-open Backspace
// routed to insert_backspace, etc). Those paths return
// KeyOutcome::Continue without ever reaching dispatch_insert_key
// or the engine FSM step wrapper, so the engine end_step
// recorder doesn't fire. Skipped during replay so played-back
// inputs don't append to the active recording. Keys that
// fall through this block to dispatch_insert_key get their
// recording from dispatch_insert_key's own hook.
if self.active_editor().is_recording_macro()
&& !self.active_editor().is_replaying_macro()
{
let input = hjkl_engine_tui::crossterm_to_input(key);
if input.key != hjkl_engine::Key::Null {
self.active_editor_mut().record_input(input);
}
}
// <C-x><C-o> manual omni-completion trigger.
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('x') {
self.pending_ctrl_x = true;
return KeyOutcome::Continue;
}
if self.pending_ctrl_x {
self.pending_ctrl_x = false;
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('o') {
self.lsp_request_completion();
return KeyOutcome::Continue;
}
// Any other key: fall through normally (consume pending_ctrl_x).
}
// Keys that navigate/accept/dismiss the popup (popup must be open).
if self.completion.is_some() {
match key.code {
// <C-n> / <C-p> navigate selection.
KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
if let Some(ref mut p) = self.completion {
p.cycle_down();
}
return KeyOutcome::Continue;
}
KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
if let Some(ref mut p) = self.completion {
p.cycle_up();
}
return KeyOutcome::Continue;
}
// <Down> / <Up> navigate selection (mirrors <C-n>/<C-p>).
KeyCode::Down => {
if let Some(ref mut p) = self.completion {
p.cycle_down();
}
return KeyOutcome::Continue;
}
KeyCode::Up => {
if let Some(ref mut p) = self.completion {
p.cycle_up();
}
return KeyOutcome::Continue;
}
// <Enter> accepts the selected item (only when popup is open).
KeyCode::Enter => {
self.accept_completion();
self.sync_after_engine_mutation();
return KeyOutcome::Continue;
}
// <Tab> or <C-y> accept selected item.
KeyCode::Tab => {
self.accept_completion();
self.sync_after_engine_mutation();
return KeyOutcome::Continue;
}
KeyCode::Char('y') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.accept_completion();
self.sync_after_engine_mutation();
return KeyOutcome::Continue;
}
// <C-e> dismiss without accepting.
KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.dismiss_completion();
return KeyOutcome::Continue;
}
// <Esc> dismisses popup and falls through to engine
// which exits insert mode.
KeyCode::Esc => {
self.dismiss_completion();
// fall through to engine
}
// Printable char or backspace: update prefix, maybe dismiss.
KeyCode::Char(c) if key.modifiers == KeyModifiers::NONE => {
// Phase 6.5: call insert primitive directly.
self.active_editor_mut().insert_char(c);
self.sync_viewport_from_editor();
if self.active_editor_mut().take_dirty() {
let elapsed = self.active_mut().refresh_dirty_against_saved();
self.last_signature_us = elapsed;
if self.active().dirty {
self.active_mut().is_new_file = false;
}
}
let buffer_id = self.active().buffer_id;
if self.active_editor_mut().take_content_reset() {
self.handle_active_content_reset(buffer_id);
}
let edits = self.active_editor_mut().take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(buffer_id, &edits);
}
self.lsp_notify_change_active(&edits);
self.rebase_sibling_cursors(&edits);
// Defer TS reparse to the end-of-drain flush so a
// burst of insert-mode keys folds into one parse
// instead of paying per-keystroke sync cost.
self.pending_recompute = true;
// Update popup prefix.
let anchor_col =
self.completion.as_ref().map(|p| p.anchor_col).unwrap_or(0);
let cur_col = self.active_editor().buffer().cursor().col;
let cur_row = self.active_editor().buffer().cursor().row;
let anchor_row = self
.completion
.as_ref()
.map(|p| p.anchor_row)
.unwrap_or(cur_row);
if cur_row != anchor_row || cur_col < anchor_col {
// Cursor moved out of anchor range — dismiss.
self.dismiss_completion();
} else {
let new_prefix = {
// `.line(cur_row)` is O(log N) on rope storage
// and clones a single row, not the whole doc.
let rope = self.active_editor().buffer().rope();
let line = if cur_row < rope.len_lines() {
hjkl_buffer::rope_line_str(&rope, cur_row)
} else {
String::new()
};
// `anchor_col`/`cur_col` are CHAR indices; map to
// byte offsets so the slice never lands inside a
// multibyte char (crash on pasted Unicode).
let byte_of = |char_col: usize| -> usize {
line.char_indices()
.nth(char_col)
.map(|(b, _)| b)
.unwrap_or(line.len())
};
let a = byte_of(anchor_col);
let c = byte_of(cur_col);
line[a.min(c)..a.max(c)].to_string()
};
if let Some(ref mut popup) = self.completion {
popup.set_prefix(&new_prefix);
if popup.is_empty() {
self.completion = None;
}
}
}
// Auto-trigger on trigger chars when popup just closed.
if self.completion.is_none() {
self.maybe_auto_trigger_completion(c);
}
return KeyOutcome::Continue;
}
KeyCode::Backspace if key.modifiers == KeyModifiers::NONE => {
// Phase 6.5: call insert primitive directly.
self.active_editor_mut().insert_backspace();
self.sync_viewport_from_editor();
if self.active_editor_mut().take_dirty() {
let elapsed = self.active_mut().refresh_dirty_against_saved();
self.last_signature_us = elapsed;
if self.active().dirty {
self.active_mut().is_new_file = false;
}
}
let buffer_id = self.active().buffer_id;
if self.active_editor_mut().take_content_reset() {
self.handle_active_content_reset(buffer_id);
}
let edits = self.active_editor_mut().take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(buffer_id, &edits);
}
self.lsp_notify_change_active(&edits);
self.rebase_sibling_cursors(&edits);
// Defer TS reparse to the end-of-drain flush so a
// burst of insert-mode keys folds into one parse
// instead of paying per-keystroke sync cost.
self.pending_recompute = true;
let anchor_col =
self.completion.as_ref().map(|p| p.anchor_col).unwrap_or(0);
let cur_col = self.active_editor().buffer().cursor().col;
let cur_row = self.active_editor().buffer().cursor().row;
let anchor_row = self
.completion
.as_ref()
.map(|p| p.anchor_row)
.unwrap_or(cur_row);
if cur_row != anchor_row || cur_col < anchor_col {
self.dismiss_completion();
} else {
let new_prefix = {
let rope = self.active_editor().buffer().rope();
let line = if cur_row < rope.len_lines() {
hjkl_buffer::rope_line_str(&rope, cur_row)
} else {
String::new()
};
// CHAR indices → byte offsets (multibyte-safe).
let byte_of = |char_col: usize| -> usize {
line.char_indices()
.nth(char_col)
.map(|(b, _)| b)
.unwrap_or(line.len())
};
let a = byte_of(anchor_col);
let c = byte_of(cur_col);
line[a.min(c)..a.max(c)].to_string()
};
if let Some(ref mut popup) = self.completion {
popup.set_prefix(&new_prefix);
if popup.is_empty() {
self.completion = None;
}
}
}
return KeyOutcome::Continue;
}
_ => {
// Any other key dismisses the popup.
self.dismiss_completion();
}
}
} else {
// Popup is closed. Handle <C-n>/<C-p> as manual trigger.
if key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Char('n') | KeyCode::Char('p'))
{
self.lsp_request_completion();
return KeyOutcome::Continue;
}
// Auto-trigger on trigger chars.
if key.modifiers == KeyModifiers::NONE
&& let KeyCode::Char(c) = key.code
{
// Phase 6.5: call insert primitive directly.
self.active_editor_mut().insert_char(c);
self.sync_viewport_from_editor();
if self.active_editor_mut().take_dirty() {
let elapsed = self.active_mut().refresh_dirty_against_saved();
self.last_signature_us = elapsed;
if self.active().dirty {
self.active_mut().is_new_file = false;
}
}
let buffer_id = self.active().buffer_id;
if self.active_editor_mut().take_content_reset() {
self.handle_active_content_reset(buffer_id);
}
let edits = self.active_editor_mut().take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(buffer_id, &edits);
}
self.lsp_notify_change_active(&edits);
self.rebase_sibling_cursors(&edits);
self.pending_recompute = true;
self.maybe_auto_trigger_completion(c);
return KeyOutcome::Continue;
}
}
} else {
// Left insert mode — dismiss popup.
if self.completion.is_some() {
self.dismiss_completion();
}
}
KeyOutcome::FallThrough
}
/// Handle a single mouse event. Returns a [`MouseOutcome`] indicating
/// whether the loop should `continue` or fall through.
pub(crate) fn handle_mouse(&mut self, me: crossterm::event::MouseEvent) -> MouseOutcome {
use crossterm::event::{MouseButton, MouseEventKind};
// Skip while overlays are active — Phase 8 will handle
// mouse in overlays.
if self.command_field.is_some()
|| self.search_field.is_some()
|| self.picker.is_some()
|| self.info_popup.is_some()
{
return MouseOutcome::Continue;
}
// P11.3 — gate events by per-mode mouse flags.
// Command-field overlay already handled above; here we gate
// on the editor's vim mode for the remaining events.
{
let mode = self.active_editor().vim_mode();
if !crate::app::mouse_enabled_for(mode, &self.mouse_flags) {
return MouseOutcome::Continue;
}
}
// 3 lines/cols per wheel notch — vim's `mousescroll` default.
const WHEEL_TICKS: i16 = 3;
use crossterm::event::KeyModifiers;
/// Route scroll to the window under the cursor, focusing it
/// if needed. Returns `false` when the pointer is outside
/// every window (e.g. over the status bar) — caller should
/// skip the scroll in that case.
fn focus_window_under_cursor(app: &mut crate::app::App, col: u16, row: u16) -> bool {
use crate::app::mouse;
if let Some(win_id) = mouse::hit_test_window(app, col, row) {
let current_focus = app.focused_window();
if win_id != current_focus {
app.switch_focus(win_id);
}
true
} else {
false
}
}
// Scroll arms set `pending_recompute` instead of calling
// `recompute_and_install` synchronously. The main event loop
// drains all currently-ready events before firing one recompute,
// so a burst of mouse-wheel scroll events runs the sync query +
// install pipeline ONCE per drain instead of N times per burst.
// Without this the per-event ~2-5ms sync query stacked into
// visible scroll lag.
match me.kind {
MouseEventKind::ScrollDown => {
if me.modifiers.contains(KeyModifiers::SHIFT) {
if focus_window_under_cursor(self, me.column, me.row) {
self.active_editor_mut().scroll_right(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
} else if focus_window_under_cursor(self, me.column, me.row) {
self.active_editor_mut().scroll_down(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
}
MouseEventKind::ScrollUp => {
if me.modifiers.contains(KeyModifiers::SHIFT) {
if focus_window_under_cursor(self, me.column, me.row) {
self.active_editor_mut().scroll_left(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
} else if focus_window_under_cursor(self, me.column, me.row) {
self.active_editor_mut().scroll_up(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
}
MouseEventKind::ScrollLeft if focus_window_under_cursor(self, me.column, me.row) => {
self.active_editor_mut().scroll_left(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
MouseEventKind::ScrollRight if focus_window_under_cursor(self, me.column, me.row) => {
self.active_editor_mut().scroll_right(WHEEL_TICKS);
self.sync_viewport_from_editor();
self.pending_recompute = true;
}
MouseEventKind::Down(MouseButton::Left) => {
use crate::app::mouse;
self.dismiss_hover_popup_on_click();
// ── Explorer mouse handling ───────────────────────
// Click a tree row: focus the explorer, move the cursor there,
// and activate it (toggle a dir / open-or-focus a file).
// The search box is gone — the explorer is now a plain buffer
// where `/` opens the normal incremental search.
if let Some(win_id) = self.explorer.as_ref().map(|ep| ep.win_id) {
let rect = self
.windows
.get(win_id)
.and_then(|w| w.as_ref())
.and_then(|w| w.last_rect);
if let Some(rect) = rect {
let in_pane = me.column >= rect.x
&& me.column < rect.x + rect.w
&& me.row >= rect.y
&& me.row < rect.y + rect.h;
// Tree-row click → move cursor there + activate. Resolve
// the doc row with the FOLD-AWARE `cell_to_doc` (a naive
// `top_row + screen_offset` ignores collapsed dirs, so a
// click below a closed fold lands on the wrong node). It
// also uses the window's own scroll origin, correct for
// the (usually unfocused) explorer pane.
if in_pane {
if let Some((doc_row, _)) =
mouse::cell_to_doc(self, win_id, me.column, me.row)
{
// Move the explorer window editor cursor to the
// clicked row (#151 Phase D), then activate: toggle
// a dir's fold or open/focus a file.
self.set_explorer_window_cursor(doc_row, 0, None);
self.explorer_activate();
self.sync_after_engine_mutation_deferred();
}
return MouseOutcome::Continue;
}
// else: click outside the explorer pane → fall through.
}
}
// ── Phase 9: border-drag hit-test ─────────────────
// Check BEFORE context-menu and window-click logic so
// a border click never accidentally focuses a window.
if let Some(hit) = mouse::hit_test_border(self, me.column, me.row) {
// Encode border position as a synthetic id for the
// double-click tracker. We use a large offset beyond
// real WindowIds to avoid collisions.
let synthetic_id: usize = usize::MAX
.wrapping_sub(hit.border_cell.0 as usize)
.wrapping_sub((hit.border_cell.1 as usize) << 16);
let count = self.mouse_click_tracker.register(synthetic_id, 0, 0);
if count == 2 {
// Double-click → equalize all splits.
self.equalize_split();
} else {
// Single click → begin drag.
let last_pos = match hit.orientation {
mouse::SplitOrientation::Vertical => me.column,
mouse::SplitOrientation::Horizontal => me.row,
};
self.border_drag = Some(crate::app::BorderDrag {
orientation: hit.orientation,
split_origin: hit.split_origin,
split_total: hit.split_total,
last_pos,
});
}
return MouseOutcome::Continue;
}
// ── Context-menu: click-inside → invoke / click-outside → dismiss
if let Some(ref menu) = self.context_menu {
let screen_size = self.screen_rect();
let rect = crate::menu::bounding_rect(menu, screen_size);
let inside = me.column >= rect.x
&& me.column < rect.x + rect.width
&& me.row >= rect.y
&& me.row < rect.y + rect.height;
if inside {
// Check whether click landed on a selectable row.
if me.row > rect.y && me.row < rect.y + rect.height - 1 {
let item_idx = (me.row - rect.y - 1) as usize;
let action = menu
.items
.get(item_idx)
.filter(|it| {
it.enabled && it.action != crate::menu::MenuAction::Separator
})
.map(|it| it.action.clone());
self.context_menu = None;
if let Some(act) = action {
self.invoke_menu_action(act);
}
}
return MouseOutcome::Continue; // Don't fall through to editor click.
} else {
self.context_menu = None;
// Fall through to normal editor click.
}
}
// ── P4.1: Ctrl+Left-click → goto-definition ──────
if me.modifiers.contains(KeyModifiers::CONTROL) {
if let mouse::Zone::Code {
win_id,
doc_row,
doc_col,
} = mouse::hit_test_zone(self, me.column, me.row)
{
// Focus window if needed.
let current_focus = self.focused_window();
if win_id != current_focus {
self.switch_focus(win_id);
}
self.active_editor_mut().mouse_click_doc(doc_row, doc_col);
self.sync_after_engine_mutation_deferred();
self.lsp_goto_definition();
}
// Ctrl+click outside Code zone is a no-op.
return MouseOutcome::Continue;
}
// ── P4.2: Shift+Left-click → extend visual selection
if me.modifiers.contains(KeyModifiers::SHIFT) {
if let mouse::Zone::Code {
win_id,
doc_row,
doc_col,
} = mouse::hit_test_zone(self, me.column, me.row)
{
// Focus window if needed.
let current_focus = self.focused_window();
if win_id != current_focus {
self.switch_focus(win_id);
}
// Anchor at current cursor if not already visual.
if self.active_editor().vim_mode() != VimMode::Visual {
self.active_editor_mut().mouse_begin_drag();
}
self.active_editor_mut()
.mouse_extend_drag_doc(doc_row, doc_col);
self.sync_after_engine_mutation_deferred();
}
// Shift+click outside Code zone is a no-op.
return MouseOutcome::Continue;
}
// Left-click on the tab bar / buffer line switches
// to that tab or buffer. Clicking the close glyph closes it.
match mouse::hit_test_zone(self, me.column, me.row) {
mouse::Zone::TabBarClose { tab_idx } => {
if tab_idx != self.active_tab {
self.switch_tab(tab_idx);
}
self.do_tabclose();
return MouseOutcome::Continue;
}
mouse::Zone::TabBar { tab_idx } => {
if tab_idx != self.active_tab {
self.switch_tab(tab_idx);
}
return MouseOutcome::Continue;
}
mouse::Zone::BufferLineClose { slot_idx } => {
self.close_buffer_slot(slot_idx);
return MouseOutcome::Continue;
}
mouse::Zone::BufferLine { slot_idx } => {
if slot_idx != self.focused_slot_idx() {
self.switch_to(slot_idx);
}
return MouseOutcome::Continue;
}
// ── P10: left-click a fold marker in the gutter → toggle fold.
mouse::Zone::Gutter { win_id, doc_row } => {
// Focus the clicked window first (matches inactive-window
// click-to-focus behaviour); only toggle when a fold
// actually starts/contains this row so plain line-number
// clicks stay no-ops (see `gutter_click_no_cursor_move`).
let current_focus = self.focused_window();
if win_id != current_focus {
self.switch_focus(win_id);
}
if self.active_editor().buffer().fold_at_row(doc_row).is_some() {
self.active_editor_mut()
.apply_fold_op(hjkl_engine::FoldOp::ToggleAt(doc_row));
self.sync_after_engine_mutation_deferred();
} else if self.active().git_signs.iter().any(|s| s.row == doc_row) {
// P10: no fold here, but a git sign is — preview the
// hunk covering this row in a read-only popup.
self.git_show_hunk_diff_at_row(doc_row);
}
return MouseOutcome::Continue;
}
_ => {}
}
if let Some(win_id) = mouse::hit_test_window(self, me.column, me.row) {
// Resolve the clicked doc position AGAINST THE RENDERED FRAME,
// i.e. BEFORE focusing. `switch_focus` installs the window's
// saved cursor and applies scrolloff, which can scroll the
// editor viewport; mapping the click after that would read the
// post-scroll `top_row` and land on the wrong line (every
// click into a not-yet-focused pane came out offset).
let hit = mouse::cell_to_doc(self, win_id, me.column, me.row);
// Focus the clicked window if it differs.
let current_focus = self.focused_window();
if win_id != current_focus {
self.switch_focus(win_id);
}
if let Some((doc_row, doc_col)) = hit {
let count = self.mouse_click_tracker.register(win_id, doc_row, doc_col);
match count {
1 => {
self.active_editor_mut().mouse_click_doc(doc_row, doc_col);
}
2 => {
// Double-click: select word.
self.active_editor_mut().mouse_click_doc(doc_row, doc_col);
let line = {
let rope = self.active_editor().buffer().rope();
if doc_row < rope.len_lines() {
hjkl_buffer::rope_line_str(&rope, doc_row)
} else {
String::new()
}
};
let (ws, we) = mouse::word_bounds(&line, doc_col);
// Anchor at word start, cursor at word end - 1.
self.active_editor_mut().enter_visual_char();
self.active_editor_mut().set_cursor_doc(doc_row, ws);
self.active_editor_mut().mouse_begin_drag();
self.active_editor_mut()
.set_cursor_doc(doc_row, we.saturating_sub(1).max(ws));
}
_ => {
// Triple-click (and count≥4 wraps to 1 in tracker,
// so this branch only fires at count==3).
self.active_editor_mut().mouse_click_doc(doc_row, doc_col);
self.active_editor_mut().enter_visual_line();
}
}
self.sync_after_engine_mutation_deferred();
}
}
}
MouseEventKind::Drag(MouseButton::Left) => {
use crate::app::mouse;
// ── Phase 9: border drag ──────────────────────────
if let Some(drag) = self.border_drag {
let new_pos = match drag.orientation {
mouse::SplitOrientation::Vertical => me.column,
mouse::SplitOrientation::Horizontal => me.row,
};
let split_pos = new_pos.saturating_sub(drag.split_origin);
self.resize_split_to(
drag.orientation,
drag.split_origin,
drag.split_total,
split_pos,
);
if let Some(d) = self.border_drag.as_mut() {
d.last_pos = new_pos;
}
return MouseOutcome::Continue;
}
let win_id = self.focused_window();
if let Some((doc_row, doc_col)) =
mouse::cell_to_doc(self, win_id, me.column, me.row)
{
// Begin drag on first drag event if not already in
// visual mode.
if self.active_editor().vim_mode() != VimMode::Visual {
self.active_editor_mut().mouse_begin_drag();
}
self.active_editor_mut()
.mouse_extend_drag_doc(doc_row, doc_col);
self.sync_after_engine_mutation_deferred();
}
}
// Up: clear any active border drag; vim stays in
// Visual after a text drag-release — no-op otherwise.
MouseEventKind::Up(MouseButton::Left) if self.border_drag.is_some() => {
self.border_drag = None;
}
// ── P4.3: Middle-click → primary-selection paste ──────
//
// X11 / Wayland convention: middle-click pastes the
// primary selection (whatever is currently highlighted
// anywhere on screen, independent of the system
// clipboard). macOS / Windows have no primary
// selection; we silently no-op when the clipboard
// backend does not report `Capabilities::PRIMARY`.
MouseEventKind::Down(MouseButton::Middle) => {
self.dismiss_hover_popup_on_click();
self.middle_click(me.column, me.row);
}
// ── Right-click: open context menu (Phase 2 + 7 + 8) ─
MouseEventKind::Down(MouseButton::Right) => {
use crate::app::mouse;
use crate::menu::{
ContextMenu, build_code_menu, build_picker_menu, build_split_border_menu,
build_status_line_menu, build_tab_menu,
};
// Dismiss hover popup — same rationale as left-click.
self.hover_popup = None;
self.hover_timer = None;
let zone = mouse::hit_test_zone(self, me.column, me.row);
let items = match zone {
mouse::Zone::Code { .. } => {
self.move_cursor_for_right_click(me.column, me.row);
let has_sel = matches!(
self.active_editor().vim_mode(),
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock
);
build_code_menu(has_sel, self.active_has_lsp())
}
// ── Phase 6/10: gutter / sign-column menu ──────
// A diagnostic on the clicked line leads with Show
// Diagnostic + Code Actions (#116); a git change on
// the line adds Stage / Revert / Show Hunk (#115);
// otherwise this falls through to the Code menu.
mouse::Zone::Gutter { doc_row, .. } => {
self.move_cursor_for_right_click(me.column, me.row);
let has_sel = matches!(
self.active_editor().vim_mode(),
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock
);
let has_diag = self.diagnostic_on_row(doc_row);
let git_kind = self.git_hunk_kind_at_row(doc_row);
crate::menu::build_gutter_menu(
has_diag,
git_kind,
self.active_has_lsp(),
has_sel,
)
}
mouse::Zone::TabBar { tab_idx } | mouse::Zone::TabBarClose { tab_idx } => {
// Switch to the clicked tab first so that
// Close-Tab / Close-Right / Close-Left operate on it.
if tab_idx != self.active_tab {
self.switch_tab(tab_idx);
}
build_tab_menu(self.tabs.len() > 1)
}
mouse::Zone::BufferLine { slot_idx }
| mouse::Zone::BufferLineClose { slot_idx } => {
// Switch to the clicked buffer first so the
// tab menu's actions operate on it. Buffer
// line shares the tab menu for v1 — close /
// close-others / close-{left,right} have
// intuitive buffer-line semantics too.
if slot_idx != self.focused_slot_idx() {
self.switch_to(slot_idx);
}
build_tab_menu(self.tabs.len() > 1)
}
// ── Phase 7: status-line menu ─────────────────
mouse::Zone::StatusLine => {
let ft = self.active_filetype_label();
let lsp_name = self.active_lsp_server_name();
build_status_line_menu(&ft, lsp_name.as_deref())
}
// ── Phase 7: split-border menu ─────────────────
mouse::Zone::SplitBorder { .. } => build_split_border_menu(),
// ── Phase 8: picker overlay row menu ───────────
mouse::Zone::PickerRow { row_idx } => {
// Move picker selection to the clicked row.
if let Some(ref mut p) = self.picker {
p.selected = row_idx;
}
let has_path = self
.picker
.as_ref()
.and_then(|p| p.path_for_visible_row(p.selected))
.is_some();
build_picker_menu(has_path)
}
mouse::Zone::None => {
return MouseOutcome::Continue;
}
};
self.context_menu = Some(ContextMenu::new(items, (me.column, me.row)));
}
// ── Mouse hover: update selected item ────────────────
MouseEventKind::Moved => {
// Read viewport dims BEFORE borrowing menu mutably
// (split-borrow workaround). The previous "anchor +
// slack" approximation broke hover→item mapping for
// menus anchored near the screen edges: when
// `bounding_rect` flipped the popup upward to fit on
// screen, this handler still used the original
// anchor as the rect origin and mapped hovers to the
// wrong items. Use the real terminal area instead.
let screen_size = self.screen_rect();
if let Some(menu) = &mut self.context_menu {
let rect = crate::menu::bounding_rect(menu, screen_size);
// Inner area (strip border row/col).
if me.row > rect.y
&& me.row < rect.y + rect.height - 1
&& me.column > rect.x
&& me.column < rect.x + rect.width - 1
{
// Row inside inner content; map to item index.
let item_idx = (me.row - rect.y - 1) as usize;
if item_idx < menu.items.len() {
let enabled = menu.items[item_idx].enabled
&& menu.items[item_idx].action
!= crate::menu::MenuAction::Separator;
if enabled {
menu.selected = item_idx;
}
}
}
}
// ── Phase 5: hover-popup timer ────────────────────
let cell = (me.column, me.row);
// Any mouse move dismisses an open hover popup and
// resets the timer to track the new cell.
if self.hover_popup.is_some() {
self.hover_popup = None;
self.hover_timer = None;
}
// Skip arming entirely while an overlay is up —
// a hover for the doc cell behind the menu/picker
// would render through the overlay.
if !self.overlay_active() {
let same_cell = self.hover_timer.as_ref().is_some_and(|h| h.cell == cell);
if !same_cell {
self.hover_timer = Some(crate::app::HoverTimer {
cell,
started_at: std::time::Instant::now(),
request_sent: false,
});
}
// Fire check (also handled in the poll-timeout
// tick) so we react immediately on the Moved
// event that coincides with the 500ms threshold.
self.tick_hover_timer();
}
}
_ => {}
}
MouseOutcome::FallThrough
}
/// Main event loop. Draws every frame, routes key events through
/// the vim FSM, handles resize, exits on Ctrl-C.
///
/// WARN: This loop batches expensive sync work (tree-sitter reparse,
/// span query, git signs) via `self.pending_recompute = true` flushed
/// at the top of each iteration right before `terminal.draw`. The
/// invariants are load-bearing — break them and per-keystroke CPU
/// regresses by multiple TS parses per key on huge files:
///
/// 1. Keystroke arms (insert + normal) MUST set `pending_recompute = true`
/// and never call `recompute_and_install()` inline.
/// 2. `KeyOutcome::Continue` MUST NOT `continue` to the top of the loop —
/// it must fall through to the drain block below so queued events
/// fold into the same flush. Use the `consumed_inline` flag pattern.
/// 3. `render::frame` MUST NOT call `recompute_and_install()` — the
/// flush above already handled it. `App::new` seeds
/// `pending_recompute = true` so the first frame still runs an
/// initial parse via this flush.
/// 4. Order is fixed: lsp drain → viewport → cursor shape → FLUSH →
/// draw → async polls → poll(timeout) → read → handle + drain.
pub fn run(&mut self, terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
loop {
// ── Per-tick setup ────────────────────────────────────
// NOTE: sync_viewport_to_editor() is NOT called here — it is
// called only on focus change (switch_focus / close_focused_window
// / move_window_to_new_tab). Calling it before every keypress
// clobbered sticky_col and broke j/k column preservation (#151).
self.drain_lsp_events();
// Ensure every window has a view editor onto its slot's Content
// (#151 Phase D). Splits create a window before its editor exists;
// buffer switches change a window's slot. Idempotent — rebuilds a
// window editor only on a real content change (Arc::ptr_eq).
self.reconcile_window_editors();
{
let size = terminal.size()?;
let vp = self.active_editor_mut().host_mut().viewport_mut();
vp.width = size.width;
vp.height = size.height.saturating_sub(STATUS_LINE_HEIGHT);
}
// ── Cursor shape ──────────────────────────────────────
let current_shape = if let Some(ref f) = self.command_field {
prompt_cursor_shape(f)
} else if let Some(ref f) = self.search_field {
prompt_cursor_shape(f)
} else {
self.active_editor().host().cursor_shape()
};
if current_shape != self.last_cursor_shape {
match current_shape {
CursorShape::Block => {
let _ = execute!(terminal.backend_mut(), SetCursorStyle::SteadyBlock);
}
CursorShape::Bar => {
let _ = execute!(terminal.backend_mut(), SetCursorStyle::SteadyBar);
}
CursorShape::Underline => {
let _ = execute!(terminal.backend_mut(), SetCursorStyle::SteadyUnderScore);
}
}
self.last_cursor_shape = current_shape;
}
// Flush any deferred syntax recompute before drawing so the
// frame sees the latest spans. Insert-mode arms `return
// KeyOutcome::Continue` and skip the end-of-drain flush, so
// without this the highlights would only catch up when the
// user pressed a non-insert-arm key (e.g. ESC).
if self.pending_recompute {
self.pending_recompute = false;
self.recompute_and_install();
}
if self.scroll_anim_expired() {
self.scroll_anim = None;
}
// ── Draw ──────────────────────────────────────────────
// `:redraw!` sets force_clear_screen; clear before drawing so
// stale terminal content is wiped. Cleared immediately so only
// the next frame pays the cost.
if self.force_clear_screen {
self.force_clear_screen = false;
terminal.clear()?;
}
// Refresh the inline-blame idle debounce from the cursor position
// (source-agnostic) before drawing so the blame ghost engages only
// after the cursor has settled for `BLAME_IDLE_DELAY`.
self.note_blame_cursor_motion();
let t_draw = std::time::Instant::now();
terminal.draw(|frame| render::frame(frame, self))?;
tracing::debug!(
target: "hjkl::profile",
draw_us = t_draw.elapsed().as_micros(),
"draw"
);
// ── Async polls ───────────────────────────────────────
self.drain_async_polls();
// ── Poll timeout ──────────────────────────────────────
let poll_timeout = self.compute_poll_timeout();
// ── Wait for event ────────────────────────────────────
if !event::poll(poll_timeout)? {
let now = std::time::Instant::now();
if !self.which_key_active
&& !self.active_which_key_prefix().is_empty()
&& crate::which_key::should_show(
self.pending_prefix_at,
self.which_key_delay,
self.which_key_enabled,
now,
)
{
self.which_key_active = true;
}
// Chord timeout: only resolves an ambiguous prefix when the
// which-key popup is NOT visible. Once the popup shows, the
// user has seen the menu and should pick a key (or Esc to
// cancel) — letting the timeout fire here would yank the
// popup away mid-decision. Matches which-key.nvim default
// and vim-which-key behaviour.
if !self.which_key_active
&& let Some(prefix_at) = self.pending_prefix_at
&& !self
.app_keymap
.pending(crate::app::keymap::HjklMode::Normal)
.is_empty()
&& now >= prefix_at + self.app_keymap.timeout_duration()
&& let Some(replay) =
self.resolve_chord_timeout(crate::app::keymap::HjklMode::Normal)
&& !replay.is_empty()
{
replay_to_engine(self, &replay);
self.sync_after_engine_mutation();
}
// ── Idle swap-write (issue #185) ──────────────────────
// Write the swap for the active slot when the buffer is dirty
// and `updatetime` ms have elapsed since the last keystroke.
{
let ut_ms = self.active_editor().settings().updatetime;
let deadline = self.last_input_at + Duration::from_millis(ut_ms as u64);
if self.active_swap_pending() && now >= deadline {
let idx = self.focused_slot_idx();
self.write_swap_for_slot(idx);
}
}
self.tick_hover_timer();
if self
.hover_popup
.as_ref()
.is_some_and(|p| p.is_expired(std::time::Instant::now()))
{
self.hover_popup = None;
self.hover_timer = None;
}
self.indent_flash_active();
continue;
}
// ── Dispatch event ────────────────────────────────────
match event::read()? {
Event::Key(key) => {
// Record keystroke time for the idle swap-write timer (#185).
self.last_input_at = std::time::Instant::now();
// ── Kitty keyboard normalization (vim only) ────────
// Under DISAMBIGUATE_ESCAPE_CODES, Ctrl+[ ≠ Esc, Ctrl+I ≠ Tab,
// Ctrl+M ≠ Enter at the terminal level. Normalize back to the
// legacy aliases for vim discipline only; VSCode gets raw keys
// (Ctrl+[ = outdent, etc.).
let key = if self.keybinding_mode == hjkl_engine::KeybindingMode::Vim {
hjkl_kitty::normalize_legacy(key)
} else {
key
};
// ── VSCode keybinding mode early intercept ────────
// Folded into one choke point shared with the drain loop
// (#265 G3 B3). Returns true (consumed) when VSCode owns
// the key; false falls through to handle_keypress.
if self.try_vscode_intercept(key) {
continue;
}
let consumed_inline = match self.handle_keypress(key) {
KeyOutcome::Break => break,
// Insert-mode arms handle the keystroke fully and
// set `pending_recompute = true` themselves. Skip
// the FallThrough cleanup but still hit the drain
// loop below so a burst of inline-consumed keys
// folds into one recompute + draw.
KeyOutcome::Continue => true,
KeyOutcome::FallThrough => false,
};
if !consumed_inline {
// ── Normal editor key handling ────────────────
// Insert mode uses the inline dispatcher which calls
// Editor::insert_* primitives directly. Normal / Visual
// modes route through the FSM via hjkl_vim_tui::handle_key.
self.scroll_anim = None; // any new key cancels running animation
let prev_top = self.window_scroll(self.focused_window()).0;
let mode_was_insert = self.active_editor().vim_mode() == VimMode::Insert;
if mode_was_insert {
self.dispatch_insert_key(key);
self.active_editor_mut().emit_cursor_shape_if_changed();
} else {
hjkl_vim_tui::handle_key(self.active_editor_mut(), key);
}
self.sync_viewport_from_editor();
if self.active_editor_mut().take_dirty() {
let elapsed = self.active_mut().refresh_dirty_against_saved();
self.last_signature_us = elapsed;
if self.active().dirty {
self.active_mut().is_new_file = false;
}
}
let buffer_id = self.active().buffer_id;
if self.active_editor_mut().take_content_reset() {
self.handle_active_content_reset(buffer_id);
}
let edits = self.active_editor_mut().take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(buffer_id, &edits);
self.active_editor_mut()
.shift_syntax_spans_for_edits(&edits);
}
self.lsp_notify_change_active(&edits);
self.rebase_sibling_cursors(&edits);
// Drain pending fold ops to prevent unbounded growth;
// `recompute_and_install` (via `pending_recompute`)
// handles the visual refresh.
let _ = self.active_editor_mut().take_fold_ops();
{
let hint = self.active_editor_mut().take_scroll_anim_hint();
if hint {
let ms = self.active_editor().settings().scroll_duration_ms;
let win = self.focused_window();
let new_top = self.window_scroll(win).0;
if ms > 0 && new_top != prev_top {
self.scroll_anim = Some(crate::app::ScrollAnim {
win_id: win,
start_top: prev_top,
target_top: new_top,
started_at: std::time::Instant::now(),
duration: std::time::Duration::from_millis(ms as u64),
});
}
}
}
self.pending_recompute = true;
}
}
Event::Mouse(me) => {
let _ = self.handle_mouse(me);
}
Event::Resize(w, h) => {
let vp = self.active_editor_mut().host_mut().viewport_mut();
vp.width = w;
vp.height = h.saturating_sub(STATUS_LINE_HEIGHT);
}
Event::FocusGained => {
self.checktime_all();
}
Event::Paste(text) => {
self.handle_paste(text);
}
_ => {}
}
// After every key tick (both consumed-inline and fall-through
// paths), check whether the explorer buffer changed and apply any
// pending filesystem ops. The dirty_gen guard and Normal-mode
// check make this a no-op on most ticks.
self.maybe_reconcile_explorer();
// Drain any additional events currently ready (e.g. a burst
// of mouse-wheel scrolls) before running the deferred sync
// query. Each scroll handler set `pending_recompute = true`
// instead of firing `recompute_and_install` synchronously,
// so we collapse the whole burst into one sync query install.
let t_drain = std::time::Instant::now();
let mut drained = 0usize;
while event::poll(Duration::from_millis(0)).unwrap_or(false) {
drained += 1;
if let Ok(extra) = event::read() {
match extra {
Event::Key(k) => {
// Kitty-protocol legacy normalization (drain-loop
// mirror of the primary path): in the vim discipline,
// map disambiguated Ctrl+[ / Ctrl+I / Ctrl+M back to
// Esc / Tab / Enter so muscle-memory survives. VSCode
// keeps the raw keys (Ctrl+[ = outdent, etc.).
let k = if self.keybinding_mode == hjkl_engine::KeybindingMode::Vim {
hjkl_kitty::normalize_legacy(k)
} else {
k
};
// ── VSCode early intercept (drain loop mirror) ──
// Shared choke point with the primary path (#265 G3 B3).
if self.try_vscode_intercept(k) {
continue;
}
match self.handle_keypress(k) {
KeyOutcome::Break => {
self.exit_requested = true;
break;
}
KeyOutcome::Continue => continue,
KeyOutcome::FallThrough => {
self.scroll_anim = None;
let prev_top = self.window_scroll(self.focused_window()).0;
let mode_was_insert =
self.active_editor().vim_mode() == VimMode::Insert;
if mode_was_insert {
self.dispatch_insert_key(k);
self.active_editor_mut().emit_cursor_shape_if_changed();
} else {
hjkl_vim_tui::handle_key(self.active_editor_mut(), k);
}
self.sync_viewport_from_editor();
if self.active_editor_mut().take_dirty() {
let elapsed =
self.active_mut().refresh_dirty_against_saved();
self.last_signature_us = elapsed;
if self.active().dirty {
self.active_mut().is_new_file = false;
}
}
let bid = self.active().buffer_id;
if self.active_editor_mut().take_content_reset() {
self.handle_active_content_reset(bid);
}
let edits = self.active_editor_mut().take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(bid, &edits);
self.active_editor_mut()
.shift_syntax_spans_for_edits(&edits);
}
self.lsp_notify_change_active(&edits);
self.rebase_sibling_cursors(&edits);
// Drain pending fold ops (drain-loop mirror of
// the primary key arm above).
let _ = self.active_editor_mut().take_fold_ops();
{
let hint = self.active_editor_mut().take_scroll_anim_hint();
if hint {
let ms =
self.active_editor().settings().scroll_duration_ms;
let win = self.focused_window();
let new_top = self.window_scroll(win).0;
if ms > 0 && new_top != prev_top {
self.scroll_anim = Some(crate::app::ScrollAnim {
win_id: win,
start_top: prev_top,
target_top: new_top,
started_at: std::time::Instant::now(),
duration: std::time::Duration::from_millis(
ms as u64,
),
});
}
}
}
self.pending_recompute = true;
}
}
}
Event::Mouse(me2) => {
let _ = self.handle_mouse(me2);
}
Event::Resize(w, h) => {
let vp = self.active_editor_mut().host_mut().viewport_mut();
vp.width = w;
vp.height = h.saturating_sub(STATUS_LINE_HEIGHT);
}
Event::FocusGained => {
self.checktime_all();
}
Event::Paste(text) => {
self.handle_paste(text);
}
_ => {}
}
}
}
// Flush deferred recompute once after the drain loop ends.
// Coalesces burst-scrolls (and rapid keystrokes within one
// poll tick) into a single sync query + install.
if drained > 0 {
tracing::debug!(
target: "hjkl::profile",
drained,
drain_us = t_drain.elapsed().as_micros(),
"event drain"
);
}
if self.pending_recompute {
self.pending_recompute = false;
self.recompute_and_install();
}
if self.exit_requested {
break;
}
}
// Graceful exit: remove all swap files so clean sessions leave no stale
// swap behind. Crashes / SIGKILL bypass this block and the swap survives
// for recovery — which is exactly the distinction we want.
self.cleanup_swaps_on_exit();
Ok(())
}
/// Tick the Phase 5 hover timer.
///
/// Called on every poll-timeout tick AND on every `MouseEventKind::Moved`
/// event so the RPC fires promptly when the mouse has been stationary for
/// [`HOVER_DELAY`]. If the timer is armed, the cell is in a Code zone, and
/// the 500ms threshold has elapsed, sends the LSP hover RPC once.
pub(crate) fn tick_hover_timer(&mut self) {
// If a popup is already showing, nothing to do.
if self.hover_popup.is_some() {
return;
}
// Suppress hover firing while any overlay is on top of the editor —
// a hover RPC for the doc cell BEHIND the overlay would show the
// popup through the menu/picker/command field. Drop the timer too
// so it doesn't fire the instant the overlay closes.
if self.overlay_active() {
self.hover_timer = None;
return;
}
let (cell, should_fire) = match &self.hover_timer {
Some(h) if !h.request_sent && h.started_at.elapsed() >= HOVER_DELAY => (h.cell, true),
_ => return,
};
if !should_fire {
return;
}
// In BLAME mode, hovering ANY row — including the virtual commit-header
// border — shows the full commit message in the markdown popup. Resolve
// the commit's doc row via the box-plan-aware helper (hit_test_zone
// returns None on border rows, so it can't be used here).
if self.active_editor().is_blame() {
if let Some(doc_row) = crate::app::mouse::blame_hover_doc_row(self, cell.0, cell.1) {
self.show_blame_commit_hover(doc_row, cell);
if let Some(h) = self.hover_timer.as_mut() {
h.request_sent = true;
}
}
return;
}
// Otherwise a code cell triggers an LSP hover.
if let crate::app::mouse::Zone::Code {
win_id,
doc_row,
doc_col,
} = crate::app::mouse::hit_test_zone(self, cell.0, cell.1)
{
// Skip (and clear the timer) when the hovered window's buffer has
// hover popups disabled — avoids spurious LSP requests over the
// explorer or other special scratch buffers.
let hover_disabled = self
.windows
.get(win_id)
.and_then(|w| w.as_ref())
.map(|w| !self.slots[w.slot].features.hover)
.unwrap_or(false);
if hover_disabled {
self.hover_timer = None;
return;
}
self.lsp_hover_at_doc(doc_row, doc_col);
if let Some(h) = self.hover_timer.as_mut() {
h.request_sent = true;
}
}
}
}