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
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
//! `App` — owns the editor + host, drives the event loop.
use anyhow::Result;
use hjkl_buffer::Buffer;
use hjkl_engine::{BufferEdit, Host};
use hjkl_engine::{CursorShape, Editor, Options, VimMode};
use hjkl_form::TextFieldEditor;
use hjkl_keymap::Keymap;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime};
use crate::keymap_actions::AppAction;
use crate::git_worker::GitSignsWorker;
use crate::host::TuiHost;
use crate::syntax::{self, BufferId, SyntaxLayer};
use std::collections::HashSet;
mod buffer_ops;
mod engine_actions;
mod event_loop;
mod ex_dispatch;
pub(crate) mod ex_host_cmds;
pub(crate) mod keymap;
pub mod lsp_glue;
pub(crate) mod mappings_dispatch;
pub mod mouse;
mod pending_actions;
mod picker_glue;
mod prompt;
mod syntax_glue;
#[cfg(test)]
mod tests;
pub mod window;
use crate::completion::Completion;
/// Height reserved for the status line at the bottom of the screen.
pub const STATUS_LINE_HEIGHT: u16 = 1;
/// How long a grammar-load failure stays visible in the status line before
/// auto-expiring.
const GRAMMAR_ERR_TTL: Duration = Duration::from_secs(5);
/// A grammar-load failure surfaced as a transient status message.
#[derive(Clone)]
pub(crate) struct GrammarLoadError {
pub name: String,
pub message: String,
pub at: Instant,
}
impl GrammarLoadError {
pub fn is_expired(&self) -> bool {
self.at.elapsed() >= GRAMMAR_ERR_TTL
}
}
/// Height of the unified top bar (buffers left, tabs right) at the top of the
/// screen, when shown (either more than one slot or more than one tab).
pub const TOP_BAR_HEIGHT: u16 = 1;
/// Resolve a path for buffer-list matching. Two paths that point to
/// the same file should compare equal here even when one is relative
/// and the other absolute. We try `canonicalize` first (only works for
/// files that exist on disk) and fall back to lexical absolutization
/// for new-file paths.
fn canon_for_match(p: &std::path::Path) -> PathBuf {
if let Ok(c) = std::fs::canonicalize(p) {
return c;
}
if p.is_absolute() {
p.to_path_buf()
} else if let Ok(cwd) = std::env::current_dir() {
cwd.join(p)
} else {
p.to_path_buf()
}
}
/// Hash + byte-length of the buffer's canonical line content (lines
/// joined by `\n` — same shape as what `:w` writes, modulo the trailing
/// newline). Used to detect "buffer matches the saved snapshot" so undo
/// back to the saved state clears the dirty flag.
fn buffer_signature(editor: &Editor<Buffer, TuiHost>) -> (u64, usize) {
let mut hasher = DefaultHasher::new();
let mut len = 0usize;
let lines = editor.buffer().lines();
for (i, l) in lines.iter().enumerate() {
if i > 0 {
b'\n'.hash(&mut hasher);
len += 1;
}
l.hash(&mut hasher);
len += l.len();
}
(hasher.finish(), len)
}
/// Per-mode mouse-enable flags — mirrors Vim's `:set mouse=<flags>`.
///
/// Default (all enabled) corresponds to `mouse=a`. Set individual fields to
/// `false` to disable mouse in that mode. The event loop checks
/// [`App::mouse_flags`] via [`mouse_enabled_for`] before processing any mouse
/// event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseFlags {
/// Mouse active in Normal mode (`n`).
pub normal: bool,
/// Mouse active in Visual / VisualLine / VisualBlock mode (`v`).
pub visual: bool,
/// Mouse active in Insert mode (`i`).
pub insert: bool,
/// Mouse active in Command-line / prompt mode (`c`).
pub command: bool,
/// Mouse active in Help buffers (`h`). Parsed for compatibility but unused today.
pub help: bool,
}
impl MouseFlags {
/// All modes enabled — equivalent to `mouse=a`.
pub fn all() -> Self {
Self {
normal: true,
visual: true,
insert: true,
command: true,
help: true,
}
}
/// All modes disabled — equivalent to `set nomouse` / `mouse=`.
pub fn none() -> Self {
Self {
normal: false,
visual: false,
insert: false,
command: false,
help: false,
}
}
/// Parse a Vim-style flags string (`"a"`, `"nvi"`, `""`, …).
///
/// - `"a"` → all modes on.
/// - Each char `n/v/i/c/h` enables the corresponding mode.
/// - Unknown chars are silently ignored (forward-compat).
/// - Empty string → all modes off.
pub fn from_flags(s: &str) -> Self {
if s == "a" {
return Self::all();
}
let mut f = Self::none();
for c in s.chars() {
match c {
'n' => f.normal = true,
'v' => f.visual = true,
'i' => f.insert = true,
'c' => f.command = true,
'h' => f.help = true,
'a' => {
// 'a' anywhere in string still means all.
return Self::all();
}
_ => {}
}
}
f
}
/// Return a canonical flags string suitable for `:set mouse?` display.
pub fn as_flags_str(&self) -> String {
if self.normal && self.visual && self.insert && self.command && self.help {
return "a".into();
}
let mut s = String::new();
if self.normal {
s.push('n');
}
if self.visual {
s.push('v');
}
if self.insert {
s.push('i');
}
if self.command {
s.push('c');
}
if self.help {
s.push('h');
}
s
}
}
impl Default for MouseFlags {
fn default() -> Self {
Self::all()
}
}
/// Return `true` when mouse events should be processed for the given Vim mode.
///
/// Used by the event loop at the top of `Event::Mouse` to gate events by mode.
/// Extracted as a pure function so it can be unit-tested without a running App.
pub fn mouse_enabled_for(mode: VimMode, flags: &MouseFlags) -> bool {
match mode {
VimMode::Normal => flags.normal,
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock => flags.visual,
VimMode::Insert => flags.insert,
}
}
/// Whether the on-disk file is in sync with what was last loaded/saved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiskState {
/// File matches what we loaded/saved last.
Synced,
/// File changed on disk since last load/save (and buffer is dirty — no auto-reload).
ChangedOnDisk,
/// File no longer exists on disk.
DeletedOnDisk,
}
/// Direction of an active host-driven search prompt. `/` opens a
/// forward prompt, `?` opens a backward one. The direction is recorded
/// alongside [`App::search_field`] so the commit path can call the
/// matching `Editor::search_advance_*` and persist the direction onto
/// the engine's `last_search_forward` for future `n` / `N` repeats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchDir {
Forward,
Backward,
}
/// Cardinal direction for window navigation (`<C-h/j/k/l>` / `TmuxNavigate`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavDir {
Left,
Down,
Up,
Right,
}
/// LSP diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiagSeverity {
Error = 1,
Warning = 2,
Info = 3,
Hint = 4,
}
/// A single LSP diagnostic stored on a `BufferSlot`.
#[derive(Debug, Clone)]
pub struct LspDiag {
/// 0-based start row.
pub start_row: usize,
/// 0-based start char-column.
pub start_col: usize,
/// 0-based end row.
pub end_row: usize,
/// 0-based end char-column.
pub end_col: usize,
pub severity: DiagSeverity,
pub message: String,
pub source: Option<String>,
pub code: Option<String>,
}
/// Snapshot of a running LSP server's state, tracked by the app.
pub struct LspServerInfo {
pub initialized: bool,
pub capabilities: serde_json::Value,
}
/// Tracks an in-flight LSP request so the response handler knows what to do.
/// Each variant carries the buffer context and cursor origin so the result can
/// be acted on (jump, picker, popup) without re-reading app state at response
/// time (the active buffer may have changed by then).
#[derive(Debug, Clone)]
pub enum LspPendingRequest {
GotoDefinition {
buffer_id: hjkl_lsp::BufferId,
/// 0-based (row, col) of the cursor when the request was sent.
origin: (usize, usize),
},
GotoDeclaration {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
GotoTypeDefinition {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
GotoImplementation {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
GotoReferences {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
Hover {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
/// Mouse-hover variant of `Hover` — result goes to the floating
/// [`HoverPopup`] instead of `info_popup`. Phase 5 mouse support.
HoverAtMouse {
buffer_id: hjkl_lsp::BufferId,
origin: (usize, usize),
},
Completion {
buffer_id: hjkl_lsp::BufferId,
/// 0-based cursor position when the request was sent.
anchor_row: usize,
anchor_col: usize,
},
/// `textDocument/codeAction` — Phase 5.
CodeAction {
buffer_id: hjkl_lsp::BufferId,
anchor_row: usize,
anchor_col: usize,
},
/// `textDocument/rename` — Phase 5.
Rename {
buffer_id: hjkl_lsp::BufferId,
anchor_row: usize,
anchor_col: usize,
new_name: String,
},
/// `textDocument/formatting` — Phase 5.
Format {
buffer_id: hjkl_lsp::BufferId,
/// `None` = full document; `Some((sr, sc, er, ec))` = range (Phase 5 always None).
range: Option<(usize, usize, usize, usize)>,
},
}
/// Per-buffer state. Phase B: App holds `Vec<BufferSlot>` + `active: usize`.
/// Phase C will add bnext / bdelete / switch-or-create.
pub struct BufferSlot {
/// Stable id used to multiplex the SyntaxLayer / Worker.
pub buffer_id: BufferId,
/// The live editor — buffer + FSM + host, all in one.
pub editor: Editor<Buffer, TuiHost>,
/// File path shown in status line and used for `:w` saves.
pub filename: Option<PathBuf>,
/// Persistent dirty flag. Set when `editor.take_dirty()` returns `true`;
/// cleared after a successful `:w` save.
pub dirty: bool,
/// True when a file was requested but not found on disk — shows
/// "[New File]" annotation in the status line until the first edit
/// or successful `:w`.
pub is_new_file: bool,
/// `true` when the current file is in a git repo but not in HEAD —
/// drives the `[Untracked]` status-line tag. Refreshed alongside
/// `git_signs`.
pub is_untracked: bool,
/// Diagnostic gutter signs (tree-sitter ERROR / MISSING) for the
/// current viewport. Refreshed by `recompute_and_install`; read by
/// `render::buffer_pane`.
pub diag_signs: Vec<hjkl_buffer::Sign>,
/// LSP diagnostic gutter signs. Separate from `diag_signs` so the
/// oracle/syntax source can be cleared independently of LSP.
pub diag_signs_lsp: Vec<hjkl_buffer::Sign>,
/// Full LSP diagnostic list for the buffer. Replaced wholesale each
/// time `textDocument/publishDiagnostics` arrives (server is source
/// of truth — empty notification clears all diags).
pub lsp_diags: Vec<LspDiag>,
/// `dirty_gen` of the buffer the last time we sent `textDocument/didChange`
/// to the LSP. `None` = never sent.
pub(crate) last_lsp_dirty_gen: Option<u64>,
/// Git diff signs (`+` / `~` / `_`) against HEAD. Recomputed
/// whenever the buffer's `dirty_gen` advances so unsaved edits
/// show in the gutter live. Filtered to the viewport per-frame
/// in the renderer.
pub git_signs: Vec<hjkl_buffer::Sign>,
/// `dirty_gen` of the buffer when `git_signs` was last rebuilt.
/// `None` = stale, force recompute on next render.
last_git_dirty_gen: Option<u64>,
/// Wall-clock time of the last successful git_signs refresh — used
/// to throttle the libgit2 diff to ~4 Hz during active typing on
/// large files.
last_git_refresh_at: Instant,
/// Wall-clock time of the last syntax recompute+install.
last_recompute_at: Instant,
/// `(dirty_gen, vp_top, vp_height)` snapshot of the last call to
/// `recompute_and_install`. When the next call has identical
/// inputs, the syntax span recompute + install is skipped.
last_recompute_key: Option<(u64, usize, usize)>,
/// Hash + byte-length of the buffer content as it was at the most
/// recent save (or load).
saved_hash: u64,
saved_len: usize,
/// mtime of the file on disk at the most recent load or save.
pub disk_mtime: Option<SystemTime>,
/// Byte length of the file on disk at the most recent load or save.
pub disk_len: Option<u64>,
/// Whether the on-disk file is in sync, changed, or deleted.
pub disk_state: DiskState,
/// Most recent completed viewport-scoped `RenderOutput` for this buffer.
/// Cached so a buffer switch can immediately re-install the last known
/// spans while a fresh parse runs in the background (T3 — per-slot
/// span cache). `None` until the first viewport parse result arrives.
pub(crate) viewport_render_output: Option<crate::syntax::RenderOutput>,
/// Pre-cached spans for the top of the file (`0..min(3*h, line_count)`).
/// Populated after the first cold viewport parse so `gg` never flashes
/// un-highlighted rows even on large files.
pub(crate) top_render_output: Option<crate::syntax::RenderOutput>,
/// Pre-cached spans for the bottom of the file
/// (`line_count - min(3*h, line_count)..line_count`). Populated after
/// the cold viewport parse so `G` never flashes un-highlighted rows.
pub(crate) bottom_render_output: Option<crate::syntax::RenderOutput>,
/// Per-row edit log: each entry is `(dirty_gen, row_range)` where
/// `dirty_gen` is the buffer's `dirty_gen` AFTER the edit landed and
/// `row_range` is the inclusive row range touched by that edit.
///
/// Used by `merge_render_outputs` so rows untouched since a cache's
/// parse are still painted from the cache, avoiding the "white flash"
/// where ALL spans vanish until the background worker returns.
///
/// Capped at 256 entries to bound memory on long sessions.
pub(crate) dirty_rows_log: Vec<(u64, std::ops::RangeInclusive<usize>)>,
}
impl BufferSlot {
/// Snapshot the loaded content so undo-to-saved clears dirty.
fn snapshot_saved(&mut self) {
let (h, l) = buffer_signature(&self.editor);
self.saved_hash = h;
self.saved_len = l;
self.dirty = false;
}
/// Sync `self.dirty` against a fresh content comparison.
fn refresh_dirty_against_saved(&mut self) -> u128 {
let t = std::time::Instant::now();
let (h, l) = buffer_signature(&self.editor);
let elapsed = t.elapsed().as_micros();
self.dirty = h != self.saved_hash || l != self.saved_len;
elapsed
}
}
/// Top-level application state. Everything the event loop and renderer need.
pub struct App {
/// All open buffer slots. Never empty — always at least one slot.
slots: Vec<BufferSlot>,
/// Window list. Indexed by `WindowId`. Entries are `Option<Window>`;
/// closed windows are set to `None` so ids stay stable.
pub windows: Vec<Option<window::Window>>,
/// All open tabs. Each tab owns its own layout tree + focused window.
/// Never empty — always at least one tab.
pub tabs: Vec<window::Tab>,
/// Index of the currently active tab into `tabs`.
pub active_tab: usize,
/// Counter for the next fresh `WindowId`.
next_window_id: window::WindowId,
/// Monotonic counter for fresh `BufferId`s. Slot 0 takes id 0; new
/// slots created via `:e <new-path>` or replacements after `:bd` on
/// the last slot consume the next value.
next_buffer_id: BufferId,
/// The slot that was active just before the most recent `switch_to`
/// call. Used by `<C-^>` / `:b#` to jump to the alternate buffer.
pub prev_active: Option<usize>,
/// Set to `true` when the FSM or Ctrl-C wants to quit.
pub exit_requested: bool,
/// Last ex-command result (Info / Error / write confirmation).
/// Shown in the status line; cleared on next keypress.
pub status_message: Option<String>,
/// Multi-line info popup (e.g. from `:reg`, `:marks`, `:jumps`,
/// `:changes`). When `Some`, rendered as a centered overlay; any
/// keypress dismisses it without dispatching to the editor.
pub info_popup: Option<String>,
/// Active `:` command input. `Some` while the user is typing an ex
/// command. Backed by a vim-grammar [`TextFieldEditor`] so motions
/// (h/l/w/b/dw/diw/...) work inside the prompt.
pub command_field: Option<TextFieldEditor>,
/// Active wildmenu state for the command-line prompt. `None` outside
/// completion (no Tab pressed yet, or after acceptance/cancel).
pub(crate) command_completion: Option<crate::app::prompt::CommandCompletion>,
/// Active `/` (forward) / `?` (backward) search prompt.
pub search_field: Option<TextFieldEditor>,
/// Active picker overlay (file, buffer, grep, …).
pub picker: Option<crate::picker::Picker>,
/// Buffered digit-prefix count for an app-level count prefix (e.g. `5` in
/// `5gt`). Accumulated in Normal mode when no chord prefix is active.
/// Digits are replayed to the engine when the non-digit key is
/// engine-handled, or consumed when the key is app-handled.
pub pending_count: hjkl_vim::CountAccumulator,
/// Direction of the active `search_field`.
pub search_dir: SearchDir,
/// Last cursor shape we emitted to the terminal.
last_cursor_shape: CursorShape,
/// Tree-sitter syntax highlighting layer. Owns the worker thread + the
/// active theme. Multiplexed by BufferId.
syntax: SyntaxLayer,
/// Background worker for git diff-sign computation.
git_worker: GitSignsWorker,
/// Background worker for external formatter invocations (`=` / `==`).
/// Moves blocking subprocess calls off the UI thread (#118).
pub(crate) format_worker: hjkl_mangler::FormatWorker,
/// Buffer ids for which a format job is currently in-flight.
/// Used to show a "formatting…" status indicator and to skip redundant
/// submits (the worker's per-buffer dedup is the hard guarantee; this
/// set is advisory UI state).
pub(crate) format_pending: HashSet<BufferId>,
/// Shared grammar resolver. `Arc` so the syntax layer and every picker
/// source point at the same in-memory `Grammar` cache (one dlopen +
/// query parse per language, app-wide).
pub directory: std::sync::Arc<crate::lang::LanguageDirectory>,
/// App-wide theme (UI chrome + syntax). Loaded once at startup from
/// `themes/{ui,syntax}-dark.toml` baked via include_str!.
pub theme: crate::theme::AppTheme,
/// Per-language `Highlighter` cache used by the picker preview pane
/// (computed via [`Self::preview_spans_for`]). Centralised here so
/// every preview source — files, rg results, open buffers, git diff
/// rows — shares one parser per language for the session. The
/// editor's own syntax pipeline lives on `syntax`; this is for the
/// preview-only highlight path.
pub(crate) preview_highlighters:
std::sync::Mutex<std::collections::HashMap<String, hjkl_bonsai::Highlighter>>,
/// Toggled by `:perf`. When true, render shows last-frame timings.
pub perf_overlay: bool,
pub last_recompute_us: u128,
pub last_install_us: u128,
pub last_signature_us: u128,
pub last_git_us: u128,
pub last_perf: crate::syntax::PerfBreakdown,
/// Counters surfaced in `:perf` so the user can verify cache ratios.
pub recompute_hits: u64,
pub recompute_throttled: u64,
pub recompute_runs: u64,
/// Count of async syntax results dropped because their tagged
/// buffer_id no longer matches the active buffer (race: parse
/// queued before a tab/buffer switch). Surfaced in `:perf` and
/// asserted in the regression test on the install path.
pub syntax_stale_drops: u64,
/// User config (bundled defaults + optional XDG overrides). Tests
/// receive `Config::default()` (the bundled values); main wires the
/// XDG-merged value via [`Self::with_config`] before entering the
/// event loop.
pub config: crate::config::Config,
/// Animated start screen shown when no file argument was given.
/// Cleared (set to `None`) on the first keypress.
pub start_screen: Option<crate::start_screen::StartScreen>,
/// Recent grammar-load failure surfaced as a transient status message.
/// Auto-expires after `GRAMMAR_ERR_TTL` so a stale error doesn't stick.
pub(crate) grammar_load_error: Option<GrammarLoadError>,
/// LSP subsystem handle. `None` when `config.lsp.enabled = false` (default).
pub lsp: Option<hjkl_lsp::LspManager>,
/// Tracks the state of running LSP servers. Populated/updated by
/// `drain_lsp_events` on `ServerInitialized` / `ServerExited`.
pub lsp_state: HashMap<hjkl_lsp::ServerKey, LspServerInfo>,
/// Monotonic counter for allocating request ids sent to the LSP runtime.
pub lsp_next_request_id: i64,
/// Maps app-allocated request id → what the request was for, so the
/// response handler knows how to act on the result.
pub lsp_pending: HashMap<i64, LspPendingRequest>,
/// Active completion popup, if any.
pub completion: Option<Completion>,
/// Code actions from the most recent `textDocument/codeAction` response.
/// The picker uses `ApplyCodeAction(i)` to index into this list.
pub pending_code_actions: Vec<lsp_types::CodeActionOrCommand>,
/// Tracks the first key of the `<C-x><C-o>` omni-completion chord.
/// Set to `true` after `Ctrl-x`; cleared after the next key.
pub pending_ctrl_x: bool,
/// Monotonic instant at which the current prefix was set.
/// `None` when no prefix is pending.
pub pending_prefix_at: Option<std::time::Instant>,
/// `true` when the which-key idle timeout has expired and the popup
/// should be rendered.
pub which_key_active: bool,
/// `true` when the which-key popup is sticky-visible after a Backspace
/// emptied the chord buffer. Stays open showing root entries until any
/// non-Backspace key is pressed.
pub(crate) which_key_sticky: bool,
/// Whether the which-key feature is enabled (from config).
pub which_key_enabled: bool,
/// Idle delay before the which-key popup appears (from config).
pub which_key_delay: std::time::Duration,
/// Side-table of user-registered runtime key maps (for `:map` listing).
/// The trie `app_keymap` owns the actual dispatch; this records what was
/// registered so listing commands don't expose built-in bindings.
pub(crate) user_keymap_records: Vec<keymap::UserKeymapRecord>,
/// Active recursion depth of `AppAction::Replay { recursive: true }`
/// dispatches. Used to bail out of cyclic user maps (`:nmap a a`) before
/// stack overflow. The per-Replay-frame `steps` counter only catches
/// horizontal cycles; this catches vertical (re-entrant) cycles too.
pub(crate) replay_depth: usize,
/// Mouse-capture state. Mirrors the terminal's
/// EnableMouseCapture / DisableMouseCapture mode. Initialised from
/// `config.editor.mouse`; runtime-togglable via `:set [no]mouse`.
/// When false, wheel events fall through to the terminal as
/// synthesised arrow keys.
pub mouse_enabled: bool,
/// Per-mode mouse flags (`:set mouse=<flags>`). Controls which vim modes
/// process mouse events. Default: all modes enabled (`mouse=a`).
pub mouse_flags: MouseFlags,
/// Application-level chord dispatch. Holds Normal-mode bindings for all
/// leader / g / ] / [ / <C-w> sequences.
pub(crate) app_keymap: Keymap<AppAction, keymap::HjklMode>,
/// Background install worker pool shared across all `:Anvil install` calls.
pub anvil_pool: hjkl_anvil::InstallPool,
/// In-flight install handles keyed by tool name.
pub anvil_handles: HashMap<String, hjkl_anvil::InstallHandle>,
/// Per-tool install log lines accumulated from status messages.
pub anvil_log: HashMap<String, Vec<String>>,
/// Embedded anvil tool registry (built once at startup from the baked-in
/// `anvil.toml`; `None` only when the embedded catalog fails to parse).
pub anvil_registry: Option<hjkl_anvil::Registry>,
/// App-level pending chord state. `Some` while a second-key chord (e.g.
/// `r<x>`) is in flight and being driven by `hjkl_vim::step`. Cleared
/// when the reducer emits `Commit` or `Cancel`. When `Some`, the event
/// loop routes the next key through `hjkl_vim::step` instead of the trie.
pub(crate) pending_state: Option<hjkl_vim::PendingState>,
/// Last successfully-dispatched ex command (text body, no leading `:`),
/// used by `@:` to repeat. Phase 5d of kryptic-sh/hjkl#71.
pub(crate) last_ex_command: Option<String>,
/// Double/triple-click state for mouse support (Phase 1 — issue #114).
pub(crate) mouse_click_tracker: mouse::MouseClickTracker,
/// Active right-click context menu (Phase 2, Round A — issue #114).
/// `None` when no menu is open. Floated above all other content by the
/// renderer. Dismissed on Esc, click-outside, or action invocation.
pub(crate) context_menu: Option<crate::menu::ContextMenu>,
/// Floating LSP hover popup (Phase 5 mouse support).
/// Shown after the mouse rests on a Code zone for [`HOVER_DELAY`].
/// Dismissed by mouse move, any key press, or 8-second auto-fade.
pub(crate) hover_popup: Option<crate::hover_popup::HoverPopup>,
/// "Mouse has been resting at this cell since `started_at`" tracker.
/// Reset on any cell change; fires the LSP hover RPC after [`HOVER_DELAY`].
pub(crate) hover_timer: Option<HoverTimer>,
/// Active split-border drag state (Phase 9). `Some` while the user is
/// dragging a split border; `None` otherwise.
pub(crate) border_drag: Option<BorderDrag>,
/// Brief visual flash painted over rows touched by the most recent
/// auto-indent (`=`) operator. `None` when no flash is pending or
/// after [`INDENT_FLASH_DURATION`] has elapsed. Drained by
/// [`Self::indent_flash_active`].
pub(crate) indent_flash: Option<IndentFlash>,
}
/// Tracks how long the mouse has been stationary at a given terminal cell.
/// Used to fire the LSP `textDocument/hover` request after [`HOVER_DELAY`].
pub(crate) struct HoverTimer {
/// Terminal cell (col, row) the mouse is resting on.
pub cell: (u16, u16),
/// When the mouse first arrived at this cell.
pub started_at: Instant,
/// `true` once we've fired the LSP hover RPC — prevents re-sending.
pub request_sent: bool,
}
/// Auto-indent flash duration — single brief on-pulse, no fade, no
/// repeat. 75 ms keeps it snappy and out of the way of further input.
pub(crate) const INDENT_FLASH_DURATION: Duration = Duration::from_millis(75);
/// Visual flash state set immediately after an `=` / `==` / `=G` / Visual-`=`
/// auto-indent operation. The renderer paints a highlight bg over rows
/// `[top, bot]` (inclusive) while `started_at.elapsed() < INDENT_FLASH_DURATION`.
pub(crate) struct IndentFlash {
pub top: usize,
pub bot: usize,
pub started_at: Instant,
}
/// Minimum cell size for each side of a split when drag-resizing (Phase 9).
/// VSplit: each pane must be at least this many columns wide.
/// HSplit: each pane must be at least this many rows tall.
pub(crate) const SPLIT_MIN_SIZE_COLS: u16 = 10;
pub(crate) const SPLIT_MIN_SIZE_ROWS: u16 = 3;
/// Active split-border drag state (Phase 9). Populated on `Down(Left)` when
/// the click lands on a border; cleared on `Up(Left)`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct BorderDrag {
/// Orientation of the split being resized.
pub orientation: mouse::SplitOrientation,
/// Origin of the split's rect (x for VSplit, y for HSplit).
pub split_origin: u16,
/// Total size of the split's rect (width for VSplit, height for HSplit).
pub split_total: u16,
/// Most recent mouse position (column for VSplit, row for HSplit).
pub last_pos: u16,
}
/// Resolve the cursor shape for an active prompt field (`command_field` or
/// `search_field`). Insert mode → Bar; anything else → Block.
fn prompt_cursor_shape(field: &hjkl_form::TextFieldEditor) -> CursorShape {
match field.vim_mode() {
hjkl_form::VimMode::Insert => CursorShape::Bar,
_ => CursorShape::Block,
}
}
/// Build a [`BufferSlot`] from disk content.
///
/// - `path = None` → empty unnamed scratch buffer (used by `:bd` on the
/// last slot; today `open_new_slot`/`App::new` always pass `Some(path)`,
/// but accepting `None` lets future call sites converge here too).
/// - `path = Some(p)` and file missing → `is_new_file = true`,
/// buffer empty, filename retained.
/// - `path = Some(p)` and file unreadable → `Err`.
///
/// Both original call sites used `wait_for_initial_result(150ms)`; that
/// method is kept here as the single canonical timeout.
pub(super) fn build_slot(
syntax: &mut SyntaxLayer,
buffer_id: BufferId,
path: Option<PathBuf>,
config: &crate::config::Config,
) -> Result<BufferSlot, String> {
let mut buffer = Buffer::new();
let mut is_new_file = false;
let mut disk_mtime: Option<SystemTime> = None;
let mut disk_len: Option<u64> = None;
if let Some(ref p) = path {
match std::fs::read_to_string(p) {
Ok(content) => {
// Snapshot disk metadata right after a successful read.
if let Ok(meta) = std::fs::metadata(p) {
disk_mtime = meta.modified().ok();
disk_len = Some(meta.len());
}
let content = content.strip_suffix('\n').unwrap_or(&content);
BufferEdit::replace_all(&mut buffer, content);
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
is_new_file = true;
}
Err(e) => return Err(format!("E484: Can't open file {}: {e}", p.display())),
}
}
let host = TuiHost::new();
// Seed Options from user config — editorconfig overlay (if any) takes
// precedence over the user-config fallback values.
let mut ec_opts = Options {
expandtab: config.editor.expandtab,
tabstop: config.editor.tab_width as u32,
shiftwidth: config.editor.tab_width as u32,
softtabstop: config.editor.tab_width as u32,
..Options::default()
};
if let Some(ref p) = path {
crate::editorconfig::overlay_for_path(&mut ec_opts, p);
}
let mut editor = Editor::new(buffer, host, ec_opts);
if let Ok(size) = crossterm::terminal::size() {
let viewport_height = size.1.saturating_sub(STATUS_LINE_HEIGHT);
let vp = editor.host_mut().viewport_mut();
vp.width = size.0;
vp.height = viewport_height;
// Publish the viewport height to the engine's atomic so any
// pre-event-loop scroll math (e.g. ensure_cursor_in_scrolloff
// after a +/pat startup search) takes the scrolloff path
// instead of the no-margin fallback.
editor.set_viewport_height(viewport_height);
}
// Non-blocking: returns immediately; Loading case is handled by
// poll_grammar_loads each tick.
if let Some(ref p) = path {
let outcome = syntax.set_language_for_path(buffer_id, p);
let _ = outcome; // Outcome handled via poll_grammar_loads for Loading.
}
let (vp_top, vp_height) = {
let vp = editor.host().viewport();
(vp.top_row, vp.height as usize)
};
if let Some(out) = syntax.preview_render(buffer_id, editor.buffer(), vp_top, vp_height) {
editor.install_ratatui_syntax_spans(out.spans);
}
syntax.submit_render(
buffer_id,
editor.buffer(),
vp_top,
vp_height,
crate::syntax::ParseKind::Viewport,
);
let initial_dg = editor.buffer().dirty_gen();
let (key, signs) = if let Some(out) = syntax.wait_for_initial_result(Duration::from_millis(150))
{
let k = out.key;
editor.install_ratatui_syntax_spans(out.spans);
(Some(k), out.signs)
} else {
(Some((initial_dg, vp_top, vp_height)), Vec::new())
};
let _ = editor.take_content_edits();
let _ = editor.take_content_reset();
let mut slot = BufferSlot {
buffer_id,
editor,
filename: path,
dirty: false,
is_new_file,
is_untracked: false,
diag_signs: signs,
diag_signs_lsp: Vec::new(),
lsp_diags: Vec::new(),
last_lsp_dirty_gen: None,
git_signs: Vec::new(),
last_git_dirty_gen: None,
last_git_refresh_at: Instant::now(),
last_recompute_at: Instant::now() - Duration::from_secs(1),
last_recompute_key: key,
saved_hash: 0,
saved_len: 0,
disk_mtime,
disk_len,
disk_state: DiskState::Synced,
viewport_render_output: None,
top_render_output: None,
bottom_render_output: None,
dirty_rows_log: Vec::new(),
};
slot.snapshot_saved();
Ok(slot)
}
/// Build the Normal-mode application keymap for the given leader character.
///
/// Every app-handled chord binding is registered here. The resulting
/// `Keymap<AppAction, keymap::HjklMode>` is stored on [`App`] and consulted by the event loop
/// before forwarding keys to the editor engine.
fn build_app_keymap(leader: char) -> Keymap<AppAction, keymap::HjklMode> {
use keymap::HjklMode as Mode;
let mut km = Keymap::new(leader);
// Timeout matches the which-key delay default; overridden by `with_config`.
km.set_timeout(Duration::from_millis(500));
let bindings: &[(&str, AppAction, &str)] = &[
// ── Prompt / overlay entry (Phase 2 — issue #120) ─────────────────
// These chords are registered in the keymap trie and dispatched via
// dispatch_action, removing the need for inline intercepts in run().
// `:` in Normal mode is gated on pending_state.is_none() at the
// dispatch site (see dispatch_action arm) to preserve `@:` behaviour.
(":", AppAction::OpenCommandPrompt, "open command prompt"),
(
"/",
AppAction::OpenSearchPrompt(SearchDir::Forward),
"search forward",
),
(
"?",
AppAction::OpenSearchPrompt(SearchDir::Backward),
"search backward",
),
("K", AppAction::LspHover, "lsp hover"),
("<C-^>", AppAction::BufferAlt, "alt buffer"),
// <C-6> is the ASCII-terminal alias for <C-^> on some terminals.
("<C-6>", AppAction::BufferAlt, "alt buffer"),
// ── File / buffer / grep pickers ──────────────────────────────────
("<leader><leader>", AppAction::OpenFilePicker, "file picker"),
("<leader>f", AppAction::OpenFilePicker, "file picker"),
("<leader>b", AppAction::OpenBufferPicker, "buffer picker"),
("<leader>/", AppAction::OpenGrepPicker, "grep picker"),
// ── Git sub-commands ───────────────────────────────────────────────
("<leader>gs", AppAction::GitStatus, "git status"),
("<leader>gl", AppAction::GitLog, "git log"),
("<leader>gb", AppAction::GitBranch, "git branches"),
("<leader>gB", AppAction::GitFileHistory, "git file history"),
("<leader>gS", AppAction::GitStashes, "git stashes"),
("<leader>gt", AppAction::GitTags, "git tags"),
("<leader>gr", AppAction::GitRemotes, "git remotes"),
// ── LSP / diagnostics ─────────────────────────────────────────────
("<leader>d", AppAction::ShowDiagAtCursor, "show diagnostic"),
("<leader>ca", AppAction::LspCodeActions, "code actions"),
("<leader>rn", AppAction::LspRename, "rename symbol"),
// ── g-prefix ──────────────────────────────────────────────────────
// NOTE: bare `g` is bound separately below as BeginPendingAfterG.
// The app-level g-chord actions (gt, gd, etc.) are dispatched from
// the AfterGChord arm in event_loop.rs rather than the trie, so
// that a bare `g` can immediately set pending state without waiting
// for the trie timeout (Ambiguous resolution).
// ── ] / [ bracket motions ─────────────────────────────────────────
("]b", AppAction::BufferNext, "next buffer"),
("[b", AppAction::BufferPrev, "prev buffer"),
("]d", AppAction::DiagNext, "next diagnostic"),
("[d", AppAction::DiagPrev, "prev diagnostic"),
("]D", AppAction::DiagNextError, "next error"),
("[D", AppAction::DiagPrevError, "prev error"),
// ── <C-w> window motions ──────────────────────────────────────────
("<C-w>h", AppAction::FocusLeft, "focus left"),
("<C-w>j", AppAction::FocusBelow, "focus down"),
("<C-w>k", AppAction::FocusAbove, "focus up"),
("<C-w>l", AppAction::FocusRight, "focus right"),
("<C-w>w", AppAction::FocusNext, "focus next"),
("<C-w>W", AppAction::FocusPrev, "focus prev"),
("<C-w>c", AppAction::CloseFocusedWindow, "close window"),
("<C-w>q", AppAction::QuitOrClose, "quit/close"),
("<C-w>o", AppAction::OnlyFocusedWindow, "close others"),
("<C-w>x", AppAction::SwapWithSibling, "swap with sibling"),
("<C-w>r", AppAction::SwapWithSibling, "swap with sibling"),
("<C-w>R", AppAction::SwapWithSibling, "swap with sibling"),
("<C-w>T", AppAction::MoveWindowToNewTab, "move to new tab"),
("<C-w>n", AppAction::NewSplit, "new split"),
("<C-w>+", AppAction::ResizeHeight(1), "taller"),
("<C-w>-", AppAction::ResizeHeight(-1), "shorter"),
("<C-w><gt>", AppAction::ResizeWidth(1), "wider"),
("<C-w><lt>", AppAction::ResizeWidth(-1), "narrower"),
("<C-w>=", AppAction::EqualizeLayout, "equalize"),
("<C-w>_", AppAction::MaximizeHeight, "maximize height"),
("<C-w>|", AppAction::MaximizeWidth, "maximize width"),
];
for (chord_str, action, desc) in bindings {
if let Err(e) = km.add(Mode::Normal, chord_str, action.clone(), desc) {
// Should never fail with our static strings, but log rather than panic.
eprintln!("hjkl: keymap.add({chord_str:?}) failed: {e}");
}
}
// ── pending-state chords ───────────────────────────────────────────────
// `r<x>` — begin Replace pending state. Bound in both Normal and Visual so
// the trie intercepts `r` before the engine FSM sees it.
let replace_action = AppAction::BeginPendingReplace { count: 1 };
for mode in [Mode::Normal, Mode::Visual] {
if let Err(e) = km.add(mode, "r", replace_action.clone(), "replace char") {
eprintln!("hjkl: keymap.add(r) failed: {e}");
}
}
// `f<x>` / `F<x>` / `t<x>` / `T<x>` — bare find chords, migrated to
// hjkl-vim's PendingState::Find reducer. Bound in Normal and Visual only.
// Operator-pending find (`df<x>`, etc.) still goes through the engine FSM.
for (key, forward, till, desc) in [
("f", true, false, "find char forward"),
("F", false, false, "find char backward"),
("t", true, true, "till char forward"),
("T", false, true, "till char backward"),
] {
let action = AppAction::BeginPendingFind {
forward,
till,
count: 1,
};
for mode in [Mode::Normal, Mode::Visual] {
if let Err(e) = km.add(mode, key, action.clone(), desc) {
eprintln!("hjkl: keymap.add({key}) failed: {e}");
}
}
}
// `g<x>` — bare g-prefix chord, migrated to hjkl-vim's
// PendingState::AfterG reducer. Bound in Normal + all three visual
// modes so `gg` (and other g-chords) work consistently in
// visual/visual-line/visual-block. Operator-pending g (`dgU`, etc.)
// and the engine's internal `Pending::G` / `Pending::OpG` still go
// through the engine FSM.
let after_g_action = AppAction::BeginPendingAfterG { count: 1 };
for mode in [
Mode::Normal,
Mode::Visual,
Mode::VisualLine,
Mode::VisualBlock,
] {
if let Err(e) = km.add(mode, "g", after_g_action.clone(), "g-prefix chord") {
eprintln!("hjkl: keymap.add(g) failed: {e}");
}
}
// `z<x>` — bare z-prefix chord, migrated to hjkl-vim's
// PendingState::AfterZ reducer. Bound in Normal + all three visual
// modes for parity with `g`. Operator-pending z (`zf{motion}`) and
// the engine's internal `Pending::Z` still go through the engine
// FSM for non-visual `zf`.
let after_z_action = AppAction::BeginPendingAfterZ { count: 1 };
for mode in [
Mode::Normal,
Mode::Visual,
Mode::VisualLine,
Mode::VisualBlock,
] {
if let Err(e) = km.add(mode, "z", after_z_action.clone(), "z-prefix chord") {
eprintln!("hjkl: keymap.add(z) failed: {e}");
}
}
// `d` / `y` / `c` / `>` / `<` — bare op-pending entry from Normal mode,
// migrated to hjkl-vim's PendingState::AfterOp reducer. Bound in Normal
// mode only. Visual-mode `d`/`y`/`c`/`>`/`<` execute inline through the
// engine FSM and are NOT intercepted here.
//
// The `>` and `<` chars need quoting in the chord string per hjkl-keymap
// notation (`<gt>` and `<lt>`).
for (key, op, desc) in [
("d", hjkl_vim::OperatorKind::Delete, "delete operator"),
("y", hjkl_vim::OperatorKind::Yank, "yank operator"),
("c", hjkl_vim::OperatorKind::Change, "change operator"),
("<gt>", hjkl_vim::OperatorKind::Indent, "indent operator"),
("<lt>", hjkl_vim::OperatorKind::Outdent, "outdent operator"),
(
"=",
hjkl_vim::OperatorKind::AutoIndent,
"auto-indent operator",
),
] {
let action = AppAction::BeginPendingAfterOp { op, count1: 1 };
if let Err(e) = km.add(Mode::Normal, key, action, desc) {
eprintln!("hjkl: keymap.add({key}) failed: {e}");
}
}
// Visual-mode operators — fire inline against the current selection.
// `d` / `y` / `c` / `>` / `<` bound in HjklMode::Visual (covers Visual,
// VisualLine, and VisualBlock per the mode-collapse in keymap.rs:125).
//
// All three modes (Visual, VisualLine, VisualBlock) route through the
// public range-mutation primitives. Phase 4e follow-ups closed the gaps:
// - pending_register() getter exposed (Visual register honors "a prefix)
// - run_operator_over_range linewise guard fixed (VisualLine single-row)
// - delete_block/yank_block/change_block/indent_block exposed (VisualBlock)
for (key, op, desc) in [
("d", hjkl_vim::OperatorKind::Delete, "delete selection"),
("y", hjkl_vim::OperatorKind::Yank, "yank selection"),
("c", hjkl_vim::OperatorKind::Change, "change selection"),
("<gt>", hjkl_vim::OperatorKind::Indent, "indent selection"),
("<lt>", hjkl_vim::OperatorKind::Outdent, "outdent selection"),
(
"=",
hjkl_vim::OperatorKind::AutoIndent,
"auto-indent selection",
),
] {
let action = AppAction::VisualOp { op, count: 1 };
if let Err(e) = km.add(Mode::Visual, key, action, desc) {
eprintln!("hjkl: keymap.add({key} Visual) failed: {e}");
}
}
// `"<reg>` — register-prefix chord in Normal mode only. Visual-mode `"`
// is not intercepted here; the engine FSM handles any Visual-mode `"`
// input directly (there is no visual-register-select path in the engine).
// Bound Normal-only, matching how vim treats `"` in Normal vs Visual mode.
if let Err(e) = km.add(
Mode::Normal,
"\"",
AppAction::BeginPendingSelectRegister,
"register-prefix chord",
) {
eprintln!("hjkl: keymap.add(\\\") failed: {e}");
}
// `m<x>` — mark-set chord. Normal mode only (vim's `m` is not meaningful
// in Visual mode). The engine FSM arms for `m` in Normal mode are kept
// intact for macro-replay defensive coverage (deletion in Phase 6).
if let Err(e) = km.add(
Mode::Normal,
"m",
AppAction::BeginPendingSetMark,
"set mark chord",
) {
eprintln!("hjkl: keymap.add(m) failed: {e}");
}
// `'<x>` — mark-goto-line chord. Normal mode only.
if let Err(e) = km.add(
Mode::Normal,
"'",
AppAction::BeginPendingGotoMarkLine,
"goto mark linewise chord",
) {
eprintln!("hjkl: keymap.add(') failed: {e}");
}
// `` `<x> `` — mark-goto-char chord. Normal + all three Visual modes.
// In Visual mode, `` ` `` jumps the cursor to a mark charwise while keeping
// the selection active (matches engine's pre-existing vim.rs:2058-2066
// behaviour). The engine FSM arms for `` ` `` are kept for macro-replay.
for mode in [
Mode::Normal,
Mode::Visual,
Mode::VisualLine,
Mode::VisualBlock,
] {
if let Err(e) = km.add(
mode,
"`",
AppAction::BeginPendingGotoMarkChar,
"goto mark charwise chord",
) {
eprintln!("hjkl: keymap.add(`) failed: {e}");
}
}
// ── Phase 3a: char + line motions via hjkl-vim keymap path ───────────
// Bound in Normal, Visual, VisualLine, and VisualBlock. Engine FSM arms
// for these keys are kept intact for macro-replay defensive coverage.
for (chord, kind, desc) in [
("h", hjkl_vim::MotionKind::CharLeft, "char left"),
("<BS>", hjkl_vim::MotionKind::CharLeft, "char left"),
("l", hjkl_vim::MotionKind::CharRight, "char right"),
("<Space>", hjkl_vim::MotionKind::CharRight, "char right"),
("j", hjkl_vim::MotionKind::LineDown, "line down"),
("k", hjkl_vim::MotionKind::LineUp, "line up"),
(
"+",
hjkl_vim::MotionKind::FirstNonBlankDown,
"next line first non-blank",
),
(
"-",
hjkl_vim::MotionKind::FirstNonBlankUp,
"prev line first non-blank",
),
("w", hjkl_vim::MotionKind::WordForward, "word forward"),
(
"W",
hjkl_vim::MotionKind::BigWordForward,
"BIG word forward",
),
("b", hjkl_vim::MotionKind::WordBackward, "word back"),
("B", hjkl_vim::MotionKind::BigWordBackward, "BIG word back"),
("e", hjkl_vim::MotionKind::WordEnd, "word end"),
("E", hjkl_vim::MotionKind::BigWordEnd, "BIG word end"),
// Phase 3c: line-anchor motions.
("0", hjkl_vim::MotionKind::LineStart, "line start"),
("<Home>", hjkl_vim::MotionKind::LineStart, "line start"),
("^", hjkl_vim::MotionKind::FirstNonBlank, "first non-blank"),
("$", hjkl_vim::MotionKind::LineEnd, "line end"),
("<End>", hjkl_vim::MotionKind::LineEnd, "line end"),
// Phase 3d: doc-level motion.
("G", hjkl_vim::MotionKind::GotoLine, "goto line"),
// Phase 3e: find-repeat motions.
(";", hjkl_vim::MotionKind::FindRepeat, "find repeat"),
(
",",
hjkl_vim::MotionKind::FindRepeatReverse,
"find repeat reverse",
),
// Phase 3f: bracket-match motion.
("%", hjkl_vim::MotionKind::BracketMatch, "match bracket"),
// Phase 3g: scroll / viewport motions.
// NOTE: H and L are registered separately below (BufferCycleH/L for
// Normal mode; Motion::Viewport* for Visual modes). Removed from this
// array so they don't accidentally bind in Normal via the four-mode loop.
("M", hjkl_vim::MotionKind::ViewportMiddle, "viewport middle"),
(
"<C-d>",
hjkl_vim::MotionKind::HalfPageDown,
"half page down",
),
("<C-u>", hjkl_vim::MotionKind::HalfPageUp, "half page up"),
(
"<C-f>",
hjkl_vim::MotionKind::FullPageDown,
"full page down",
),
("<C-b>", hjkl_vim::MotionKind::FullPageUp, "full page up"),
] {
let action = AppAction::Motion { kind, count: 1 };
for mode in [
Mode::Normal,
Mode::Visual,
Mode::VisualLine,
Mode::VisualBlock,
] {
if let Err(e) = km.add(mode, chord, action.clone(), desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
}
// ── H / L viewport motions for Visual modes (issue #120 Phase 3) ─────
// In Normal mode H/L are registered below as BufferCycleH/L (the action
// checks slots.len() at dispatch time). In all Visual modes H/L remain
// viewport motions — no buffer-cycle semantics in Visual.
for (chord, kind, desc) in [
("H", hjkl_vim::MotionKind::ViewportTop, "viewport top"),
("L", hjkl_vim::MotionKind::ViewportBottom, "viewport bottom"),
] {
let action = AppAction::Motion { kind, count: 1 };
for mode in [Mode::Visual, Mode::VisualLine, Mode::VisualBlock] {
if let Err(e) = km.add(mode, chord, action.clone(), desc) {
eprintln!("hjkl: keymap.add({chord:?} visual) failed: {e}");
}
}
}
// ── H / L buffer cycle (Normal mode, issue #120 Phase 3) ─────────────
// BufferCycleH/L dispatch checks slots.len() at call time:
// slots > 1 → buffer_prev / buffer_next
// single slot → apply_motion(ViewportTop/Bottom, count) directly
// This replaces the inline H/L intercept that checked slots.len() before
// forwarding to the engine.
if let Err(e) = km.add(
Mode::Normal,
"H",
AppAction::BufferCycleH,
"prev buffer or viewport top",
) {
eprintln!("hjkl: keymap.add(H Normal) failed: {e}");
}
if let Err(e) = km.add(
Mode::Normal,
"L",
AppAction::BufferCycleL,
"next buffer or viewport bottom",
) {
eprintln!("hjkl: keymap.add(L Normal) failed: {e}");
}
// ── <C-h/j/k/l> window focus + tmux fallback (issue #120 Phase 3) ───
// TmuxNavigate dispatch checks whether a neighbour exists:
// neighbour present → focus_left/below/above/right
// no neighbour, $TMUX set → tmux select-pane
// no neighbour, no tmux → no-op
// <C-Backspace> is an alias for <C-h> on some terminals (mirrors the
// original inline intercept's `key.code == KeyCode::Backspace` arm).
for (chord, dir, desc) in [
("<C-h>", NavDir::Left, "focus left or tmux left"),
("<C-j>", NavDir::Down, "focus down or tmux down"),
("<C-k>", NavDir::Up, "focus up or tmux up"),
("<C-l>", NavDir::Right, "focus right or tmux right"),
// <C-BS> is the alias for <C-h> delivered by some terminals (crossterm
// decodes it as Backspace+CONTROL rather than Char('h')+CONTROL).
("<C-BS>", NavDir::Left, "focus left or tmux left"),
] {
if let Err(e) = km.add(Mode::Normal, chord, AppAction::TmuxNavigate(dir), desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
// ── Phase 5b: macro record / play chord entry points ─────────────────
// `q` — record-macro or stop-recording gate (QChord handles the branch).
// Normal-mode only: macros cannot be started or stopped in Visual mode.
// Engine FSM arms for `q` are kept for macro-replay defensive coverage.
if let Err(e) = km.add(
Mode::Normal,
"q",
AppAction::QChord { count: 1 },
"record macro / stop recording",
) {
eprintln!("hjkl: keymap.add(q) failed: {e}");
}
// `@` — begin play-macro chord. Normal-mode only.
// Engine FSM arms for `@` are kept for macro-replay defensive coverage.
if let Err(e) = km.add(
Mode::Normal,
"@",
AppAction::BeginPendingPlayMacro { count: 1 },
"play macro chord",
) {
eprintln!("hjkl: keymap.add(@) failed: {e}");
}
// ── Phase 5c: dot-repeat ─────────────────────────────────────────────
// `.` replays the last buffered change. Normal-mode only.
// Engine FSM `.` arm stays for macro-replay defensive coverage.
if let Err(e) = km.add(
Mode::Normal,
".",
AppAction::DotRepeat { count: 1 },
"repeat last change",
) {
eprintln!("hjkl: keymap.add(.) failed: {e}");
}
// ── Phase 6.4: insert-mode entry ─────────────────────────────────────
// Normal mode only. Engine FSM arms kept for macro-replay coverage.
for (chord, action, desc) in [
(
"i",
AppAction::EnterInsertI { count: 1 },
"insert before cursor",
),
(
"I",
AppAction::EnterInsertShiftI { count: 1 },
"insert at line start",
),
(
"a",
AppAction::EnterInsertA { count: 1 },
"append after cursor",
),
(
"A",
AppAction::EnterInsertShiftA { count: 1 },
"append at line end",
),
("o", AppAction::EnterInsertO { count: 1 }, "open line below"),
(
"O",
AppAction::EnterInsertShiftO { count: 1 },
"open line above",
),
(
"R",
AppAction::EnterReplace { count: 1 },
"enter replace mode",
),
] {
if let Err(e) = km.add(Mode::Normal, chord, action, desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
// ── Phase 6.4: char / line mutation ops ──────────────────────────────
// Normal mode only. Engine FSM arms kept for macro-replay coverage.
for (chord, action, desc) in [
(
"x",
AppAction::DeleteCharForward { count: 1 },
"delete char forward",
),
(
"X",
AppAction::DeleteCharBackward { count: 1 },
"delete char backward",
),
(
"s",
AppAction::SubstituteChar { count: 1 },
"substitute char",
),
(
"S",
AppAction::SubstituteLine { count: 1 },
"substitute line",
),
("D", AppAction::DeleteToEol, "delete to end of line"),
("C", AppAction::ChangeToEol, "change to end of line"),
(
"Y",
AppAction::YankToEol { count: 1 },
"yank to end of line",
),
("J", AppAction::JoinLine { count: 1 }, "join lines"),
("~", AppAction::ToggleCase { count: 1 }, "toggle case"),
(
"p",
AppAction::PasteAfter { count: 1 },
"paste after cursor",
),
(
"P",
AppAction::PasteBefore { count: 1 },
"paste before cursor",
),
] {
if let Err(e) = km.add(Mode::Normal, chord, action, desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
// ── Phase 6.4: undo / redo ────────────────────────────────────────────
// `u` undo in Normal mode. `<C-r>` redo in Normal mode only —
// Insert-mode `<C-r>` goes through the engine FSM and is not intercepted.
if let Err(e) = km.add(Mode::Normal, "u", AppAction::Undo, "undo") {
eprintln!("hjkl: keymap.add(u) failed: {e}");
}
if let Err(e) = km.add(Mode::Normal, "<C-r>", AppAction::Redo, "redo") {
eprintln!("hjkl: keymap.add(<C-r>) failed: {e}");
}
// ── Phase 6.4: jumplist ───────────────────────────────────────────────
// `<C-o>` / `<C-i>` bound in Normal mode only.
// Engine FSM arms kept for macro-replay coverage.
if let Err(e) = km.add(
Mode::Normal,
"<C-o>",
AppAction::JumpBack { count: 1 },
"jump back",
) {
eprintln!("hjkl: keymap.add(<C-o>) failed: {e}");
}
// Tab in Normal mode = <C-i> (vim aliases them). Crossterm delivers the
// actual Tab key as KeyCode::Tab, not as Char('i')+CTRL, so we bind <Tab>
// here. The engine FSM also handles the Tab code path for macro-replay
// defensive coverage.
if let Err(e) = km.add(
Mode::Normal,
"<Tab>",
AppAction::JumpForward { count: 1 },
"jump forward",
) {
eprintln!("hjkl: keymap.add(<Tab>) failed: {e}");
}
// ── Phase 6.4: scroll-line ops ────────────────────────────────────────
// `<C-e>` / `<C-y>` — scroll viewport without moving cursor.
// Bound in Normal mode only. (Phase 3g already bound <C-d>/<C-u>/<C-f>/<C-b>
// as Motion variants; those are kept intact — no conflict.)
use hjkl_engine::ScrollDir;
if let Err(e) = km.add(
Mode::Normal,
"<C-e>",
AppAction::ScrollLine {
dir: ScrollDir::Down,
count: 1,
},
"scroll line down",
) {
eprintln!("hjkl: keymap.add(<C-e>) failed: {e}");
}
if let Err(e) = km.add(
Mode::Normal,
"<C-y>",
AppAction::ScrollLine {
dir: ScrollDir::Up,
count: 1,
},
"scroll line up",
) {
eprintln!("hjkl: keymap.add(<C-y>) failed: {e}");
}
// ── Phase 6.4: search repeat ──────────────────────────────────────────
// `n` / `N` — repeat last search. Normal + all Visual modes.
// `*` / `#` / `g*` / `g#` — word-search. Normal mode only
// (g* / g# are dispatched through AfterG reducer via BeginPendingAfterG).
for (chord, forward, desc) in [
("n", true, "search forward repeat"),
("N", false, "search backward repeat"),
] {
let action = AppAction::SearchRepeat { forward, count: 1 };
for mode in [
Mode::Normal,
Mode::Visual,
Mode::VisualLine,
Mode::VisualBlock,
] {
if let Err(e) = km.add(mode, chord, action.clone(), desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
}
// `*` / `#` whole-word search. Normal mode only.
for (chord, forward, desc) in [
("*", true, "search word under cursor forward"),
("#", false, "search word under cursor backward"),
] {
let action = AppAction::WordSearch {
forward,
whole_word: true,
count: 1,
};
if let Err(e) = km.add(Mode::Normal, chord, action, desc) {
eprintln!("hjkl: keymap.add({chord:?}) failed: {e}");
}
}
// ── Phase 6.4: visual entry from Normal ──────────────────────────────
// `v` / `V` / `<C-v>` — enter visual from Normal. `gv` is dispatched
// through the AfterG reducer (BeginPendingAfterG) — not bound here.
if let Err(e) = km.add(
Mode::Normal,
"v",
AppAction::EnterVisualChar,
"enter visual charwise",
) {
eprintln!("hjkl: keymap.add(v) failed: {e}");
}
if let Err(e) = km.add(
Mode::Normal,
"V",
AppAction::EnterVisualLine,
"enter visual linewise",
) {
eprintln!("hjkl: keymap.add(V) failed: {e}");
}
if let Err(e) = km.add(
Mode::Normal,
"<C-v>",
AppAction::EnterVisualBlock,
"enter visual block",
) {
eprintln!("hjkl: keymap.add(<C-v>) failed: {e}");
}
// ── Phase 6.4: gv — reenter last visual ──────────────────────────────
// `gv` is routed through AfterG → the AfterGChord arm in event_loop.rs
// dispatches ReenterLastVisual. We do NOT bind `gv` directly in the trie
// because `g` is already bound as BeginPendingAfterG (pending state chord).
// ── Phase 6.4: visual-mode anchor toggle ─────────────────────────────
// `o` in Visual / VisualLine / VisualBlock — toggle cursor/anchor.
// Normal `o` is bound above as EnterInsertO. Mode discrimination is
// handled automatically by the trie (different mode → different action).
for mode in [Mode::Visual, Mode::VisualLine, Mode::VisualBlock] {
if let Err(e) = km.add(
mode,
"o",
AppAction::VisualToggleAnchor,
"visual toggle anchor",
) {
eprintln!("hjkl: keymap.add(o Visual) failed: {e}");
}
}
km
}
/// Translate an `hjkl_engine::Input` back to a `crossterm::event::KeyEvent`
/// for re-feeding through `route_chord_key` during macro replay.
///
/// This is the inverse of `Editor::handle_key`'s `crossterm_to_input` path.
/// Modifier flags (ctrl, alt, shift) are preserved. Keys that have no
/// crossterm equivalent (e.g. `Key::Null`, `Key::PageUp` without a standard
/// mapping) produce a `KeyCode::Null` sentinel that the replay loop skips.
fn engine_input_to_key_event(input: hjkl_engine::Input) -> crossterm::event::KeyEvent {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hjkl_engine::Key;
let code = match input.key {
Key::Char(c) => KeyCode::Char(c),
Key::Backspace => KeyCode::Backspace,
Key::Delete => KeyCode::Delete,
Key::Enter => KeyCode::Enter,
Key::Left => KeyCode::Left,
Key::Right => KeyCode::Right,
Key::Up => KeyCode::Up,
Key::Down => KeyCode::Down,
Key::Home => KeyCode::Home,
Key::End => KeyCode::End,
Key::Tab => KeyCode::Tab,
Key::Esc => KeyCode::Esc,
Key::PageUp => KeyCode::PageUp,
Key::PageDown => KeyCode::PageDown,
Key::Null => KeyCode::Null,
};
let mut mods = KeyModifiers::NONE;
if input.ctrl {
mods |= KeyModifiers::CONTROL;
}
if input.alt {
mods |= KeyModifiers::ALT;
}
if input.shift {
mods |= KeyModifiers::SHIFT;
}
KeyEvent::new(code, mods)
}
impl App {
/// Clear the LSP hover popup + its arming timer. Called by the
/// event loop at the top of every mouse-button-down arm so a click
/// obsoletes the rest-on-symbol state. Without this, a popup armed
/// at the previous mouse position can leak its cells over the
/// post-click render (e.g. clicking a menu's "Go to Definition"
/// item leaves a stale popup floating over the destination buffer).
pub(crate) fn dismiss_hover_popup_on_click(&mut self) {
self.hover_popup = None;
self.hover_timer = None;
}
/// Dispatch a middle mouse button down at terminal cell `(col, row)`
/// based on the zone it lands in:
///
/// - Code / Gutter → X11/Wayland primary-selection paste at the click
/// position (silent no-op on platforms without primary selection).
/// - TabBar → close that tab (vim parity: `:tabclose` on the clicked tab).
/// - BufferLine → close that buffer (`:bdelete` on the clicked slot —
/// refuses with a status message when the buffer is dirty).
/// - None → no-op.
pub(crate) fn middle_click(&mut self, col: u16, row: u16) {
match mouse::hit_test_zone(self, col, row) {
mouse::Zone::TabBar { tab_idx } => {
// Switch to the clicked tab so do_tabclose targets it,
// then close.
if tab_idx != self.active_tab {
self.sync_viewport_from_editor();
self.active_tab = tab_idx;
self.sync_viewport_to_editor();
}
self.do_tabclose();
}
mouse::Zone::BufferLine { slot_idx } => {
// Switch to the clicked slot so buffer_delete targets it.
if slot_idx != self.focused_slot_idx() {
self.switch_to(slot_idx);
}
self.buffer_delete(false);
}
mouse::Zone::Code { .. } | mouse::Zone::Gutter { .. } => {
self.middle_click_paste_primary(col, row);
}
mouse::Zone::None
| mouse::Zone::StatusLine
| mouse::Zone::SplitBorder { .. }
| mouse::Zone::PickerRow { .. } => {}
}
}
/// Primary-selection paste at terminal cell `(col, row)`. Pulled out
/// of [`Self::middle_click`] so the Code-zone path is independently
/// expressible (and so the X11/Wayland-only branch is grep-able).
fn middle_click_paste_primary(&mut self, col: u16, row: u16) {
use hjkl_clipboard::{Capabilities, MimeType, Selection};
let Some(win_id) = mouse::hit_test_window(self, col, row) else {
return;
};
let Some((doc_row, doc_col)) = mouse::cell_to_doc(self, win_id, col, row) else {
return;
};
// Read primary selection BEFORE any mut borrows of self.
let primary_text: Option<String> = {
let cb = self.active().editor.host().clipboard();
cb.filter(|cb| {
cb.capabilities().contains(Capabilities::PRIMARY)
&& cb.capabilities().contains(Capabilities::READ)
})
.and_then(|cb| {
cb.get(Selection::Primary, MimeType::Text)
.ok()
.and_then(|b| String::from_utf8(b).ok())
})
};
let current_focus = self.focused_window();
if win_id != current_focus {
self.sync_viewport_from_editor();
self.set_focused_window(win_id);
self.sync_viewport_to_editor();
}
self.active_mut().editor.mouse_click_doc(doc_row, doc_col);
self.sync_after_engine_mutation();
if let Some(text) = primary_text {
self.active_mut().editor.set_yank(text);
self.active_mut().editor.paste_after(1);
self.sync_after_engine_mutation();
}
}
/// Focus the window under `(col, row)` and move its cursor to the
/// clicked doc-position. Used at the top of the right-click handler
/// so menu actions (Go to Definition, Rename, etc.) operate on the
/// symbol under the mouse — not on the keyboard cursor's previous
/// position.
///
/// Preserves an active visual selection: when the user has a visual
/// range up and right-clicks, the selection stays intact so Cut /
/// Copy work on it. Without a selection, the cursor moves to the
/// clicked cell. Gutter clicks move to `(doc_row, 0)`.
pub(crate) fn move_cursor_for_right_click(&mut self, col: u16, row: u16) {
use hjkl_engine::VimMode;
let has_sel = matches!(
self.active().editor.vim_mode(),
VimMode::Visual | VimMode::VisualLine | VimMode::VisualBlock
);
if has_sel {
return;
}
let zone = mouse::hit_test_zone(self, col, row);
let win_id = match mouse::hit_test_window(self, col, row) {
Some(w) => w,
None => return,
};
let current_focus = self.focused_window();
if win_id != current_focus {
self.sync_viewport_from_editor();
self.set_focused_window(win_id);
self.sync_viewport_to_editor();
}
let target = match zone {
mouse::Zone::Code {
doc_row, doc_col, ..
} => Some((doc_row, doc_col)),
mouse::Zone::Gutter { doc_row, .. } => Some((doc_row, 0)),
_ => None,
};
if let Some((doc_row, doc_col)) = target {
self.active_mut().editor.mouse_click_doc(doc_row, doc_col);
self.sync_after_engine_mutation();
}
}
/// `true` when a blocking overlay is on top of the editor — context
/// menu, picker, command/search field, info popup. Used to gate
/// background features that shouldn't fire while the user is
/// interacting with the overlay (notably the LSP hover popup, which
/// would otherwise show through the menu for whatever doc text the
/// mouse cell happens to sit over).
pub(crate) fn overlay_active(&self) -> bool {
self.context_menu.is_some()
|| self.picker.is_some()
|| self.command_field.is_some()
|| self.search_field.is_some()
|| self.info_popup.is_some()
}
/// Full-screen rect for clamping popups / context menus to the
/// terminal area. Matches the layout `render::frame` computes:
/// optional top bar (tabs + buffer line, when multiple slots OR
/// tabs are open) + editor viewport + bottom status line.
///
/// MUST include the top bar when it's visible — otherwise this
/// underestimates total height by 1 row and a popup anchored near
/// the bottom flips one row too soon, putting the
/// `Moved`-handler's row→item math out of sync with what
/// `bounding_rect` produces at render time.
pub(crate) fn screen_rect(&self) -> ratatui::layout::Rect {
let vp = self.active().editor.host().viewport();
let show_top_bar = self.tabs.len() > 1 || self.slots.len() > 1;
let top_bar_h = if show_top_bar { TOP_BAR_HEIGHT } else { 0 };
ratatui::layout::Rect {
x: 0,
y: 0,
width: vp.width,
height: top_bar_h + vp.height + STATUS_LINE_HEIGHT,
}
}
// ── Tab accessors ──────────────────────────────────────────────────────
/// Shared reference to the active tab's layout tree.
pub fn layout(&self) -> &window::LayoutTree {
&self.tabs[self.active_tab].layout
}
/// Mutable reference to the active tab's layout tree.
pub fn layout_mut(&mut self) -> &mut window::LayoutTree {
&mut self.tabs[self.active_tab].layout
}
/// The `WindowId` that has focus in the active tab.
pub fn focused_window(&self) -> window::WindowId {
self.tabs[self.active_tab].focused_window
}
/// Set the focused window in the active tab.
pub fn set_focused_window(&mut self, id: window::WindowId) {
self.tabs[self.active_tab].focused_window = id;
}
/// Temporarily take the active tab's layout, replacing it with a
/// sentinel, so we can pass `&mut LayoutTree` to the renderer while
/// still holding `&mut App`.
pub fn take_layout(&mut self) -> window::LayoutTree {
std::mem::replace(self.layout_mut(), window::LayoutTree::Leaf(usize::MAX))
}
/// Restore the layout after a [`take_layout`] call.
pub fn restore_layout(&mut self, layout: window::LayoutTree) {
*self.layout_mut() = layout;
}
// ── Core helpers ──────────────────────────────────────────────────────
/// Slot index for the focused window.
fn focused_slot_idx(&self) -> usize {
self.windows[self.focused_window()]
.as_ref()
.expect("focused_window must point to an open window")
.slot
}
/// Return a shared reference to the active buffer slot.
pub fn active(&self) -> &BufferSlot {
&self.slots[self.focused_slot_idx()]
}
/// Return a mutable reference to the active buffer slot.
pub fn active_mut(&mut self) -> &mut BufferSlot {
let slot_idx = self.focused_slot_idx();
&mut self.slots[slot_idx]
}
/// Return a shared slice of all buffer slots.
pub fn slots(&self) -> &[BufferSlot] {
&self.slots
}
/// Return a mutable slice of all buffer slots. Used by the renderer to
/// publish viewport dimensions and set cursor positions per-window.
pub fn slots_mut(&mut self) -> &mut [BufferSlot] {
&mut self.slots
}
/// Return the slot index of the currently focused window (used by
/// the buffer-line renderer to highlight the active buffer tab).
pub fn active_index(&self) -> usize {
self.focused_slot_idx()
}
// ── Viewport sync ─────────────────────────────────────────────────────
/// Copy the focused window's stored scroll position and cursor into the
/// active editor's host viewport. Call BEFORE input dispatch so the
/// engine's scroll math starts from the right offset.
pub fn sync_viewport_to_editor(&mut self) {
let fw = self.focused_window();
let win = self.windows[fw].as_ref().expect("focused_window open");
let (top_row, top_col) = (win.top_row, win.top_col);
let (cursor_row, cursor_col) = (win.cursor_row, win.cursor_col);
let maybe_rect = win.last_rect;
if let Some(rect) = maybe_rect {
let vp = self.active_mut().editor.host_mut().viewport_mut();
vp.top_row = top_row;
vp.top_col = top_col;
vp.width = rect.width;
vp.height = rect.height;
}
self.active_mut().editor.jump_cursor(cursor_row, cursor_col);
}
/// Copy the active editor's host viewport scroll state and cursor back
/// into the focused window. Call AFTER input dispatch so the engine's
/// auto-scroll and cursor updates are persisted.
pub fn sync_viewport_from_editor(&mut self) {
let vp = self.active().editor.host().viewport();
let (top_row, top_col) = (vp.top_row, vp.top_col);
let (cursor_row, cursor_col) = self.active().editor.cursor();
let fw = self.focused_window();
let win = self.windows[fw].as_mut().expect("focused_window open");
win.top_row = top_row;
win.top_col = top_col;
win.cursor_row = cursor_row;
win.cursor_col = cursor_col;
}
/// Refresh window cursor cache, drain dirty flag + content edits, notify
/// LSP, recompute syntax — call this after any code path that mutated
/// engine state via `apply_motion` / `handle_key` / replay / etc.
///
/// Bug class memo: any keymap-Match arm that triggers cursor motion via
/// `apply_motion` must call this before `continue` — otherwise the window
/// cursor cache goes stale and the render shows the cursor at its old
/// position. This helper consolidates the three previously duplicated
/// ~15-line sync blocks in `event_loop.rs` into a single call site.
pub(crate) fn sync_after_engine_mutation(&mut self) {
// Keymap-dispatched motions go through `apply_motion_kind` which
// calls `execute_motion` but does NOT invoke `ensure_cursor_in_scrolloff`
// (the engine FSM `step()` path does it explicitly). Without this call
// the engine cursor advances off-screen and the viewport top_row
// never updates — the user sees the cursor disappear. Mirror the FSM
// behaviour from the app side so the keymap path stays viewport-coherent.
// Idempotent for non-motion mutations (already-in-bounds = no-op).
self.active_mut().editor.ensure_cursor_in_scrolloff();
// Propagate any mode change (e.g. i/I/a/A/o/O enter-insert actions
// dispatched through the app keymap) to the host cursor-shape so the
// render loop picks it up on the next frame. Idempotent when mode
// did not change.
self.active_mut().editor.emit_cursor_shape_if_changed();
self.sync_viewport_from_editor();
if self.active_mut().editor.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_mut().editor.take_content_reset() {
self.syntax.reset(buffer_id);
}
let edits = self.active_mut().editor.take_content_edits();
if !edits.is_empty() {
self.syntax.apply_edits(buffer_id, &edits);
// Record which rows were touched by this batch of edits so the
// merger can keep untouched cache rows visible while the worker
// parses the new content. The dirty_gen AFTER the edit is the
// current one — any cache older than this gen is stale for these
// rows and should show blank until the worker returns.
let new_dg = self.active().editor.buffer().dirty_gen();
for edit in &edits {
let start_row = edit.start_position.0 as usize;
let end_row =
(edit.old_end_position.0 as usize).max(edit.new_end_position.0 as usize);
self.active_mut()
.dirty_rows_log
.push((new_dg, start_row..=end_row));
}
// Cap to 256 entries to avoid unbounded growth.
const DIRTY_LOG_CAP: usize = 256;
let log = &mut self.active_mut().dirty_rows_log;
if log.len() > DIRTY_LOG_CAP {
let drain_count = log.len() - DIRTY_LOG_CAP;
log.drain(..drain_count);
}
}
self.lsp_notify_change_active();
self.recompute_and_install();
}
/// Return the active auto-indent flash row range `(top, bot)` while
/// `started_at.elapsed() < INDENT_FLASH_DURATION`, otherwise clear
/// the stored flash and return `None`.
///
/// Renderer calls this every frame; event-loop tick also calls it to
/// expire the flash even when no key is pressed.
pub(crate) fn indent_flash_active(&mut self) -> Option<(usize, usize)> {
let elapsed = self.indent_flash.as_ref().map(|f| f.started_at.elapsed())?;
if elapsed >= INDENT_FLASH_DURATION {
self.indent_flash = None;
return None;
}
self.indent_flash.as_ref().map(|f| (f.top, f.bot))
}
// ── External formatter dispatch (hjkl-mangler) ───────────────────────
/// Walk up from `start` looking for a project-root marker file.
///
/// Markers: `.git`, `Cargo.toml`, `package.json`, `go.mod`, `pyproject.toml`,
/// `setup.py`, `composer.json`, `.hg`. Returns the first directory that
/// contains one of these files, or `start` itself as a fallback.
fn find_project_root(start: &std::path::Path) -> std::path::PathBuf {
const MARKERS: &[&str] = &[
".git",
"Cargo.toml",
"package.json",
"go.mod",
"pyproject.toml",
"setup.py",
"composer.json",
".hg",
];
let mut dir = start.to_owned();
loop {
for marker in MARKERS {
if dir.join(marker).exists() {
return dir;
}
}
match dir.parent() {
Some(p) => dir = p.to_owned(),
None => return start.to_owned(),
}
}
}
/// Try to format the active buffer using an external formatter.
///
/// **BLOCKS the calling thread for up to 2 seconds.** This is a
/// synchronous subprocess invocation. Async invocation is tracked in #118.
///
/// Returns `true` if the formatter ran successfully and the buffer was
/// Submit an async format job for the active buffer.
///
/// Returns `true` when a formatter was found and the job was submitted
/// (caller should skip the dumb `auto_indent_range` fallback and wait
/// for `poll_format_results` to install the result).
///
/// Returns `false` when no formatter is registered for the active
/// buffer's extension — caller should run the dumb fallback immediately.
pub(crate) fn submit_external_format(
&mut self,
range: Option<hjkl_mangler::RangeSpec>,
) -> bool {
use hjkl_mangler::{formatter_for_path, probe_tool};
let filename = self.active().filename.clone();
let Some(ref path) = filename else {
return false;
};
let Some(formatter) = formatter_for_path(path) else {
return false;
};
// Probe binary availability up-front so a missing formatter
// (prettier on a fresh box opening a .md, etc.) silently falls
// through to the dumb-algo path instead of dispatching a worker
// job that would surface as a noisy "prettier: not installed".
let tool_name = formatter.tool_name().to_owned();
if let Err(why) = probe_tool(&tool_name) {
tracing::debug!(
tool = %tool_name,
reason = %why,
"formatter probe failed; falling back to dumb algo"
);
// Surface the *real* reason so the user can tell apart
// "binary not on PATH" from "wrapper script exits non-zero".
self.status_message = Some(format!("{tool_name} probe: {why}"));
return false;
}
let source = std::sync::Arc::new(self.active().editor.buffer().as_string());
let dirty_gen = self.active().editor.buffer().dirty_gen();
let buffer_id = self.active().buffer_id;
let parent = path
.parent()
.map(|p| p.to_owned())
.unwrap_or_else(|| std::path::PathBuf::from("."));
let project_root = Self::find_project_root(&parent);
tracing::debug!(
file = %path.display(),
root = %project_root.display(),
buffer_id,
dirty_gen,
"submitting async format job"
);
self.format_worker.submit(hjkl_mangler::FormatJob {
buffer_id,
source,
project_root,
formatter,
dirty_gen,
range,
});
self.format_pending.insert(buffer_id);
self.status_message = Some(format!("{tool_name}: formatting\u{2026}"));
// Arm the visual flash *immediately* on submit — the user sees
// confirmation that `=` was accepted without waiting for the
// (possibly multi-second) formatter to complete. Range is the
// currently-visible viewport rows, so it covers whatever the
// user is looking at.
let vp = self.active().editor.host().viewport();
let line_count = self.active().editor.buffer().row_count();
let top = vp.top_row;
let height = vp.height as usize;
let bot = (top + height.saturating_sub(1)).min(line_count.saturating_sub(1));
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
true
}
/// Drain completed format results from the worker and install them.
///
/// Called once per event-loop tick alongside `poll_git_signs` /
/// `drain_lsp_events`. Returns `true` when at least one result was
/// installed and a redraw is needed.
pub(crate) fn poll_format_results(&mut self) -> bool {
let mut redraw = false;
while let Some(result) = self.format_worker.try_recv() {
self.format_pending.remove(&result.buffer_id);
// Find the slot — may have been closed since submit; drop if so.
let Some(slot_idx) = self
.slots
.iter()
.position(|s| s.buffer_id == result.buffer_id)
else {
tracing::debug!(
buffer_id = result.buffer_id,
"format result for closed buffer; dropping"
);
continue;
};
// Stale check: if the buffer was mutated after the job was
// submitted, drop the result — the user will re-trigger `=`.
let current_dg = self.slots[slot_idx].editor.buffer().dirty_gen();
if current_dg != result.dirty_gen {
tracing::debug!(
buffer_id = result.buffer_id,
submitted_gen = result.dirty_gen,
current_gen = current_dg,
"format result stale; dropping"
);
// Clear the "formatting…" status only if it's still ours.
if self
.status_message
.as_deref()
.is_some_and(|m| m.ends_with("formatting\u{2026}"))
{
self.status_message = None;
}
continue;
}
match result.result {
Ok(formatted) => {
// Native-range formatters (prettier, stylua, ruff) return the whole
// file with only the in-range region reformatted. Whole-file formatters
// return the fully-reformatted file. Either way install directly — no
// diff-splice post-processing needed.
let content = formatted
.strip_suffix('\n')
.unwrap_or(&formatted)
.to_owned();
// set_content_undoable so the engine pushes the pre-format
// buffer state onto the undo stack first — the user can
// press `u` to revert the formatter's changes as a single
// undo step. pending_content_reset is set inside, which
// sync_after_engine_mutation picks up for the syntax layer.
self.slots[slot_idx].editor.set_content_undoable(&content);
// Note: the indent flash was armed at submit time in
// `submit_external_format` so the user gets immediate
// feedback. We don't re-arm here — that would push the
// flash window past the formatter latency on big files.
// Clear the "formatting…" status.
if self
.status_message
.as_deref()
.is_some_and(|m| m.ends_with("formatting\u{2026}"))
{
self.status_message = None;
}
// Propagate dirty/syntax/LSP state — same as the old sync path.
// Only do this when the formatted slot is the active one,
// otherwise we'd pollute the active editor's syntax state.
let active_bid = self.active().buffer_id;
if result.buffer_id == active_bid {
self.sync_after_engine_mutation();
}
redraw = true;
tracing::debug!(buffer_id = result.buffer_id, "format result installed");
}
Err(hjkl_mangler::FormatError::NotInstalled(name)) => {
self.status_message = Some(format!("{name}: not installed"));
redraw = true;
}
Err(e) => {
self.status_message = Some(format!("formatter: {e}"));
redraw = true;
}
}
}
redraw
}
// ── Count-prefix helpers ──────────────────────────────────────────────
/// Drain the pending digit count and replay each digit to the active
/// editor as a bare `Char` key event. No-ops when the count is empty
/// (drain returns an empty string), so callers may omit an
/// `is_empty` guard if they prefer — the existing guards are kept at
/// call sites for clarity and symmetry with the surrounding flow.
fn flush_pending_count_to_engine(&mut self) {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
let digits = self.pending_count.drain_as_digits();
for d in digits.chars() {
hjkl_vim::handle_key(
&mut self.active_mut().editor,
KeyEvent::new(KeyCode::Char(d), KeyModifiers::NONE),
);
}
}
// ── Window focus navigation ───────────────────────────────────────────
/// Move focus to the window below the current one (`Ctrl-w j`).
pub fn focus_below(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().neighbor_below(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Move focus to the window above the current one (`Ctrl-w k`).
pub fn focus_above(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().neighbor_above(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Move focus to the window left of the current one (`Ctrl-w h`).
pub fn focus_left(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().neighbor_left(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Move focus to the window right of the current one (`Ctrl-w l`).
pub fn focus_right(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().neighbor_right(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Move focus to the next window in pre-order traversal, wrapping around (`Ctrl-w w`).
pub fn focus_next(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().next_leaf(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Move focus to the previous window in pre-order traversal, wrapping around (`Ctrl-w W`).
pub fn focus_previous(&mut self) {
let fw = self.focused_window();
if let Some(target) = self.layout().prev_leaf(fw) {
self.sync_viewport_from_editor();
self.set_focused_window(target);
self.sync_viewport_to_editor();
}
}
/// Close all windows except the focused one. Replaces the layout with a
/// single leaf and drops the `Option<Window>` entries for all other windows.
pub fn only_focused_window(&mut self) {
let focused = self.focused_window();
let all_leaves = self.layout().leaves();
for id in all_leaves {
if id != focused {
self.windows[id] = None;
}
}
*self.layout_mut() = window::LayoutTree::Leaf(focused);
self.status_message = Some("only".into());
}
/// Swap the focused leaf with its sibling in the immediately enclosing
/// Split. No-op (with no message) when the focused window is the only one.
pub fn swap_with_sibling(&mut self) {
let focused = self.focused_window();
if self.layout_mut().swap_with_sibling(focused) {
self.status_message = Some("swap".into());
}
}
/// Move the focused window to a new tab (`Ctrl-w T`).
///
/// Fails if the current tab has only one window (vim's "E1: at last window").
/// On success: the window is removed from the current tab's layout (the
/// previous tab gets focus on its new top leaf), and a new tab is appended
/// containing only the moved window.
pub fn move_window_to_new_tab(&mut self) -> Result<(), &'static str> {
let focused = self.focused_window();
if self.layout().leaves().len() <= 1 {
return Err("E1: only one window in this tab");
}
self.sync_viewport_from_editor();
// Remove the focused leaf from the current tab's layout. The returned
// value is the leaf that should receive focus in the current tab.
let new_focus_in_old_tab = self
.layout_mut()
.remove_leaf(focused)
.map_err(|_| "remove_leaf failed")?;
// Update the old tab's focused window to the surviving sibling.
self.tabs[self.active_tab].focused_window = new_focus_in_old_tab;
// Create a new tab containing only the moved window.
let new_tab = window::Tab {
layout: window::LayoutTree::Leaf(focused),
focused_window: focused,
};
self.tabs.push(new_tab);
self.active_tab = self.tabs.len() - 1;
self.sync_viewport_to_editor();
Ok(())
}
/// Close the focused window. Fails (with status message) when only one
/// window remains. On success the layout collapses and focus moves to the
/// sibling that took over.
pub fn close_focused_window(&mut self) {
let focused = self.focused_window();
match self.layout_mut().remove_leaf(focused) {
Err(_) => {
self.status_message = Some("E444: Cannot close last window".into());
}
Ok(new_focus) => {
self.windows[focused] = None;
self.set_focused_window(new_focus);
self.sync_viewport_to_editor();
self.status_message = Some("window closed".into());
}
}
}
// ── Window size manipulation ───────────────────────────────────────────
/// Adjust the focused window's height by `delta` lines. Positive grows,
/// negative shrinks. Clamps so neither sibling drops below 1 line.
/// No-op when there is no enclosing Horizontal split or last_rect is None.
pub fn resize_height(&mut self, delta: i32) {
use window::SplitDir;
let fw = self.focused_window();
if let Some((ratio, Some(rect), in_a)) = self
.layout_mut()
.enclosing_split_mut(fw, SplitDir::Horizontal)
{
let parent_h = rect.height as i32;
if parent_h < 2 {
return;
}
let current_focused_height = if in_a {
(parent_h as f32 * *ratio) as i32
} else {
(parent_h as f32 * (1.0 - *ratio)) as i32
};
let new_focused = (current_focused_height + delta).clamp(1, parent_h - 1);
let new_ratio = if in_a {
new_focused as f32 / parent_h as f32
} else {
(parent_h - new_focused) as f32 / parent_h as f32
};
*ratio = new_ratio.clamp(0.01, 0.99);
}
}
/// Adjust the focused window's width by `delta` columns. Positive grows,
/// negative shrinks. Clamps so neither sibling drops below 1 column.
/// No-op when there is no enclosing Vertical split or last_rect is None.
pub fn resize_width(&mut self, delta: i32) {
use window::SplitDir;
let fw = self.focused_window();
if let Some((ratio, Some(rect), in_a)) = self
.layout_mut()
.enclosing_split_mut(fw, SplitDir::Vertical)
{
let parent_w = rect.width as i32;
if parent_w < 2 {
return;
}
let current_focused_width = if in_a {
(parent_w as f32 * *ratio) as i32
} else {
(parent_w as f32 * (1.0 - *ratio)) as i32
};
let new_focused = (current_focused_width + delta).clamp(1, parent_w - 1);
let new_ratio = if in_a {
new_focused as f32 / parent_w as f32
} else {
(parent_w - new_focused) as f32 / parent_w as f32
};
*ratio = new_ratio.clamp(0.01, 0.99);
}
}
/// Equalize all splits to 0.5 ratio.
pub fn equalize_layout(&mut self) {
self.layout_mut().equalize_all();
}
/// Resize the split whose `last_rect` encompasses `split_origin` and
/// `split_total` so the boundary sits at `split_pos` cells from the
/// split origin. `split_pos` is clamped to leave at least
/// `SPLIT_MIN_SIZE_COLS` / `SPLIT_MIN_SIZE_ROWS` on each side.
///
/// Called by the border-drag handler in the event loop (Phase 9).
/// `orientation` determines whether we're moving a column (VSplit) or
/// a row (HSplit) boundary.
pub(crate) fn resize_split_to(
&mut self,
orientation: mouse::SplitOrientation,
split_origin: u16,
split_total: u16,
split_pos: u16,
) {
use window::SplitDir;
let min_size = match orientation {
mouse::SplitOrientation::Vertical => SPLIT_MIN_SIZE_COLS,
mouse::SplitOrientation::Horizontal => SPLIT_MIN_SIZE_ROWS,
};
if split_total < min_size * 2 + 1 {
return; // too small to resize
}
// Clamp split_pos so both children stay at least min_size.
let clamped = split_pos.clamp(min_size, split_total.saturating_sub(min_size + 1));
let new_ratio = clamped as f32 / split_total as f32;
let new_ratio = new_ratio.clamp(0.01, 0.99);
// Find the matching split node by walking the layout tree and looking
// for a Split whose last_rect matches the origin + total we recorded
// when the drag started.
let dir = match orientation {
mouse::SplitOrientation::Vertical => SplitDir::Vertical,
mouse::SplitOrientation::Horizontal => SplitDir::Horizontal,
};
fn update_matching(
node: &mut window::LayoutTree,
dir: window::SplitDir,
origin: u16,
total: u16,
new_ratio: f32,
) {
if let window::LayoutTree::Split {
dir: my_dir,
ratio,
a,
b,
last_rect,
} = node
{
if *my_dir == dir
&& let Some(r) = last_rect
{
let (rect_origin, rect_total) = match dir {
window::SplitDir::Vertical => (r.x, r.width),
window::SplitDir::Horizontal => (r.y, r.height),
};
if rect_origin == origin && rect_total == total {
*ratio = new_ratio;
return; // found the target; done
}
}
update_matching(a, dir, origin, total, new_ratio);
update_matching(b, dir, origin, total, new_ratio);
}
}
update_matching(self.layout_mut(), dir, split_origin, split_total, new_ratio);
}
/// Equalize all splits (set every ratio to 0.5). Used by double-click on a
/// border (Phase 9). Delegates to the existing `equalize_layout`.
pub(crate) fn equalize_split(&mut self) {
self.equalize_layout();
}
/// Maximize focused window's height — set every enclosing Horizontal
/// split so the focused branch gets as much height as possible (siblings
/// collapse to 1 line each).
pub fn maximize_height(&mut self) {
use window::SplitDir;
let focused = self.focused_window();
self.layout_mut()
.for_each_ancestor(focused, &mut |dir, ratio, in_a, rect| {
if dir != SplitDir::Horizontal {
return;
}
if let Some(r) = rect {
let h = r.height as f32;
if h < 2.0 {
return;
}
let max_branch = (h - 1.0) / h;
let min_branch = 1.0 / h;
*ratio = if in_a { max_branch } else { min_branch };
}
});
}
/// Maximize focused window's width — set every enclosing Vertical split
/// so the focused branch gets as much width as possible (siblings collapse
/// to 1 column each).
pub fn maximize_width(&mut self) {
use window::SplitDir;
let focused = self.focused_window();
self.layout_mut()
.for_each_ancestor(focused, &mut |dir, ratio, in_a, rect| {
if dir != SplitDir::Vertical {
return;
}
if let Some(r) = rect {
let w = r.width as f32;
if w < 2.0 {
return;
}
let max_branch = (w - 1.0) / w;
let min_branch = 1.0 / w;
*ratio = if in_a { max_branch } else { min_branch };
}
});
}
/// Build a fresh [`App`], optionally loading `filename` from disk.
///
/// - File found → content seeded into buffer, dirty = false.
/// - File not found → buffer empty, filename retained, `is_new_file = true`.
/// - Other I/O error → returns `Err` so main can print to stderr before
/// entering alternate-screen mode.
///
/// `readonly` sets `:set readonly` on the editor options.
/// `goto_line` (1-based) moves the cursor after load when `Some`.
/// `search_pattern` triggers an initial search when `Some`.
pub fn new(
filename: Option<PathBuf>,
readonly: bool,
goto_line: Option<usize>,
search_pattern: Option<String>,
) -> Result<Self> {
// Load the app theme up front and build the syntax layer with the
// override theme — so apps/hjkl renders with the website palette
// (hjkl-bonsai's bundled DotFallbackTheme is left untouched
// for other consumers).
let theme = crate::theme::AppTheme::default_dark();
let directory = std::sync::Arc::new(crate::lang::LanguageDirectory::new()?);
let mut syntax = syntax::layer_with_theme(theme.syntax.clone(), directory.clone());
let buffer_id: BufferId = 0;
// App::new uses bundled config defaults; main wires the XDG-merged
// value via `with_config` after construction. For build_slot's
// initial Options seed, the bundled defaults are correct because
// tests never customize config and main re-applies overrides via
// `apply_options` after `with_config`.
let bootstrap_config = crate::config::Config::default();
let no_file = filename.is_none();
let mut slot = build_slot(&mut syntax, buffer_id, filename, &bootstrap_config)
.map_err(|s| anyhow::anyhow!(s))?;
// Apply readonly after the slot is built — build_slot always uses
// Options::default(); override here when requested.
if readonly {
slot.editor.apply_options(&Options {
readonly: true,
..Options::default()
});
}
// +N line jump — 1-based, clamp to buffer.
if let Some(n) = goto_line {
slot.editor.goto_line(n);
}
// +/pattern initial search — compile the pattern and set it.
if let Some(pat) = search_pattern {
match regex::Regex::new(&pat) {
Ok(re) => {
slot.editor.set_search_pattern(Some(re));
slot.editor.search_advance_forward(false);
// search_advance_forward moves the cursor without
// going through vim::step's end-of-step scrolloff
// hook, so the editor's viewport stays at row 0.
// Reveal the cursor here so the focused window's
// initial top_row (read below) picks up the scroll.
slot.editor.ensure_cursor_in_scrolloff();
// Persist direction so a subsequent `n` repeats
// forward; without this, vim.last_search_forward
// stays at its bool default (false) and `n` jumps
// backward as if `?pat<CR>` had been typed.
slot.editor.set_last_search(Some(pat), true);
}
Err(e) => {
eprintln!("hjkl: bad search pattern: {e}");
}
}
}
let start_screen = if no_file {
Some(crate::start_screen::StartScreen::new())
} else {
None
};
// Single window pointing at slot 0. Seed top_row / top_col from
// the slot's editor viewport so any pre-event-loop scroll (e.g.
// +/pat search-on-open) is preserved through the first tick of
// sync_viewport_to_editor.
let (initial_top_row, initial_top_col) = {
let vp = slot.editor.host().viewport();
(vp.top_row, vp.top_col)
};
let initial_window = window::Window {
slot: 0,
top_row: initial_top_row,
top_col: initial_top_col,
cursor_row: 0,
cursor_col: 0,
last_rect: None,
};
let default_leader = crate::config::Config::default().editor.leader;
Ok(Self {
slots: vec![slot],
windows: vec![Some(initial_window)],
tabs: vec![window::Tab {
layout: window::LayoutTree::Leaf(0),
focused_window: 0,
}],
active_tab: 0,
next_window_id: 1,
next_buffer_id: 1,
prev_active: None,
exit_requested: false,
status_message: None,
info_popup: None,
command_field: None,
command_completion: None,
search_field: None,
picker: None,
pending_count: hjkl_vim::CountAccumulator::new(),
search_dir: SearchDir::Forward,
last_cursor_shape: CursorShape::Block,
syntax,
git_worker: GitSignsWorker::new(),
format_worker: hjkl_mangler::FormatWorker::spawn(),
format_pending: HashSet::new(),
directory,
theme,
preview_highlighters: std::sync::Mutex::new(std::collections::HashMap::new()),
perf_overlay: false,
last_recompute_us: 0,
last_install_us: 0,
last_signature_us: 0,
last_git_us: 0,
last_perf: crate::syntax::PerfBreakdown::default(),
recompute_hits: 0,
recompute_throttled: 0,
recompute_runs: 0,
syntax_stale_drops: 0,
config: crate::config::Config::default(),
start_screen,
grammar_load_error: None,
lsp: None,
lsp_state: HashMap::new(),
lsp_next_request_id: 0,
lsp_pending: HashMap::new(),
completion: None,
pending_code_actions: Vec::new(),
pending_ctrl_x: false,
pending_prefix_at: None,
which_key_active: false,
which_key_sticky: false,
which_key_enabled: true,
which_key_delay: std::time::Duration::from_millis(500),
user_keymap_records: Vec::new(),
replay_depth: 0,
// Default to bundled config's value; main overrides via with_config
// before crossterm capture is enabled.
mouse_enabled: crate::config::Config::default().editor.mouse,
mouse_flags: MouseFlags::all(),
app_keymap: build_app_keymap(default_leader),
anvil_pool: hjkl_anvil::InstallPool::new(),
anvil_handles: HashMap::new(),
anvil_log: HashMap::new(),
anvil_registry: hjkl_anvil::Registry::embedded().ok(),
pending_state: None,
last_ex_command: None,
mouse_click_tracker: mouse::MouseClickTracker::new(),
context_menu: None,
hover_popup: None,
hover_timer: None,
border_drag: None,
indent_flash: None,
})
}
/// Replace the user config (typically loaded by `main` from the XDG
/// path or `--config <PATH>`) and re-apply config-derived
/// [`Options`] to every already-open slot.
///
/// `App::new` constructs slot 0 with bootstrap defaults before any
/// user config is wired, so without this re-application a user
/// override of `editor.tab_width` / `editor.expandtab` would only
/// affect *subsequent* slots (`:e`, `open_extra`). The re-applied
/// `Options` seed is overlaid by `.editorconfig` per-path so project
/// rules still take precedence over user-config fallbacks.
///
/// Readonly state on each slot is preserved.
/// Toggle terminal mouse capture at runtime. Drives the corresponding
/// crossterm Enable/DisableMouseCapture commands against stdout so
/// the change takes effect on the next event poll. Idempotent —
/// flipping to the current state is a no-op for the terminal but
/// still updates `mouse_enabled` so the field remains the source of
/// truth.
pub fn set_mouse_capture(&mut self, on: bool) {
if self.mouse_enabled == on {
self.status_message = Some(if on { "mouse" } else { "nomouse" }.into());
return;
}
let res = if on {
crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture)
} else {
crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture)
};
match res {
Ok(()) => {
self.mouse_enabled = on;
self.status_message = Some(if on { "mouse" } else { "nomouse" }.into());
}
Err(e) => {
self.status_message = Some(format!("E: failed to toggle mouse capture: {e}"));
}
}
}
pub fn with_config(mut self, config: crate::config::Config) -> Self {
self.mouse_enabled = config.editor.mouse;
self.which_key_enabled = config.which_key.enabled;
self.which_key_delay = std::time::Duration::from_millis(config.which_key.delay_ms);
// Rebuild the app keymap with the configured leader and timeout.
let leader = config.editor.leader;
let timeout = Duration::from_millis(config.which_key.delay_ms);
self.app_keymap = build_app_keymap(leader);
self.app_keymap.set_timeout(timeout);
self.config = config;
for slot in &mut self.slots {
let was_readonly = slot.editor.is_readonly();
let mut opts = Options {
expandtab: self.config.editor.expandtab,
tabstop: self.config.editor.tab_width as u32,
shiftwidth: self.config.editor.tab_width as u32,
softtabstop: self.config.editor.tab_width as u32,
readonly: was_readonly,
..Options::default()
};
if let Some(p) = slot.filename.as_ref() {
crate::editorconfig::overlay_for_path(&mut opts, p);
}
slot.editor.apply_options(&opts);
}
self
}
/// Attach an `LspManager` to the app. Call after `with_config`. Iterates
/// the existing slots and attaches each one whose filename matches a
/// known language and whose language has a configured server — fixes the
/// startup case where slot 0 was built before `with_lsp` was wired and
/// would otherwise miss its `didOpen`.
pub fn with_lsp(mut self, lsp: hjkl_lsp::LspManager) -> Self {
self.lsp = Some(lsp);
for idx in 0..self.slots.len() {
self.lsp_attach_buffer(idx);
}
self
}
/// Mode label for the status line.
pub fn mode_label(&self) -> &'static str {
if self.start_screen.is_some() {
return "START";
}
match self.active().editor.vim_mode() {
VimMode::Normal => "NORMAL",
VimMode::Insert => "INSERT",
VimMode::Visual => "VISUAL",
VimMode::VisualLine => "VISUAL LINE",
VimMode::VisualBlock => "VISUAL BLOCK",
}
}
/// Public entry point for loading an extra file from the CLI into a new
/// slot without switching the active buffer. Used by `main` to handle
/// `hjkl a.rs b.rs c.rs` — slots 1…N are populated here after `App::new`
/// opens slot 0.
pub fn open_extra(&mut self, path: PathBuf) -> Result<(), String> {
self.open_new_slot(path).map(|_| ())
}
/// Dismiss the active completion popup (if any).
pub fn dismiss_completion(&mut self) {
self.completion = None;
self.pending_ctrl_x = false;
}
// ── Context menu keyboard dispatch (Phase 2, Round A) ────────────────
/// Handle a keypress while the context menu is open.
///
/// Returns `true` if the key was consumed by the menu (caller should
/// `continue` the event loop). Returns `false` when the key is not a
/// menu-nav key — caller should then dismiss the menu and fall through
/// to normal dispatch.
pub(crate) fn handle_context_menu_key(&mut self, key: crossterm::event::KeyEvent) -> bool {
use crossterm::event::KeyCode;
match key.code {
// Navigation.
KeyCode::Up | KeyCode::Char('k') => {
if let Some(ref mut m) = self.context_menu {
m.move_up();
}
true
}
KeyCode::Down | KeyCode::Char('j') => {
if let Some(ref mut m) = self.context_menu {
m.move_down();
}
true
}
// Confirm.
KeyCode::Enter => {
let action = self.context_menu.as_ref().and_then(|m| m.selected_action());
self.context_menu = None;
if let Some(act) = action {
self.invoke_menu_action(act);
}
true
}
// Dismiss.
KeyCode::Esc => {
self.context_menu = None;
true
}
// Any other key: caller dismisses and falls through.
_ => false,
}
}
/// Execute a [`crate::menu::MenuAction`] selected from the context menu.
pub(crate) fn invoke_menu_action(&mut self, action: crate::menu::MenuAction) {
use crate::menu::MenuAction;
match action {
MenuAction::Copy => self.menu_copy(),
MenuAction::Cut => self.menu_cut(),
MenuAction::Paste => self.menu_paste(),
MenuAction::TabClose => self.dispatch_ex("tabclose"),
MenuAction::TabCloseOthers => self.do_tabonly(),
MenuAction::TabCloseRight => self.close_tabs_to_right(),
MenuAction::TabCloseLeft => self.close_tabs_to_left(),
// ── LSP actions (Phase 2, Round B) ───────────────────────────────
MenuAction::LspGotoDefinition => self.lsp_goto_definition(),
MenuAction::LspGotoReferences => self.lsp_goto_references(),
MenuAction::LspHover => self.lsp_hover(),
MenuAction::LspCodeActions => self.lsp_code_actions(),
MenuAction::LspFormat => self.lsp_format(),
// Rename needs a new name from the user. The ex command
// `:Rename <newname>` is the supported entry point — mirror the
// same status-message prompt the `<leader>rn` keybind uses so the
// user knows how to proceed.
MenuAction::LspRename => {
self.status_message = Some("use :Rename <newname> to rename".into());
}
// ── Phase 7: status-line menu actions ────────────────────────────
MenuAction::LspRestart => self.restart_lsp(),
MenuAction::OpenFilePicker => self.open_picker(),
// ── Phase 7: split-border menu actions ───────────────────────────
MenuAction::WindowEqualize => self.equalize_layout(),
MenuAction::WindowClose => self.dispatch_ex("close"),
// ── Phase 8: picker overlay menu actions ──────────────────────────
MenuAction::PickerOpen => self.picker_accept(),
MenuAction::PickerOpenSplit => self.picker_open_in_split(),
MenuAction::PickerOpenVSplit => self.picker_open_in_vsplit(),
MenuAction::PickerOpenTab => self.picker_open_in_tab(),
MenuAction::PickerCopyPath => self.picker_copy_path(),
MenuAction::Separator | MenuAction::Info => {} // no-op
}
}
// ── Menu clipboard actions (Phase 2, Round A) ─────────────────────────
/// Right-click Copy action.
///
/// If a visual selection is active, yank the selection into the unnamed
/// register (which the engine already mirrors to the system clipboard via
/// `Host::write_clipboard`). If no selection is active, yank the current
/// line (same as `yy` / `Y` line-yank semantics).
pub(crate) fn menu_copy(&mut self) {
use hjkl_engine::{RangeKind, VimMode};
let vim_mode = self.active().editor.vim_mode();
match vim_mode {
VimMode::VisualBlock => {
if let Some((top_row, bot_row, left_col, right_col)) =
self.active().editor.block_highlight()
{
self.active_mut()
.editor
.yank_block(top_row, bot_row, left_col, right_col, '"');
}
}
VimMode::Visual => {
if let Some((start, end)) = self.active().editor.char_highlight() {
self.active_mut()
.editor
.yank_range(start, end, RangeKind::Inclusive, '"');
}
}
VimMode::VisualLine => {
if let Some((top_row, bot_row)) = self.active().editor.line_highlight() {
self.active_mut().editor.yank_range(
(top_row, 0),
(bot_row, usize::MAX),
RangeKind::Linewise,
'"',
);
}
}
_ => {
// No selection — yank current line (yy semantics).
self.active_mut().editor.yank_to_eol(1);
}
}
self.sync_after_engine_mutation();
}
/// Right-click Cut action.
///
/// Identical to [`menu_copy`] but also deletes the yanked region.
/// On a visual selection this calls the appropriate `delete_range` /
/// `delete_block` path. Without a selection it yanks and deletes the
/// current line (`dd` semantics).
pub(crate) fn menu_cut(&mut self) {
use hjkl_engine::{RangeKind, VimMode};
let vim_mode = self.active().editor.vim_mode();
match vim_mode {
VimMode::VisualBlock => {
if let Some((top_row, bot_row, left_col, right_col)) =
self.active().editor.block_highlight()
{
self.active_mut()
.editor
.delete_block(top_row, bot_row, left_col, right_col, '"');
// Exit visual mode.
use crossterm::event::{KeyCode, KeyEvent as CtKeyEvent, KeyModifiers};
hjkl_vim::handle_key(
&mut self.active_mut().editor,
CtKeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
);
}
}
VimMode::Visual => {
if let Some((start, end)) = self.active().editor.char_highlight() {
self.active_mut()
.editor
.delete_range(start, end, RangeKind::Inclusive, '"');
use crossterm::event::{KeyCode, KeyEvent as CtKeyEvent, KeyModifiers};
hjkl_vim::handle_key(
&mut self.active_mut().editor,
CtKeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
);
}
}
VimMode::VisualLine => {
if let Some((top_row, bot_row)) = self.active().editor.line_highlight() {
self.active_mut().editor.delete_range(
(top_row, 0),
(bot_row, usize::MAX),
RangeKind::Linewise,
'"',
);
use crossterm::event::{KeyCode, KeyEvent as CtKeyEvent, KeyModifiers};
hjkl_vim::handle_key(
&mut self.active_mut().editor,
CtKeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
);
}
}
_ => {
// No selection — delete current line (dd semantics):
// yank_to_eol then delete_to_eol is not quite right for full-line;
// use the engine's delete_range for the full current row.
let (row, _) = self.active().editor.cursor();
self.active_mut().editor.delete_range(
(row, 0),
(row, usize::MAX),
hjkl_engine::RangeKind::Linewise,
'"',
);
}
}
self.sync_after_engine_mutation();
}
/// Right-click Paste action.
///
/// Reads the system clipboard into the unnamed register (so the engine's
/// `p` command sees fresh content) and then performs a `paste_after`.
pub(crate) fn menu_paste(&mut self) {
// Pull from system clipboard → unnamed register so paste_after uses it.
if let Some(text) = self.active_mut().editor.host_mut().read_clipboard() {
self.active_mut().editor.set_yank(text);
}
self.active_mut().editor.paste_after(1);
self.sync_after_engine_mutation();
}
/// Call whenever a chord prefix first enters the `app_keymap` pending buffer.
/// Records the timestamp used to drive the which-key idle timeout.
pub fn note_prefix_set(&mut self) {
self.pending_prefix_at = Some(std::time::Instant::now());
self.which_key_active = false;
}
/// Call whenever a prefix is resolved or cleared (second key arrived,
/// Escape pressed, mode change, etc.). Resets all which-key state.
pub fn clear_prefix_state(&mut self) {
self.pending_prefix_at = None;
self.which_key_active = false;
}
/// Return the currently-pending chord buffer for Normal mode, or an empty
/// `Vec` when no prefix is active.
///
/// The caller uses this to drive `which_key::entries_for` directly —
/// the static `Prefix` enum is no longer needed.
pub fn active_which_key_prefix(&self) -> Vec<hjkl_keymap::KeyEvent> {
self.app_keymap.pending(keymap::HjklMode::Normal).to_vec()
}
/// Dispatch an [`AppAction`] with an optional repeat count.
///
/// This is the single authoritative dispatch site for all chord-triggered
/// app actions. Routing by domain — each cluster delegates to a focused
/// sub-dispatcher that lives in the corresponding glue module:
/// - picker opens → inline (3 one-liners)
/// - git actions → `picker_glue::dispatch_git_action`
/// - LSP actions → `lsp_glue::dispatch_lsp_action`
/// - window actions → `window::dispatch_window_action` (incl. TmuxNavigate)
/// - buffer actions → `buffer_ops::dispatch_buffer_action`
/// - prompt actions → `prompt::dispatch_prompt_action`
/// - pending-state → `pending_actions::dispatch_pending_state_action`
/// - engine actions → `engine_actions::dispatch_engine_action`
/// - QuitOrClose → inline (app-lifecycle, 5 LOC)
pub fn dispatch_action(&mut self, action: AppAction, count: u32) {
let count = count.max(1) as usize;
match action {
// ── File / buffer pickers (open) ───────────────────────────────
AppAction::OpenFilePicker => self.open_picker(),
AppAction::OpenBufferPicker => self.open_buffer_picker(),
AppAction::OpenGrepPicker => self.open_grep_picker(None),
// ── Git picker openers ─────────────────────────────────────────
AppAction::GitStatus
| AppAction::GitLog
| AppAction::GitBranch
| AppAction::GitFileHistory
| AppAction::GitStashes
| AppAction::GitTags
| AppAction::GitRemotes => self.dispatch_git_action(action),
// ── LSP + diagnostic navigation ────────────────────────────────
AppAction::ShowDiagAtCursor
| AppAction::LspCodeActions
| AppAction::LspRename
| AppAction::LspGotoDef
| AppAction::LspGotoDecl
| AppAction::LspGotoRef
| AppAction::LspGotoImpl
| AppAction::LspGotoTypeDef
| AppAction::LspHover
| AppAction::DiagNext
| AppAction::DiagPrev
| AppAction::DiagNextError
| AppAction::DiagPrevError => self.dispatch_lsp_action(action),
// ── Window / layout management ─────────────────────────────────
AppAction::FocusLeft
| AppAction::FocusBelow
| AppAction::FocusAbove
| AppAction::FocusRight
| AppAction::FocusNext
| AppAction::FocusPrev
| AppAction::CloseFocusedWindow
| AppAction::OnlyFocusedWindow
| AppAction::SwapWithSibling
| AppAction::MoveWindowToNewTab
| AppAction::NewSplit
| AppAction::ResizeHeight(_)
| AppAction::ResizeWidth(_)
| AppAction::EqualizeLayout
| AppAction::MaximizeHeight
| AppAction::MaximizeWidth
| AppAction::TmuxNavigate(_) => self.dispatch_window_action(action, count),
// ── Buffer / tab navigation ────────────────────────────────────
AppAction::Tabnext
| AppAction::Tabprev
| AppAction::BufferNext
| AppAction::BufferPrev
| AppAction::BufferAlt
| AppAction::BufferCycleH
| AppAction::BufferCycleL => self.dispatch_buffer_action(action, count),
// ── Prompt / overlay entry ─────────────────────────────────────
AppAction::OpenCommandPrompt | AppAction::OpenSearchPrompt(_) => {
self.dispatch_prompt_action(action)
}
// ── Pending-state chords ───────────────────────────────────────
AppAction::BeginPendingReplace { .. }
| AppAction::BeginPendingFind { .. }
| AppAction::BeginPendingAfterG { .. }
| AppAction::BeginPendingAfterZ { .. }
| AppAction::BeginPendingAfterOp { .. }
| AppAction::BeginPendingSelectRegister
| AppAction::BeginPendingSetMark
| AppAction::BeginPendingGotoMarkLine
| AppAction::BeginPendingGotoMarkChar
| AppAction::QChord { .. }
| AppAction::BeginPendingPlayMacro { .. } => self.dispatch_pending_state_action(action),
// ── App lifecycle ──────────────────────────────────────────────
AppAction::QuitOrClose => {
if self.layout().leaves().len() > 1 {
self.close_focused_window();
} else {
self.exit_requested = true;
}
}
// ── Engine-mutating actions ────────────────────────────────────
_ => self.dispatch_engine_action(action, count),
}
}
/// Replay a slice of `hjkl_keymap::KeyEvent`s straight to the engine,
/// converting each one to a crossterm `KeyEvent` via the shared translator.
pub(crate) fn replay_km_events_to_engine(&mut self, events: &[hjkl_keymap::KeyEvent]) {
for km_ev in events {
let ct_ev = crate::keymap_translate::to_crossterm(km_ev);
hjkl_vim::handle_key(&mut self.active_mut().editor, ct_ev);
}
}
/// Feed a crossterm key event through the app-level chord keymap and
/// dispatch any resolved action. Returns `true` if the key was consumed
/// (either resolved or still pending), `false` if the keymap returned
/// `Unbound` and the caller should replay the events to the engine.
///
/// Replayed events are stored in `out_replay` (never `None`-cleared).
///
/// This is a thin shim over [`dispatch_keymap_in_mode`] fixed to Normal mode.
pub fn dispatch_keymap(
&mut self,
km_ev: hjkl_keymap::KeyEvent,
count: u32,
out_replay: &mut Vec<hjkl_keymap::KeyEvent>,
) -> bool {
self.dispatch_keymap_in_mode(km_ev, count, out_replay, keymap::HjklMode::Normal)
}
/// Mode-generalized chord dispatch. Feed `km_ev` into the trie for `mode`
/// and dispatch any resolved action.
///
/// Returns `true` if consumed (Pending / Ambiguous / Match),
/// `false` if Unbound (events stored in `out_replay`).
pub fn dispatch_keymap_in_mode(
&mut self,
km_ev: hjkl_keymap::KeyEvent,
count: u32,
out_replay: &mut Vec<hjkl_keymap::KeyEvent>,
mode: keymap::HjklMode,
) -> bool {
use hjkl_keymap::KeyResolve;
let now = std::time::Instant::now();
match self.app_keymap.feed(mode, km_ev, now) {
KeyResolve::Pending => {
self.note_prefix_set();
true
}
KeyResolve::Ambiguous => {
self.note_prefix_set();
true
}
KeyResolve::Match(binding) => {
self.clear_prefix_state();
self.dispatch_action(binding.action, count);
true
}
KeyResolve::Unbound(events) => {
self.clear_prefix_state();
out_replay.extend(events);
false
}
}
}
/// Convert a `hjkl_keymap::KeyEvent` back to a `crossterm::event::KeyEvent`
/// for replaying unbound sequences to the engine.
///
/// Moved here from `event_loop.rs` (option A) so that both the event loop
/// and tests can replay keymap events without touching file-local functions.
pub(crate) fn km_to_crossterm(ev: &hjkl_keymap::KeyEvent) -> crossterm::event::KeyEvent {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hjkl_keymap::{KeyCode as KmKeyCode, KeyModifiers as KmKeyMods};
let code = match ev.code {
KmKeyCode::Char(c) => KeyCode::Char(c),
KmKeyCode::Enter => KeyCode::Enter,
KmKeyCode::Esc => KeyCode::Esc,
KmKeyCode::Tab => KeyCode::Tab,
KmKeyCode::Backspace => KeyCode::Backspace,
KmKeyCode::Delete => KeyCode::Delete,
KmKeyCode::Insert => KeyCode::Insert,
KmKeyCode::Up => KeyCode::Up,
KmKeyCode::Down => KeyCode::Down,
KmKeyCode::Left => KeyCode::Left,
KmKeyCode::Right => KeyCode::Right,
KmKeyCode::Home => KeyCode::Home,
KmKeyCode::End => KeyCode::End,
KmKeyCode::PageUp => KeyCode::PageUp,
KmKeyCode::PageDown => KeyCode::PageDown,
KmKeyCode::F(n) => KeyCode::F(n),
};
let mut mods = KeyModifiers::NONE;
if ev.modifiers.contains(KmKeyMods::CTRL) {
mods |= KeyModifiers::CONTROL;
}
if ev.modifiers.contains(KmKeyMods::SHIFT) {
mods |= KeyModifiers::SHIFT;
}
if ev.modifiers.contains(KmKeyMods::ALT) {
mods |= KeyModifiers::ALT;
}
KeyEvent::new(code, mods)
}
/// Replay a slice of `hjkl_keymap::KeyEvent`s to the engine via crossterm
/// `KeyEvent`s. Each keymap event is converted back to a crossterm event
/// and forwarded to `editor.handle_key`.
///
/// Moved here from `event_loop.rs` (option A) for testability.
pub(crate) fn replay_to_engine(&mut self, events: &[hjkl_keymap::KeyEvent]) {
for km_ev in events {
let ct_ev = Self::km_to_crossterm(km_ev);
hjkl_vim::handle_key(&mut self.active_mut().editor, ct_ev);
}
}
/// Single canonical chord-routing entry. Called by the event loop's key
/// handler and by tests. Returns `true` if the key was consumed at any
/// stage of the chord routing; `false` if it should fall through to the
/// engine `handle_key` path.
///
/// Order (matches production event loop exactly — this IS the production
/// routing now, not a test mirror):
/// 1. pending_state reducer (all modes, when `pending_state.is_some()`)
/// 2. Non-Normal trie dispatch (mode != Normal AND pending_state.is_none())
/// 3. Normal-mode keymap dispatch (mode == Normal AND pending_state.is_none())
///
/// Out of scope (run BEFORE this method in event_loop.rs):
/// - command-field overlay (`self.command_field.is_some()`)
/// - search-field overlay (`self.search_field.is_some()`)
/// - picker overlay (`self.picker.is_some()`)
/// - info-popup dismissal
/// - Visual-mode `:` intercept (must precede pending_state reducer)
/// - Insert-mode completion handling
/// - tmux-navigator Ctrl-h/j/k/l (Phase 3 — issue #120)
/// - count-prefix buffering (digits `0`–`9` in Normal mode)
/// - Shift-H / Shift-L buffer cycle (Phase 3 — issue #120)
/// - Esc chord-reset and which-key Backspace navigate-up
///
/// Migrated to keymap trie (issue #120 Phase 2 — now dispatch_action arms):
/// - `K` → `AppAction::LspHover`
/// - `:` → `AppAction::OpenCommandPrompt`
/// - `/` / `?` → `AppAction::OpenSearchPrompt`
/// - `<C-^>` / `<C-6>` → `AppAction::BufferAlt`
pub(crate) fn route_chord_key(&mut self, key: crossterm::event::KeyEvent) -> bool {
// Snapshot recording state BEFORE dispatch so we can detect the moment
// a new recording starts (StartMacroRecord arm) — the register-name key
// that triggered the start is a bookkeeping key and must NOT be recorded.
// Similarly, if we were not recording before and are now, skip this key.
//
// The @{reg} register-name key (PlayMacro arm) also must not be recorded;
// that arm returns early in route_chord_key_inner so is_recording_macro()
// state doesn't change between before/after — BUT recording may be active
// before the @{reg} key (recording a macro that includes a @a call). In
// that case we ALSO skip the register name (pending_was_macro_chord logic).
let was_recording_before = self.active().editor.is_recording_macro();
let was_play_macro_pending = matches!(
self.pending_state,
Some(hjkl_vim::PendingState::PlayMacroTarget { .. })
);
let consumed = self.route_chord_key_inner(key);
// Recorder hook: append the consumed key to the active macro recording
// (if any) so replays reproduce the same sequence. Skip:
// 1. When not consumed (key was not processed).
// 2. When replaying (is_replaying_macro).
// 3. When the key just started a new recording (was_recording_before
// was false but is_recording_macro() is now true — the `a` in `qa`
// is the register-name bookkeeping key).
// 4. When the key was the second half of a @{reg} chord
// (was_play_macro_pending) — the register name is bookkeeping.
let is_recording_now = self.active().editor.is_recording_macro();
let is_replaying_now = self.active().editor.is_replaying_macro();
let just_started_recording = !was_recording_before && is_recording_now;
let register_name_of_play = was_play_macro_pending;
if consumed
&& is_recording_now
&& !is_replaying_now
&& !just_started_recording
&& !register_name_of_play
{
let input = hjkl_engine::Input::from(key);
if input.key != hjkl_engine::Key::Null {
self.active_mut().editor.record_input(input);
}
}
consumed
}
/// Inner implementation of `route_chord_key`. Returns `true` if the key
/// was consumed. The public wrapper adds the recorder hook on top.
fn route_chord_key_inner(&mut self, key: crossterm::event::KeyEvent) -> bool {
use crossterm::event::KeyCode;
use hjkl_vim::{Key as VimKey, Outcome};
// (1) pending_state reducer — fires in all modes when state is Some.
// Must precede the Non-Normal trie dispatch so the second key of a
// chord (e.g. second `g` of `gg` in VisualLine) reaches the commit
// arm instead of re-firing BeginPendingAfterG via the trie.
if let Some(state) = self.pending_state {
let vim_key = match key.code {
KeyCode::Char(c) => Some(VimKey::Char(c)),
KeyCode::Esc => Some(VimKey::Esc),
KeyCode::Enter => Some(VimKey::Enter),
KeyCode::Backspace => Some(VimKey::Backspace),
KeyCode::Tab => Some(VimKey::Tab),
_ => None,
};
if let Some(vk) = vim_key {
match hjkl_vim::step(state, vk) {
Outcome::Wait(new_state) => {
self.pending_state = Some(new_state);
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ReplaceChar { ch, count }) => {
self.pending_state = None;
self.active_mut().editor.replace_char_at(ch, count);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::FindChar {
ch,
forward,
till,
count,
}) => {
self.pending_state = None;
self.active_mut().editor.find_char(ch, forward, till, count);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::AfterGChord { ch, count }) => {
self.pending_state = None;
// App-level g-prefix actions dispatched before falling
// through to the engine.
match ch {
// Phase 6.4: `gv` — reenter last visual selection.
'v' => {
self.dispatch_action(
crate::keymap_actions::AppAction::ReenterLastVisual,
count as u32,
);
return true;
}
// Phase 6.4: `g*` / `g#` — word search without whole-word anchors.
'*' => {
self.dispatch_action(
crate::keymap_actions::AppAction::WordSearch {
forward: true,
whole_word: false,
count: count as u32,
},
count as u32,
);
return true;
}
'#' => {
self.dispatch_action(
crate::keymap_actions::AppAction::WordSearch {
forward: false,
whole_word: false,
count: count as u32,
},
count as u32,
);
return true;
}
't' => {
self.dispatch_action(
crate::keymap_actions::AppAction::Tabnext,
count as u32,
);
return true;
}
'T' => {
self.dispatch_action(
crate::keymap_actions::AppAction::Tabprev,
count as u32,
);
return true;
}
'd' => {
self.dispatch_action(
crate::keymap_actions::AppAction::LspGotoDef,
count as u32,
);
return true;
}
'D' => {
self.dispatch_action(
crate::keymap_actions::AppAction::LspGotoDecl,
count as u32,
);
return true;
}
'r' => {
self.dispatch_action(
crate::keymap_actions::AppAction::LspGotoRef,
count as u32,
);
return true;
}
'i' => {
self.dispatch_action(
crate::keymap_actions::AppAction::LspGotoImpl,
count as u32,
);
return true;
}
'y' => {
self.dispatch_action(
crate::keymap_actions::AppAction::LspGotoTypeDef,
count as u32,
);
return true;
}
_ => {}
}
// Chord-init case-ops: intercept u/U/~/q and set
// reducer AfterOp instead of calling after_g (which
// would set engine Pending::Op). This keeps the full
// gU/gu/g~/gq op-pending path inside the reducer.
let case_op_kind = match ch {
'u' => Some(hjkl_vim::OperatorKind::Lowercase),
'U' => Some(hjkl_vim::OperatorKind::Uppercase),
'~' => Some(hjkl_vim::OperatorKind::ToggleCase),
'q' => Some(hjkl_vim::OperatorKind::Reflow),
_ => None,
};
if let Some(op) = case_op_kind {
self.pending_state = Some(hjkl_vim::PendingState::AfterOp {
op,
count1: count,
inner_count: 0,
});
return true;
}
// All other g-chords: delegate to engine.
self.active_mut().editor.after_g(ch, count);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::AfterZChord { ch, count }) => {
self.pending_state = None;
// All z-chords delegate directly to the engine.
self.active_mut().editor.after_z(ch, count);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ApplyOpMotion {
op,
motion_key,
total_count,
}) => {
self.pending_state = None;
// AutoIndent with motion (=<motion>): dry-run the motion to
// find the row range, then submit the async formatter.
// Falls back to dumb algo when no formatter is registered.
let used_formatter = op == hjkl_vim::OperatorKind::AutoIndent && {
let range = self
.active_mut()
.editor
.range_for_op_motion(motion_key, total_count)
.map(|(r0, r1)| hjkl_mangler::RangeSpec {
start_row: r0,
end_row: r1,
});
self.submit_external_format(range)
};
if !used_formatter {
self.active_mut().editor.apply_op_motion(
event_loop::op_kind_to_operator(op),
motion_key,
total_count,
);
if let Some((top, bot)) =
self.active_mut().editor.take_last_indent_range()
{
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
}
}
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ApplyOpDouble { op, total_count }) => {
self.pending_state = None;
// AutoIndent (==): submit async formatter with cursor-row range.
// Falls back to dumb algo when no formatter is registered.
let used_formatter = op == hjkl_vim::OperatorKind::AutoIndent && {
let cursor_row = self.active().editor.cursor().0;
let end_row = cursor_row.saturating_add(total_count).saturating_sub(1);
let range = hjkl_mangler::RangeSpec {
start_row: cursor_row,
end_row,
};
self.submit_external_format(Some(range))
};
if !used_formatter {
self.active_mut()
.editor
.apply_op_double(event_loop::op_kind_to_operator(op), total_count);
if let Some((top, bot)) =
self.active_mut().editor.take_last_indent_range()
{
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
}
}
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ApplyOpTextObj {
op,
ch,
inner,
total_count,
}) => {
self.pending_state = None;
// AutoIndent text-obj (=ap, =i{, etc): dry-run text-object
// range query, then submit the async formatter if applicable.
let used_formatter = op == hjkl_vim::OperatorKind::AutoIndent && {
let range = self
.active()
.editor
.range_for_op_text_obj(ch, inner, total_count)
.map(|(r0, r1)| hjkl_mangler::RangeSpec {
start_row: r0,
end_row: r1,
});
self.submit_external_format(range)
};
if used_formatter {
self.sync_after_engine_mutation();
return true;
}
self.active_mut().editor.apply_op_text_obj(
event_loop::op_kind_to_operator(op),
ch,
inner,
total_count,
);
if let Some((top, bot)) = self.active_mut().editor.take_last_indent_range()
{
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
}
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ApplyOpG {
op,
ch,
total_count,
}) => {
self.pending_state = None;
// AutoIndent g-motion (=gg, =gj, etc): dry-run g-motion range
// query, then submit the async formatter if applicable.
let used_formatter = op == hjkl_vim::OperatorKind::AutoIndent && {
let range = self
.active_mut()
.editor
.range_for_op_g(ch, total_count)
.map(|(r0, r1)| hjkl_mangler::RangeSpec {
start_row: r0,
end_row: r1,
});
self.submit_external_format(range)
};
if used_formatter {
self.sync_after_engine_mutation();
return true;
}
self.active_mut().editor.apply_op_g(
event_loop::op_kind_to_operator(op),
ch,
total_count,
);
if let Some((top, bot)) = self.active_mut().editor.take_last_indent_range()
{
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
}
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::ApplyOpFind {
op,
ch,
forward,
till,
total_count,
}) => {
self.pending_state = None;
self.active_mut().editor.apply_op_find(
event_loop::op_kind_to_operator(op),
ch,
forward,
till,
total_count,
);
if let Some((top, bot)) = self.active_mut().editor.take_last_indent_range()
{
self.indent_flash = Some(IndentFlash {
top,
bot,
started_at: Instant::now(),
});
}
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::SetPendingRegister { reg }) => {
self.pending_state = None;
self.active_mut().editor.set_pending_register(reg);
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::SetMark { ch }) => {
self.pending_state = None;
self.active_mut().editor.set_mark_at_cursor(ch);
// No sync needed — set_mark_at_cursor does not move cursor.
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::GotoMarkLine { ch }) => {
self.pending_state = None;
self.active_mut().editor.goto_mark_line(ch);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::GotoMarkChar { ch }) => {
self.pending_state = None;
self.active_mut().editor.goto_mark_char(ch);
self.sync_after_engine_mutation();
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::StartMacroRecord { reg }) => {
// `q{reg}` chord completed — begin recording. The
// bookkeeping key (`q` itself) was already excluded from
// the recording by QChord's pending-count reset path;
// this register-char is also a bookkeeping key (it names
// the register, not a replay action), so the recorder hook
// below must skip it. We set pending_state = None before
// returning so the hook sees None and skips naturally.
self.pending_state = None;
self.active_mut().editor.start_macro_record(reg);
// Do NOT call the recorder hook here — the register char is
// bookkeeping, not a recorded keystroke. Return immediately.
return true;
}
Outcome::Commit(hjkl_vim::EngineCmd::PlayMacro { reg, count }) => {
self.pending_state = None;
if reg == ':' {
// `@:` — repeat last ex command. App-side storage,
// NOT routed through engine.play_macro (which would
// look in a register). count > 1 → repeat N times
// (vim semantics). Phase 5d of kryptic-sh/hjkl#71.
for _ in 0..count.max(1) {
self.replay_last_ex();
}
return true;
}
// `@{reg}` chord completed — decode and re-feed the macro.
let inputs = self.active_mut().editor.play_macro(reg, count);
// Re-feed each Input through route_chord_key by converting
// it back to a crossterm KeyEvent. During replay,
// is_replaying_macro() == true so the recorder hook skips
// the replayed inputs.
for input in inputs {
let ct_key = engine_input_to_key_event(input);
if ct_key.code != KeyCode::Null {
self.route_chord_key(ct_key);
}
}
self.active_mut().editor.end_macro_replay();
self.sync_after_engine_mutation();
return true;
}
Outcome::Cancel => {
self.pending_state = None;
return true;
}
Outcome::Forward => {
// State stays alive; fall through to step (2) below.
}
}
}
}
// (2) Non-Normal trie dispatch — gated on pending_state.is_none().
// Step (1) above already returns early when pending_state.is_some(),
// so this gate is logically redundant but documents intent: the second
// key of a chord (e.g. second `g` of `gg` in VisualLine) must reach
// the reducer's commit arm above, not re-fire the trie.
if self.pending_state.is_none()
&& self.active().editor.vim_mode() != hjkl_engine::VimMode::Normal
&& let Some(km_ev) = crate::keymap_translate::from_crossterm(&key)
&& let Some(km_mode) = current_km_mode(self)
{
let mut replay: Vec<hjkl_keymap::KeyEvent> = Vec::new();
let consumed = self.dispatch_keymap_in_mode(km_ev, 1, &mut replay, km_mode);
if consumed {
self.sync_after_engine_mutation();
return true;
}
// Unbound — fall through to engine.
}
// (3) Normal-mode keymap dispatch — only the trie step; count-prefix
// buffering and engine-pending bypass run in event_loop.rs before this
// call and set up the correct state for dispatch_keymap to read.
if self.pending_state.is_none()
&& self.active().editor.vim_mode() == hjkl_engine::VimMode::Normal
&& let Some(km_ev) = crate::keymap_translate::from_crossterm(&key)
{
let engine_pending = self.active().editor.is_chord_pending();
if !engine_pending {
let count = self.pending_count.peek().max(1);
let mut replay: Vec<hjkl_keymap::KeyEvent> = Vec::new();
let consumed = self.dispatch_keymap(km_ev, count, &mut replay);
if !consumed {
if !self.pending_count.is_empty() {
self.flush_pending_count_to_engine();
}
self.replay_to_engine(&replay);
}
self.sync_after_engine_mutation();
return true;
}
}
false
}
/// `@:` — replay the last ex command. No-op when nothing has been
/// dispatched yet. Phase 5d of kryptic-sh/hjkl#71.
pub(crate) fn replay_last_ex(&mut self) {
if let Some(cmd) = self.last_ex_command.clone() {
self.dispatch_ex(&cmd);
}
}
/// Force-resolve a pending chord buffer after the keymap timeout has
/// elapsed. Called from the event loop's poll-timeout branch when a chord
/// is pending (typically `Ambiguous`: e.g. both `g` and `gd` bound — the
/// shorter binding fires after `timeoutlen`).
///
/// Returns:
/// - `Some(events)` to be replayed to the engine for `Unbound` with
/// drained events (real dead-end case).
/// - `Some(empty)` after a `Match` (the action was already dispatched).
/// - `None` when the buffer was empty OR when the buffer is a pure prefix
/// (user is mid-chord and `timeout_resolve` left the buffer in place —
/// needed so the which-key popup stays visible past the timeout).
pub fn resolve_chord_timeout(
&mut self,
mode: keymap::HjklMode,
) -> Option<Vec<hjkl_keymap::KeyEvent>> {
use hjkl_keymap::KeyResolve;
if self.app_keymap.pending(mode).is_empty() {
return None;
}
match self.app_keymap.timeout_resolve(mode) {
KeyResolve::Match(binding) => {
self.clear_prefix_state();
self.dispatch_action(binding.action, 1);
Some(Vec::new())
}
KeyResolve::Unbound(events) if events.is_empty() => {
// Pure-prefix: timeout_resolve was a no-op. Keep prefix state
// alive so the which-key popup stays visible.
None
}
KeyResolve::Unbound(events) => {
self.clear_prefix_state();
Some(events)
}
// timeout_resolve only returns Match or Unbound; defensive fallthrough.
_ => None,
}
}
}
/// Return the current `HjklMode` based on the active editor's vim mode.
/// Returns `None` for modes with no keymap equivalent (currently none, but
/// Terminal mode would be `None` if ever added here).
pub(crate) fn current_km_mode(app: &App) -> Option<keymap::HjklMode> {
keymap::map_mode_to_km_mode(keymap::map_mode_for_vim(app.active().editor.vim_mode())?)
}