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
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
use std::{collections::HashMap, ops::ControlFlow, path::PathBuf};
use itertools::Itertools;
use nu_ansi_term::{Color, Style};
use crate::{enums::ReedlineRawEvent, CursorConfig};
#[cfg(feature = "bashisms")]
use crate::{
history::SearchFilter,
menu_functions::{parse_selection_char, ParseAction},
};
#[cfg(feature = "external_printer")]
use {
crate::external_printer::ExternalPrinter,
crossbeam::channel::TryRecvError,
std::io::{Error, ErrorKind},
};
use {
crate::{
completion::{Completer, CompletionOrigin, CompletionStatus, DefaultCompleter},
core_editor::Editor,
edit_mode::{EditMode, Emacs},
enums::{EventStatus, ReedlineEvent},
highlighter::SimpleMatchHighlighter,
hinter::Hinter,
history::{
FileBackedHistory, History, HistoryCursor, HistoryItem, HistoryItemId,
HistoryNavigationQuery, HistorySessionId, SearchDirection, SearchQuery,
},
painting::{Painter, PainterSuspendedState, PromptLines, RenderSnapshot, W},
prompt::{PromptEditMode, PromptHistorySearchStatus},
result::{ReedlineError, ReedlineErrorVariants},
terminal_extensions::{
bracketed_paste::BracketedPasteGuard,
kitty::KittyProtocolGuard,
semantic_prompt::{Osc133ClickEventsMarkers, SemanticPromptMarkers},
},
utils::text_manipulation,
AbbrExpandContext, EditCommand, ExampleHighlighter, Highlighter, LineBuffer, Menu,
MenuEvent, MouseButton, Prompt, PromptHistorySearch, ReedlineMenu, Signal, UndoBehavior,
ValidationResult, Validator,
},
crossterm::{
cursor::{SetCursorStyle, Show},
event,
event::{Event, KeyCode, KeyEvent, KeyModifiers},
terminal, QueueableCommand,
},
std::{
fs::File,
io,
io::Result,
io::Write,
process::Command,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
time::SystemTime,
},
};
// The POLL_WAIT is used to specify for how long the POLL should wait for
// events, to accelerate the handling of paste or compound resize events. Having
// a POLL_WAIT of zero means that every single event is treated as soon as it
// arrives. This doesn't allow for the possibility of more than 1 event
// happening at the same time.
const POLL_WAIT: Duration = Duration::from_millis(100);
// Since a paste event is multiple `Event::Key` events happening at the same
// time, we specify how many events should be in the `crossterm_events` vector
// before it is considered a paste. 10 events is conservative enough.
const EVENTS_THRESHOLD: usize = 10;
/// Default maximum time Reedline will block on input before yielding control
/// for features that require periodic processing (e.g., external printer,
/// idle callback).
const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(100);
/// Determines if inputs should be used to extend the regular line buffer,
/// traverse the history in the standard prompt or edit the search string in the
/// reverse search
#[derive(Debug, PartialEq, Eq)]
enum InputMode {
/// Regular input by user typing or previous insertion.
/// Undo tracking is active
Regular,
/// Full reverse search mode with different prompt,
/// editing affects the search string,
/// suggestions are provided to be inserted in the line buffer
HistorySearch,
/// Hybrid mode indicating that history is walked through in the standard prompt
/// Either bash style up/down history or fish style prefix search,
/// Edits directly switch to [`InputMode::Regular`]
HistoryTraversal,
}
/// Configuration for mouse click-to-cursor support.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum MouseClickMode {
/// Disable mouse click handling.
#[default]
Disabled,
/// Enable mouse click handling without emitting OSC 133 markers.
Enabled,
/// Enable mouse click handling and emit OSC 133 markers with `click_events=1`.
EnabledWithOsc133,
}
impl MouseClickMode {
fn is_enabled(self) -> bool {
matches!(self, Self::Enabled | Self::EnabledWithOsc133)
}
}
/// Line editor engine
///
/// ## Example usage
/// ```no_run
/// use reedline::{Reedline, Signal, DefaultPrompt};
/// let mut line_editor = Reedline::create();
/// let prompt = DefaultPrompt::default();
///
/// let out = line_editor.read_line(&prompt).unwrap();
/// match out {
/// Signal::Success(content) => {
/// // process content
/// }
/// _ => {
/// eprintln!("Entry aborted!");
///
/// }
/// }
/// ```
pub struct Reedline {
editor: Editor,
// History
history: Box<dyn History>,
history_cursor: HistoryCursor,
history_session_id: Option<HistorySessionId>,
// none if history doesn't support this
history_last_run_id: Option<HistoryItemId>,
history_exclusion_prefix: Option<String>,
history_excluded_item: Option<HistoryItem>,
history_cursor_on_excluded: bool,
input_mode: InputMode,
// State of the painter after a `ReedlineEvent::ExecuteHostCommand` was requested, used after
// execution to decide if we can re-use the previous prompt or paint a new one.
suspended_state: Option<PainterSuspendedState>,
last_render_snapshot: Option<RenderSnapshot>,
// Validator
validator: Option<Box<dyn Validator>>,
// Stdout
painter: Painter,
transient_prompt: Option<Box<dyn Prompt>>,
// Edit Mode: Vi, Emacs
edit_mode: Box<dyn EditMode>,
// Provides the tab completions
completer: Box<dyn Completer + Send>,
quick_completions: bool,
partial_completions: bool,
persistent_menus: bool,
// Completions owed to a menu activation the completer could not answer in time
deferred_menu_completion: Option<DeferredMenuCompletion>,
// Highlight the edit buffer
highlighter: Box<dyn Highlighter>,
// Style used for visual selection
visual_selection_style: Style,
/// A distinct style for the cell under the cursor inside a selection;
/// `None` leaves the cell on `visual_selection_style`.
visual_selection_cursor_style: Option<Style>,
// Showcase hints based on various strategies (history, language-completion, spellcheck, etc)
hinter: Option<Box<dyn Hinter>>,
hide_hints: bool,
// Use ansi coloring or not
use_ansi_coloring: bool,
// Whether to enable mouse click-to-cursor functionality
mouse_click_mode: MouseClickMode,
// Current working directory as defined by the application. If set, it will
// override the actual working directory of the process.
cwd: Option<String>,
// Engine Menus
menus: Vec<ReedlineMenu>,
abbreviations: HashMap<String, String>,
// Text editor used to open the line buffer for editing
buffer_editor: Option<BufferEditor>,
// Use different cursors depending on the current edit mode
cursor_shapes: Option<CursorConfig>,
// Manage bracketed paste mode
bracketed_paste: BracketedPasteGuard,
// Manage optional kitty protocol
kitty_protocol: KittyProtocolGuard,
// Whether lines should be accepted immediately
immediately_accept: bool,
// External break signal: when set to `true`, `read_line()` will return
// `Signal::ExternalBreak` with the current buffer contents.
break_signal: Option<Arc<AtomicBool>>,
// External repaint signal: when triggered, the prompt is re-evaluated
// and repainted in place while `read_line()` is running.
repaint_signal: Option<RepaintSignal>,
// Maximum time to block on input before yielding control for features that
// require periodic processing (external printer, idle callback).
// Only used when external_printer or idle_callback is configured.
poll_interval: Duration,
#[cfg(feature = "external_printer")]
external_printer: Option<ExternalPrinter<String>>,
// Callback function that is called periodically while waiting for input.
// Useful for processing external events (e.g., GUI updates) during idle time.
#[cfg(feature = "idle_callback")]
idle_callback: Option<Box<dyn FnMut() + Send>>,
}
struct BufferEditor {
command: Command,
temp_file: PathBuf,
}
/// The completions the [`Menu`](ReedlineEvent::Menu) event could not decide, because the
/// completer had not answered yet.
///
/// Activating a menu immediately inspects its values twice: quick completions accept a
/// lone suggestion, and partial completions splice in the prefix the suggestions share.
/// A completer computing in the background can answer neither yet.
///
/// The snapshot pins the editor state as of the keystroke this was armed on: a result
/// landing after the user has typed on is discarded rather than rewriting the line
/// underneath them.
struct DeferredMenuCompletion {
menu: String,
/// The line this was armed on, stamped as a completer stamps its own results.
origin: CompletionOrigin,
}
impl DeferredMenuCompletion {
fn new(menu: &ReedlineMenu, editor: &Editor) -> Self {
Self {
menu: menu.name().to_string(),
origin: CompletionOrigin::new(editor.get_buffer(), editor.insertion_point()),
}
}
/// Whether the line is still exactly as it was when this was armed, on the same menu.
/// Anything else means the user moved on and the decision is void.
fn still_applies(&self, menu: &ReedlineMenu, editor: &Editor) -> bool {
self.menu == menu.name()
&& self
.origin
.matches(editor.get_buffer(), editor.insertion_point())
}
}
/// Call [`request_repaint`](RepaintSignal::request_repaint) once
/// new prompt data is ready! The next iteration of the input loop re-evaluates
/// the [`Prompt`] and redraws it without interrupting the current line edit.
#[derive(Clone, Debug, Default)]
pub struct RepaintSignal {
flag: Arc<AtomicBool>,
}
impl RepaintSignal {
/// Request that the prompt is re-evaluated and repainted in place.
pub fn request_repaint(&self) {
self.flag.store(true, Ordering::Relaxed);
}
/// Consume a pending repaint request.
fn take(&self) -> bool {
self.flag.swap(false, Ordering::Relaxed)
}
}
impl Drop for Reedline {
fn drop(&mut self) {
if self.cursor_shapes.is_some() {
let _ignore = terminal::enable_raw_mode();
let mut stdout = std::io::stdout();
let _ignore = stdout.queue(SetCursorStyle::DefaultUserShape);
let _ignore = stdout.queue(Show);
let _ignore = stdout.flush();
}
// Ensures that the terminal is in a good state if we panic semigracefully
// Calling `disable_raw_mode()` twice is fine with Linux
let _ignore = terminal::disable_raw_mode();
}
}
/// Mark the painter's cached prompt anchor stale around a menu running its completer,
/// which may have left the cached row pointing at content that has scrolled. See
/// [`ReedlineMenu::queries_host_completer`] for why only some completers count, and
/// #1130 for the bug.
///
/// Also skipped for a menu the same keystroke deactivated, whose queued event nothing
/// goes on to consume.
///
/// Call this from every event that reaches the completer, which is not the same set as
/// the events that change the menu's selection: `MenuNext` splices a partial completion
/// and queries, while `MenuPrevious` only moves and does not.
fn invalidate_anchor_if_host_completer_runs(menu: &ReedlineMenu, painter: &mut Painter) {
if menu.is_active() && menu.queries_host_completer() {
painter.invalidate_prompt_start_row();
}
}
impl Reedline {
const FILTERED_ITEM_ID: HistoryItemId = HistoryItemId(i64::MAX);
/// Create a new [`Reedline`] engine with a local [`History`] that is not synchronized to a file.
#[must_use]
pub fn create() -> Self {
let history = Box::<FileBackedHistory>::default();
#[cfg(not(test))]
let painter = Painter::new(W::terminal());
#[cfg(test)]
let painter = Painter::new(W::sink());
let buffer_highlighter = Box::<ExampleHighlighter>::default();
let visual_selection_style = Style::new().on(Color::LightGray);
let completer = Box::<DefaultCompleter>::default();
let hinter = None;
let validator = None;
let edit_mode = Box::<Emacs>::default();
let hist_session_id = None;
Reedline {
editor: Editor::default(),
history,
history_cursor: HistoryCursor::new(
HistoryNavigationQuery::Normal(LineBuffer::default()),
hist_session_id,
),
history_session_id: hist_session_id,
history_last_run_id: None,
history_exclusion_prefix: None,
history_excluded_item: None,
history_cursor_on_excluded: false,
input_mode: InputMode::Regular,
suspended_state: None,
last_render_snapshot: None,
painter,
transient_prompt: None,
edit_mode,
completer,
quick_completions: false,
partial_completions: false,
persistent_menus: false,
deferred_menu_completion: None,
highlighter: buffer_highlighter,
visual_selection_style,
visual_selection_cursor_style: None,
hinter,
hide_hints: false,
validator,
use_ansi_coloring: true,
mouse_click_mode: MouseClickMode::default(),
cwd: None,
menus: Vec::new(),
abbreviations: HashMap::new(),
buffer_editor: None,
cursor_shapes: None,
bracketed_paste: BracketedPasteGuard::default(),
kitty_protocol: KittyProtocolGuard::default(),
immediately_accept: false,
break_signal: None,
repaint_signal: None,
poll_interval: DEFAULT_POLL_INTERVAL,
#[cfg(feature = "external_printer")]
external_printer: None,
#[cfg(feature = "idle_callback")]
idle_callback: None,
}
}
/// Get a new history session id based on the current time and the first commit datetime of reedline
pub fn create_history_session_id() -> Option<HistorySessionId> {
let nanos = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_nanos() as i64,
Err(_) => 0,
};
Some(HistorySessionId::new(nanos))
}
/// Toggle whether reedline enables bracketed paste to reed copied content
///
/// This currently alters the behavior for multiline pastes as pasting of regular text will
/// execute after every complete new line as determined by the [`Validator`]. With enabled
/// bracketed paste all lines will appear in the buffer and can then be submitted with a
/// separate enter.
///
/// At this point most terminals should support it or ignore the setting of the necessary
/// flags. For full compatibility, keep it disabled.
pub fn use_bracketed_paste(mut self, enable: bool) -> Self {
self.bracketed_paste.set(enable);
self
}
/// Toggle whether reedline uses the kitty keyboard enhancement protocol
///
/// This allows us to disambiguate more events than the traditional standard
/// Only available with a few terminal emulators.
/// You can check for that with [`crate::kitty_protocol_available`]
/// `Reedline` will perform this check internally
///
/// Read more: <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>
pub fn use_kitty_keyboard_enhancement(mut self, enable: bool) -> Self {
self.kitty_protocol.set(enable);
self
}
/// Return the previously generated history session id
pub fn get_history_session_id(&self) -> Option<HistorySessionId> {
self.history_session_id
}
/// Set a new history session id
/// This should be used in situations where the user initially did not have a history_session_id
/// and then later realized they want to have one without restarting the application.
pub fn set_history_session_id(&mut self, session: Option<HistorySessionId>) -> Result<()> {
self.history_session_id = session;
Ok(())
}
/// A builder to include a [`Hinter`] in your instance of the Reedline engine
/// # Example
/// ```rust
/// //Cargo.toml
/// //[dependencies]
/// //nu-ansi-term = "*"
/// use {
/// nu_ansi_term::{Color, Style},
/// reedline::{DefaultHinter, Reedline},
/// };
///
/// let mut line_editor = Reedline::create().with_hinter(Box::new(
/// DefaultHinter::default()
/// .with_style(Style::new().italic().fg(Color::LightGray)),
/// ));
/// ```
#[must_use]
pub fn with_hinter(mut self, hinter: Box<dyn Hinter>) -> Self {
self.hinter = Some(hinter);
self
}
/// Remove current [`Hinter`]
#[must_use]
pub fn disable_hints(mut self) -> Self {
self.hinter = None;
self
}
/// A builder to configure the tab completion
/// # Example
/// ```rust
/// // Create a reedline object with tab completions support
///
/// use reedline::{DefaultCompleter, Reedline};
///
/// let commands = vec![
/// "test".into(),
/// "hello world".into(),
/// "hello world reedline".into(),
/// "this is the reedline crate".into(),
/// ];
/// let completer = Box::new(DefaultCompleter::new_with_wordlen(commands.clone(), 2));
///
/// let mut line_editor = Reedline::create().with_completer(completer);
/// ```
#[must_use]
pub fn with_completer(mut self, completer: Box<dyn Completer + Send>) -> Self {
self.completer = completer;
self
}
/// Turn on quick completions. These completions will auto-select if the completer
/// ever narrows down to a single entry.
#[must_use]
pub fn with_quick_completions(mut self, quick_completions: bool) -> Self {
self.quick_completions = quick_completions;
self
}
/// Control whether the cursor crosses line boundaries on left/right motions
/// in a block caret (vi normal/visual mode). When `true` (the default), `l`
/// at the end of a line moves to the next line's first character and `h` at
/// column 0 to the previous line's last; when `false`, both stop at the line
/// edge (vim's default `h`/`l`). Has no effect on emacs or vi insert mode,
/// whose bar caret always moves freely across lines.
///
/// Scope: this steers where the **caret rests** on `h`/`l`, not how far an
/// operator reaches. Operator motions (`d`/`c`/`y`) delete the literal
/// grapheme span regardless of this flag, so e.g. `dl` always deletes the
/// char under the caret and never the line break.
#[must_use]
pub fn with_cross_line_cursor(mut self, cross_line_cursor: bool) -> Self {
self.editor.set_cross_line_cursor(cross_line_cursor);
self
}
/// Turn on partial completions. These completions will fill the buffer with the
/// smallest common string from all the options
#[must_use]
pub fn with_partial_completions(mut self, partial_completions: bool) -> Self {
self.partial_completions = partial_completions;
self
}
/// Make active menus persist while the line is edited: erasing characters
/// or emptying the line refilters the menu instead of dismissing it.
///
/// When disabled (the default), an active menu is deactivated by a backspace
/// when quick completions are on, and by any edit that leaves the line
/// buffer empty. A persistent menu still closes on Esc, Ctrl-C, or when a
/// value is accepted.
#[must_use]
pub fn with_persistent_menus(mut self, persistent_menus: bool) -> Self {
self.persistent_menus = persistent_menus;
self
}
/// A builder which enables or disables the use of ansi coloring in the prompt
/// and in the command line syntax highlighting.
#[must_use]
pub fn with_ansi_colors(mut self, use_ansi_coloring: bool) -> Self {
self.use_ansi_coloring = use_ansi_coloring;
self
}
/// Configure mouse click-to-cursor support.
///
/// Use [`MouseClickMode::Enabled`] to handle click events when your host shell
/// emits OSC 133 markers. Use [`MouseClickMode::EnabledWithOsc133`] to have
/// Reedline emit OSC 133 markers with `click_events=1` so supporting terminals
/// can send click events.
/// See: <https://sw.kovidgoyal.net/kitty/shell-integration/#notes-for-shell-developers>
#[must_use]
pub fn with_mouse_click(mut self, mode: MouseClickMode) -> Self {
self.mouse_click_mode = mode;
if matches!(mode, MouseClickMode::EnabledWithOsc133) {
self.painter
.set_semantic_markers(Some(Osc133ClickEventsMarkers::boxed()));
}
self
}
/// Update current working directory.
#[must_use]
pub fn with_cwd(mut self, cwd: Option<String>) -> Self {
self.cwd = cwd;
self
}
/// A builder that configures the highlighter for your instance of the Reedline engine
/// # Example
/// ```rust
/// // Create a reedline object with highlighter support
///
/// use reedline::{ExampleHighlighter, Reedline};
///
/// let commands = vec![
/// "test".into(),
/// "hello world".into(),
/// "hello world reedline".into(),
/// "this is the reedline crate".into(),
/// ];
/// let mut line_editor =
/// Reedline::create().with_highlighter(Box::new(ExampleHighlighter::new(commands)));
/// ```
#[must_use]
pub fn with_highlighter(mut self, highlighter: Box<dyn Highlighter>) -> Self {
self.highlighter = highlighter;
self
}
/// A builder that configures the style used for visual selection
#[must_use]
pub fn with_visual_selection_style(mut self, style: Style) -> Self {
self.visual_selection_style = style;
self
}
/// A builder that gives the cell under the cursor its own style inside a
/// visual selection, the way helix styles its primary cursor distinctly
/// from the selection around it. Left unset, the cell keeps the plain
/// selection style, which can paint a flat selection (e.g. reverse video)
/// over the terminal cursor and hide it.
#[must_use]
pub fn with_visual_selection_cursor_style(mut self, style: Style) -> Self {
self.visual_selection_cursor_style = Some(style);
self
}
/// A builder which configures the history for your instance of the Reedline engine
/// # Example
/// ```rust,no_run
/// // Create a reedline object with history support, including history size limits
///
/// use reedline::{FileBackedHistory, Reedline};
///
/// let history = Box::new(
/// FileBackedHistory::with_file(5, "history.txt".into())
/// .expect("Error configuring history with file"),
/// );
/// let mut line_editor = Reedline::create()
/// .with_history(history);
/// ```
#[must_use]
pub fn with_history(mut self, history: Box<dyn History>) -> Self {
self.history = history;
self
}
/// A builder which configures history exclusion for your instance of the Reedline engine
/// # Example
/// ```rust,no_run
/// // Create a reedline instance with history that will *not* include commands starting with a space
///
/// use reedline::{FileBackedHistory, Reedline};
///
/// let history = Box::new(
/// FileBackedHistory::with_file(5, "history.txt".into())
/// .expect("Error configuring history with file"),
/// );
/// let mut line_editor = Reedline::create()
/// .with_history(history)
/// .with_history_exclusion_prefix(Some(" ".into()));
/// ```
#[must_use]
pub fn with_history_exclusion_prefix(mut self, ignore_prefix: Option<String>) -> Self {
self.history_exclusion_prefix = ignore_prefix;
self
}
/// A builder that configures the validator for your instance of the Reedline engine
/// # Example
/// ```rust
/// // Create a reedline object with validator support
///
/// use reedline::{DefaultValidator, Reedline};
///
/// let mut line_editor =
/// Reedline::create().with_validator(Box::new(DefaultValidator));
/// ```
#[must_use]
pub fn with_validator(mut self, validator: Box<dyn Validator>) -> Self {
self.validator = Some(validator);
self
}
/// A builder that configures the alternate text editor used to edit the line buffer
///
/// You are responsible for providing a file path that is unique to this reedline session
///
/// # Example
/// ```rust,no_run
/// // Create a reedline object with vim as editor
///
/// use reedline::Reedline;
/// use std::env::temp_dir;
/// use std::process::Command;
///
/// let temp_file = std::env::temp_dir().join("my-random-unique.file");
/// let mut command = Command::new("vim");
/// // you can provide additional flags:
/// command.arg("-p"); // open in a vim tab (just for demonstration)
/// // you don't have to pass the filename to the command
/// let mut line_editor =
/// Reedline::create().with_buffer_editor(command, temp_file);
/// ```
#[must_use]
pub fn with_buffer_editor(mut self, editor: Command, temp_file: PathBuf) -> Self {
let mut editor = editor;
if !editor.get_args().contains(&temp_file.as_os_str()) {
editor.arg(&temp_file);
}
self.buffer_editor = Some(BufferEditor {
command: editor,
temp_file,
});
self
}
/// Remove the current [`Validator`]
#[must_use]
pub fn disable_validator(mut self) -> Self {
self.validator = None;
self
}
/// Set a different prompt to be used after submitting each line
#[must_use]
pub fn with_transient_prompt(mut self, transient_prompt: Box<dyn Prompt>) -> Self {
self.transient_prompt = Some(transient_prompt);
self
}
/// A builder that configures semantic prompt markers for terminal integration.
///
/// This enables semantic prompt support for terminals that support it, such as Ghostty.
/// Use `Osc133Markers::boxed()` for standard terminal support or `Osc633Markers::boxed()`
/// for VS Code integrated terminal support.
#[must_use]
pub fn with_semantic_markers(
mut self,
markers: Option<Box<dyn SemanticPromptMarkers>>,
) -> Self {
self.painter.set_semantic_markers(markers);
self
}
/// A builder which configures the edit mode for your instance of the Reedline engine
#[must_use]
pub fn with_edit_mode(mut self, edit_mode: Box<dyn EditMode>) -> Self {
self.edit_mode = edit_mode;
self
}
/// A builder that appends a menu to the engine
#[must_use]
pub fn with_menu(mut self, menu: ReedlineMenu) -> Self {
self.menus.push(menu);
self
}
/// A builder that clears the list of menus added to the engine
#[must_use]
pub fn clear_menus(mut self) -> Self {
self.menus = Vec::new();
self
}
/// A builder that adds abbreviations to the Reedline engine
///
/// Overwrites any existing abbreviations with the same key.
///
/// Note, by default abbreviations are expanded everywhere. To suppress expansion in certain
/// syntactic positions (e.g. string literals), override [`Highlighter::should_expand_abbr`].
pub fn with_abbreviations(mut self, abbreviations: HashMap<String, String>) -> Self {
self.abbreviations.extend(abbreviations);
self
}
/// A builder that adds the history item id
#[must_use]
pub fn with_history_session_id(mut self, session: Option<HistorySessionId>) -> Self {
self.history_session_id = session;
self
}
/// A builder that enables reedline changing the cursor shape based on the current edit mode.
/// The current implementation sets the cursor shape when drawing the prompt.
/// Do not use this if the cursor shape is set elsewhere, e.g. in the terminal settings or by ansi escape sequences.
pub fn with_cursor_config(mut self, cursor_shapes: CursorConfig) -> Self {
self.cursor_shapes = Some(cursor_shapes);
self
}
/// A builder that configures whether reedline should immediately accept the input.
pub fn with_immediately_accept(mut self, immediately_accept: bool) -> Self {
self.immediately_accept = immediately_accept;
self
}
/// A builder that configures an external break signal.
///
/// When the [`AtomicBool`] is set to `true` by an external thread,
/// [`Reedline::read_line()`] will return [`Signal::ExternalBreak`] with the
/// current buffer contents. The flag is automatically reset to `false`
/// after being consumed.
pub fn with_break_signal(mut self, signal: Arc<AtomicBool>) -> Self {
self.break_signal = Some(signal);
self
}
/// Get a [`RepaintSignal`] handle that can trigger an in-place repaint of
/// the prompt from another thread while [`Reedline::read_line()`] is
/// running, avoiding interfering with current line edit.
pub fn repaint_signal(&mut self) -> RepaintSignal {
// The handle is created lazily on the first call; subsequent calls return clones
self.repaint_signal
.get_or_insert_with(RepaintSignal::default)
.clone()
}
/// Returns the corresponding expected prompt style for the given edit mode
pub fn prompt_edit_mode(&self) -> PromptEditMode {
self.edit_mode.edit_mode()
}
/// Output the complete [`History`] chronologically with numbering to the terminal
pub fn print_history(&mut self) -> Result<()> {
let history: Vec<_> = self
.history
.search(SearchQuery::everything(SearchDirection::Forward, None))
.expect("todo: error handling");
for (i, entry) in history.iter().enumerate() {
self.print_line(&format!("{}\t{}", i, entry.command_line))?;
}
Ok(())
}
/// Output the complete [`History`] for this session, chronologically with numbering to the terminal
pub fn print_history_session(&mut self) -> Result<()> {
let history: Vec<_> = self
.history
.search(SearchQuery::everything(
SearchDirection::Forward,
self.get_history_session_id(),
))
.expect("todo: error handling");
for (i, entry) in history.iter().enumerate() {
self.print_line(&format!("{}\t{}", i, entry.command_line))?;
}
Ok(())
}
/// Print the history session id
pub fn print_history_session_id(&mut self) -> Result<()> {
println!("History Session Id: {:?}", self.get_history_session_id());
Ok(())
}
/// Toggle between having a history that uses the history session id and one that does not
pub fn toggle_history_session_matching(
&mut self,
session: Option<HistorySessionId>,
) -> Result<()> {
self.history_session_id = match self.get_history_session_id() {
Some(_) => None,
None => session,
};
Ok(())
}
/// Read-only view of the history
pub fn history(&self) -> &dyn History {
&*self.history
}
/// Mutable view of the history
pub fn history_mut(&mut self) -> &mut dyn History {
&mut *self.history
}
/// Update the underlying [`History`] to/from disk
pub fn sync_history(&mut self) -> std::io::Result<()> {
// TODO: check for interactions in the non-submitting events
self.history.sync()
}
/// Check if any commands have been run.
///
/// When no commands have been run, calling [`Self::update_last_command_context`]
/// does not make sense and is guaranteed to fail with a "No command run" error.
pub fn has_last_command_context(&self) -> bool {
self.history_last_run_id.is_some()
}
/// update the last history item with more information
pub fn update_last_command_context(
&mut self,
f: &dyn Fn(HistoryItem) -> HistoryItem,
) -> crate::Result<()> {
match &self.history_last_run_id {
Some(Self::FILTERED_ITEM_ID) => {
self.history_excluded_item = Some(f(self.history_excluded_item.take().unwrap()));
Ok(())
}
Some(r) => self.history.update(*r, f),
None => Err(ReedlineError(ReedlineErrorVariants::OtherHistoryError(
"No command run",
))),
}
}
/// Wait for input and provide the user with a specified [`Prompt`].
///
/// Returns a [`std::io::Result`] in which the `Err` type is [`std::io::Result`]
/// and the `Ok` variant wraps a [`Signal`] which handles user inputs.
pub fn read_line(&mut self, prompt: &dyn Prompt) -> Result<Signal> {
terminal::enable_raw_mode()?;
self.bracketed_paste.enter();
self.kitty_protocol.enter();
let result = self.read_line_helper(prompt);
self.bracketed_paste.exit();
self.kitty_protocol.exit();
terminal::disable_raw_mode()?;
result
}
/// Returns the current insertion point of the input buffer.
pub fn current_insertion_point(&self) -> usize {
self.editor.insertion_point()
}
/// Returns the current contents of the input buffer.
pub fn current_buffer_contents(&self) -> &str {
self.editor.get_buffer()
}
/// Writes `msg` to the terminal with a following carriage return and newline
fn print_line(&mut self, msg: &str) -> Result<()> {
self.painter.paint_line(msg)
}
/// Clear the screen by printing enough whitespace to start the prompt or
/// other output back at the first line of the terminal.
pub fn clear_screen(&mut self) -> Result<()> {
self.painter.clear_screen()?;
Ok(())
}
/// Clear the screen and the scrollback buffer of the terminal
pub fn clear_scrollback(&mut self) -> Result<()> {
self.painter.clear_scrollback()?;
Ok(())
}
/// Consume a pending external repaint request, returning whether one was
/// pending. Any number of requests since the last check collapse into one.
fn take_repaint_request(&self) -> bool {
self.repaint_signal
.as_ref()
.is_some_and(RepaintSignal::take)
}
/// Whether the input loop must poll with a timeout instead of blocking
/// indefinitely, so external triggers (break signal, repaint signal,
/// external printer, idle callback) are noticed while waiting for input.
fn input_needs_polling(&self) -> bool {
#[allow(unused_mut)] // Dependent on feature flags
let mut poll = self.break_signal.is_some()
|| self
.repaint_signal
.as_ref()
.is_some_and(|sig| Arc::strong_count(&sig.flag) > 1);
#[cfg(feature = "external_printer")]
{
poll |= self.external_printer.is_some();
}
#[cfg(feature = "idle_callback")]
{
poll |= self.idle_callback.is_some();
}
poll
}
/// Helper implementing the logic for [`Reedline::read_line()`] to be wrapped
/// in a `raw_mode` context.
fn read_line_helper(&mut self, prompt: &dyn Prompt) -> Result<Signal> {
self.painter
.initialize_prompt_position(self.suspended_state.as_ref())?;
if self.suspended_state.is_some() {
// Last editor was suspended (ExecuteHostCommand or ExternalBreak),
// we are resuming operation now.
self.suspended_state = None;
}
self.hide_hints = false;
// Repaint requests raised while no read_line was active are stale:
// the fresh prompt painted below already reflects the latest state.
self.take_repaint_request();
self.repaint(prompt)?;
loop {
// Call idle callback if set (for processing external events like GUI updates)
#[cfg(feature = "idle_callback")]
if let Some(ref mut callback) = self.idle_callback {
callback();
// The callback owns stdout while it runs and may have
// written or moved the cursor. Re-verify the anchor on
// the next paint.
self.painter.invalidate_prompt_start_row();
}
if let Some(ref signal) = self.break_signal {
if signal.swap(false, std::sync::atomic::Ordering::Relaxed) {
let buffer = self.editor.get_buffer().to_string();
self.input_mode = InputMode::Regular;
self.last_render_snapshot = None;
self.suspended_state = Some(self.painter.state_before_suspension());
self.editor.reset_undo_stack();
return Ok(Signal::ExternalBreak(buffer));
}
}
if self.take_repaint_request() {
self.repaint(prompt)?;
}
#[cfg(feature = "external_printer")]
if let Some(ref external_printer) = self.external_printer {
// get messages from printer as crlf separated "lines"
let messages = Self::external_messages(external_printer)?;
if !messages.is_empty() {
// print the message(s)
self.painter.print_external_message(
messages,
self.editor.line_buffer(),
prompt,
)?;
self.repaint(prompt)?;
}
}
// Determine if we need to poll (non-blocking) or can block on input.
// We need polling if external_printer or idle_callback is configured,
// using the shared poll_interval for the timeout.
let status = self.completer.poll_completion();
// Anything BUT idle means work is in flight. We need to keep polling.
let completer_pending = status != CompletionStatus::Idle;
if status == CompletionStatus::Ready {
self.settle_completions(prompt)?;
}
// Helper function that returns true if the input is complete and
// can be sent to the hosting application.
fn completed(events: &[Event]) -> bool {
if let Some(event) = events.last() {
matches!(
event,
Event::Key(KeyEvent {
code: KeyCode::Enter,
modifiers: KeyModifiers::NONE,
..
})
)
} else {
false
}
}
let mut events: Vec<Event> = vec![];
if !self.immediately_accept {
if self.input_needs_polling() || completer_pending {
if event::poll(self.poll_interval)? {
events.push(crossterm::event::read()?);
}
} else {
// Block until we receive an event
events.push(crossterm::event::read()?);
}
// Receive all events in the queue without blocking. Will stop when
// a line of input is completed.
while !completed(&events) && event::poll(Duration::from_millis(0))? {
events.push(crossterm::event::read()?);
}
// If we believe there's text pasting or resizing going on, batch
// more events at the cost of a slight delay.
if events.len() > EVENTS_THRESHOLD
|| events.iter().any(|e| matches!(e, Event::Resize(_, _)))
{
while !completed(&events) && event::poll(POLL_WAIT)? {
events.push(crossterm::event::read()?);
}
}
}
// Process the batch unconditionally: in `immediately_accept` mode
// `events` stays empty, but `process_input_batch` still pushes the
// synthetic `Submit` and returns the buffer. Gating this call behind
// `!immediately_accept` would spin the loop forever.
if let ControlFlow::Break(signal) = self.process_input_batch(prompt, events)? {
return Ok(signal);
}
}
}
/// Fold a finished completion request into the active menu, and honor the completions
/// owed from when the request was made.
///
/// Called when the completer reports [`CompletionStatus::Ready`]. Kept out of the
/// input loop so it is reachable from tests, which cannot drive the loop itself.
fn settle_completions(&mut self, prompt: &dyn Prompt) -> Result<()> {
let Some(menu_index) = self.menus.iter().position(|menu| menu.is_active()) else {
// No menu to answer to, so nothing can still be owed.
self.deferred_menu_completion = None;
return Ok(());
};
// The request that just finished was host code, which may have scrolled the
// terminal while it ran in the background — after the keystroke that
// dispatched it had already re-verified the anchor. `update_values` below
// can also dispatch another request for a line that moved on. Either way
// the repaint at the end of this settle must not trust the cached row.
invalidate_anchor_if_host_completer_runs(&self.menus[menu_index], &mut self.painter);
let menu = &mut self.menus[menu_index];
// The request this menu was waiting on finished, so repopulate it.
menu.update_values(
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
let still_provisional = menu.results_are_provisional();
let owed = self
.deferred_menu_completion
.as_ref()
.is_some_and(|deferred| deferred.still_applies(menu, &self.editor));
// Values were just refreshed above, so the menu must not re-fetch them.
let accept_lone_value =
owed && !still_provisional && self.decide_menu_completion(menu_index, true);
// Spent once a final answer had its say, so it cannot act on a later one.
// Provisional results decided nothing, so the arm outlives them.
if !still_provisional {
self.deferred_menu_completion = None;
}
if accept_lone_value {
// With a menu active this replaces in the buffer and deactivates, rather than
// submitting the line.
self.handle_editor_event(prompt, ReedlineEvent::Enter)?;
}
// One paint for every outcome, since painting the menu and then the accepted or
// extended line would flicker on each completion.
self.repaint(prompt)
}
/// The completion an opening menu applies to the line: a lone suggestion is accepted
/// outright, otherwise the prefix the suggestions share is spliced in. Returns whether
/// the caller should accept that lone suggestion.
///
/// Both the [`Menu`](ReedlineEvent::Menu) event and the deferred replay in
/// [`settle_completions`](Self::settle_completions) decide this, and they have to
/// decide it identically. `values_updated` says whether the caller already refreshed
/// the menu's values, so they are not fetched twice.
fn decide_menu_completion(&mut self, menu_index: usize, values_updated: bool) -> bool {
let menu = &mut self.menus[menu_index];
let accept_lone_value = if self.quick_completions && menu.can_quick_complete() {
if !values_updated {
menu.update_values(
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
}
// Accepting a lone *stale* value is refused downstream, since its span
// belongs to another line, so the menu would close over a completion that
// never happened.
menu.get_values().len() == 1 && !menu.results_are_provisional()
} else {
false
};
if !accept_lone_value && self.partial_completions {
menu.can_partially_complete(
values_updated || self.quick_completions,
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
}
accept_lone_value
}
fn process_input_batch(
&mut self,
prompt: &dyn Prompt,
events: Vec<Event>,
) -> Result<ControlFlow<Signal>> {
// Convert `Event` into `ReedlineEvent`. Also, fuse consecutive
// `ReedlineEvent::EditCommand` into one. Also, if there're multiple
// `ReedlineEvent::Resize`, only keep the last one.
let mut reedline_events: Vec<ReedlineEvent> = vec![];
let mut edits = vec![];
let mut resize = None;
for event in events {
if let Ok(event) = ReedlineRawEvent::try_from(event) {
match self.edit_mode.parse_event(event) {
ReedlineEvent::Edit(edit) => edits.extend(edit),
ReedlineEvent::Resize(x, y) => resize = Some((x, y)),
event => {
if !edits.is_empty() {
reedline_events.push(ReedlineEvent::Edit(std::mem::take(&mut edits)));
}
reedline_events.push(event);
}
}
}
}
if !edits.is_empty() {
reedline_events.push(ReedlineEvent::Edit(edits));
}
if let Some((x, y)) = resize {
reedline_events.push(ReedlineEvent::Resize(x, y));
}
if self.immediately_accept {
reedline_events.push(ReedlineEvent::Submit);
}
// The mode machine has parsed this batch, so the rest policy it
// declares is now final. Relay it to the editor before running the
// emitted commands so a command a mode transition issued (e.g. the
// Esc→normal grapheme step-back) resolves under the new policy. This
// does not commit the cursor — the commands settle it, and the
// pre-paint `set_edit_mode` below still clamps no-command switches.
self.editor.sync_edit_mode(self.edit_mode.edit_mode());
// Handle reedline events.
let mut need_repaint = false;
for event in reedline_events {
match self.handle_event(prompt, event)? {
EventStatus::Exits(signal) => {
// Check if we are merely suspended (to process an ExecuteHostCommand event)
// or if we're about to quit the editor.
if self.suspended_state.is_none() {
// We are about to quit the editor, move the cursor below the input
// area, for external commands or new read_line call
self.painter.move_cursor_to_end()?;
}
return Ok(ControlFlow::Break(signal));
}
EventStatus::Handled => {
need_repaint = true;
}
EventStatus::Inapplicable => {
// Nothing changed, no need to repaint
}
}
}
// A command-less mode transition adopts a new rest policy via
// `sync_edit_mode` but emits nothing to commit the cursor. Force the
// settle (and a repaint) so it doesn't stay unsettled until the next
// command.
if self.editor.policy_unsettled() {
need_repaint = true;
}
if need_repaint {
// Sync the editor's edit mode before painting so the cursor is
// normalized under the current rest policy. A mode change that
// bypasses the command path (e.g. Esc → Vi normal) otherwise
// wouldn't clamp until the next command, painting the cursor past
// the last grapheme for a frame.
let mode = self.edit_mode.edit_mode();
self.editor.set_edit_mode(mode);
self.repaint(prompt)?;
}
Ok(ControlFlow::Continue(()))
}
fn handle_event(&mut self, prompt: &dyn Prompt, event: ReedlineEvent) -> Result<EventStatus> {
if self.input_mode == InputMode::HistorySearch {
self.handle_history_search_event(event)
} else {
self.handle_editor_event(prompt, event)
}
}
fn handle_history_search_event(&mut self, event: ReedlineEvent) -> io::Result<EventStatus> {
match event {
ReedlineEvent::UntilFound(events) => {
for event in events {
match self.handle_history_search_event(event)? {
EventStatus::Inapplicable => {
// Try again with the next event handler
}
success => {
return Ok(success);
}
}
}
// Exhausting the event handlers is still considered handled
Ok(EventStatus::Handled)
}
ReedlineEvent::CtrlD => {
if self.editor.is_empty() {
self.input_mode = InputMode::Regular;
self.editor.reset_undo_stack();
Ok(EventStatus::Exits(Signal::CtrlD))
} else {
self.run_history_commands(&[EditCommand::Delete]);
Ok(EventStatus::Handled)
}
}
ReedlineEvent::CtrlC => {
self.input_mode = InputMode::Regular;
Ok(EventStatus::Exits(Signal::CtrlC))
}
ReedlineEvent::ClearScreen => {
self.painter.clear_screen()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::ClearScrollback => {
self.painter.clear_scrollback()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::Enter
| ReedlineEvent::HistoryHintComplete
| ReedlineEvent::Submit
| ReedlineEvent::SubmitOrNewline => {
if let Some(string) = self.history_cursor.string_at_cursor() {
self.editor
.set_buffer(string, UndoBehavior::CreateUndoPoint);
}
self.input_mode = InputMode::Regular;
Ok(EventStatus::Handled)
}
ReedlineEvent::ExecuteHostCommand(host_command) => {
self.last_render_snapshot = None;
self.suspended_state = Some(self.painter.state_before_suspension());
Ok(EventStatus::Exits(Signal::HostCommand(host_command)))
}
ReedlineEvent::Edit(commands) => {
self.run_history_commands(&commands);
Ok(EventStatus::Handled)
}
ReedlineEvent::Mouse {
column,
row,
button,
} => {
if button == MouseButton::Left {
self.handle_mouse_click(column, row)?;
}
Ok(EventStatus::Handled)
}
ReedlineEvent::Resize(width, height) => {
self.last_render_snapshot = None;
self.painter.handle_resize(width, height);
Ok(EventStatus::Handled)
}
ReedlineEvent::Repaint => {
// A handled Event causes a repaint
Ok(EventStatus::Handled)
}
ReedlineEvent::PreviousHistory | ReedlineEvent::Up | ReedlineEvent::SearchHistory => {
self.history_cursor
.back(self.history.as_ref())
.expect("todo: error handling");
Ok(EventStatus::Handled)
}
ReedlineEvent::NextHistory | ReedlineEvent::Down => {
self.history_cursor
.forward(self.history.as_ref())
.expect("todo: error handling");
// Hacky way to ensure that we don't fall of into failed search going forward
if self.history_cursor.string_at_cursor().is_none() {
self.history_cursor
.back(self.history.as_ref())
.expect("todo: error handling");
}
Ok(EventStatus::Handled)
}
ReedlineEvent::Esc => {
self.input_mode = InputMode::Regular;
Ok(EventStatus::Handled)
}
// TODO: Check if events should be handled
ReedlineEvent::Right
| ReedlineEvent::Left
| ReedlineEvent::ToStart
| ReedlineEvent::ToEnd
| ReedlineEvent::Multiple(_)
| ReedlineEvent::None
| ReedlineEvent::HistoryHintWordComplete
| ReedlineEvent::OpenEditor
| ReedlineEvent::Menu(_)
| ReedlineEvent::MenuNext
| ReedlineEvent::MenuPrevious
| ReedlineEvent::MenuUp
| ReedlineEvent::MenuDown
| ReedlineEvent::MenuLeft
| ReedlineEvent::MenuRight
| ReedlineEvent::MenuPageNext
| ReedlineEvent::MenuPagePrevious
| ReedlineEvent::ViChangeMode(_) => Ok(EventStatus::Inapplicable),
}
}
fn handle_editor_event(
&mut self,
prompt: &dyn Prompt,
event: ReedlineEvent,
) -> io::Result<EventStatus> {
match event {
ReedlineEvent::Menu(name) => {
if self.active_menu().is_none() {
if let Some(index) = self.menus.iter().position(|menu| menu.name() == name) {
self.menus[index].menu_event(MenuEvent::Activate(self.quick_completions));
invalidate_anchor_if_host_completer_runs(
&self.menus[index],
&mut self.painter,
);
if self.decide_menu_completion(index, false) {
return self.handle_editor_event(prompt, ReedlineEvent::Enter);
}
// A final answer already had its say above, so only a
// provisional one leaves anything owed. With neither option set
// nothing queried the completer, so this reads the default
// `false` and the menu paints as it always has.
if self.menus[index].results_are_provisional() {
self.deferred_menu_completion = Some(DeferredMenuCompletion::new(
&self.menus[index],
&self.editor,
));
}
return Ok(EventStatus::Handled);
}
}
Ok(EventStatus::Inapplicable)
}
ReedlineEvent::MenuNext => {
if let Some(menu) = self.menus.iter_mut().find(|menu| menu.is_active()) {
// The second route to the lone-value accept, so it carries the same
// provisional guard as `decide_menu_completion`: accepting a lone
// *stale* value is refused downstream, but the `Enter` would still
// deactivate the menu, closing it over a completion that never
// happened.
if menu.get_values().len() == 1
&& menu.can_quick_complete()
&& !menu.results_are_provisional()
{
self.handle_editor_event(prompt, ReedlineEvent::Enter)
} else {
if self.partial_completions {
menu.can_partially_complete(
self.quick_completions,
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
invalidate_anchor_if_host_completer_runs(menu, &mut self.painter);
}
menu.menu_event(MenuEvent::NextElement);
Ok(EventStatus::Handled)
}
} else {
Ok(EventStatus::Inapplicable)
}
}
ReedlineEvent::MenuPrevious => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::PreviousElement);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuUp => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveUp);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuDown => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveDown);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuLeft => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveLeft);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuRight => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveRight);
Ok(EventStatus::Handled)
})
}
// These two spell out `active_menu()`, since that borrows all of `self` and
// the painter has to stay reachable alongside the menu.
ReedlineEvent::MenuPageNext => {
match self.menus.iter_mut().find(|menu| menu.is_active()) {
Some(menu) => {
menu.menu_event(MenuEvent::NextPage);
invalidate_anchor_if_host_completer_runs(menu, &mut self.painter);
Ok(EventStatus::Handled)
}
None => Ok(EventStatus::Inapplicable),
}
}
ReedlineEvent::MenuPagePrevious => {
match self.menus.iter_mut().find(|menu| menu.is_active()) {
Some(menu) => {
menu.menu_event(MenuEvent::PreviousPage);
invalidate_anchor_if_host_completer_runs(menu, &mut self.painter);
Ok(EventStatus::Handled)
}
None => Ok(EventStatus::Inapplicable),
}
}
ReedlineEvent::HistoryHintComplete => {
let hint = self.hinter.as_mut().map(|h| h.complete_hint());
Ok(self.accept_history_hint(hint))
}
ReedlineEvent::HistoryHintWordComplete => {
let hint = self.hinter.as_mut().map(|h| h.next_hint_token());
Ok(self.accept_history_hint(hint))
}
ReedlineEvent::Esc => {
self.deactivate_menus();
self.editor.clear_selection();
Ok(EventStatus::Handled)
}
ReedlineEvent::CtrlD => {
if self.editor.is_empty() {
self.editor.reset_undo_stack();
Ok(EventStatus::Exits(Signal::CtrlD))
} else {
self.run_edit_commands(&[EditCommand::Delete]);
Ok(EventStatus::Handled)
}
}
ReedlineEvent::CtrlC => {
self.deactivate_menus();
self.run_edit_commands(&[EditCommand::Clear]);
self.editor.reset_undo_stack();
Ok(EventStatus::Exits(Signal::CtrlC))
}
ReedlineEvent::ClearScreen => {
self.deactivate_menus();
self.painter.clear_screen()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::ClearScrollback => {
self.deactivate_menus();
self.painter.clear_scrollback()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::Enter | ReedlineEvent::Submit | ReedlineEvent::SubmitOrNewline
if self.menus.iter().any(|menu| menu.is_active()) =>
{
for menu in self.menus.iter_mut() {
if menu.is_active() {
menu.replace_in_buffer(&mut self.editor);
menu.menu_event(MenuEvent::Deactivate);
return Ok(EventStatus::Handled);
}
}
unreachable!()
}
ReedlineEvent::Enter => {
#[cfg(feature = "bashisms")]
if let Some(event) = self.parse_bang_command() {
return self.handle_editor_event(prompt, event);
}
if let Some(event) = self.try_expand_abbreviation_at_cursor(true) {
self.handle_editor_event(prompt, event)?;
}
let buffer = self.editor.get_buffer().to_string();
match self.validator.as_mut().map(|v| v.validate(&buffer)) {
None | Some(ValidationResult::Complete) => Ok(self.submit_buffer(prompt)?),
Some(ValidationResult::Incomplete) => {
self.run_edit_commands(&[EditCommand::InsertNewline]);
Ok(EventStatus::Handled)
}
}
}
ReedlineEvent::Submit => {
#[cfg(feature = "bashisms")]
if let Some(event) = self.parse_bang_command() {
return self.handle_editor_event(prompt, event);
}
if let Some(event) = self.try_expand_abbreviation_at_cursor(true) {
self.handle_editor_event(prompt, event)?;
}
Ok(self.submit_buffer(prompt)?)
}
ReedlineEvent::SubmitOrNewline => {
#[cfg(feature = "bashisms")]
if let Some(event) = self.parse_bang_command() {
return self.handle_editor_event(prompt, event);
}
if let Some(event) = self.try_expand_abbreviation_at_cursor(true) {
self.handle_editor_event(prompt, event)?;
}
let cursor_position_in_buffer = self.editor.insertion_point();
let buffer = self.editor.get_buffer().to_string();
if cursor_position_in_buffer < buffer.len() {
self.run_edit_commands(&[EditCommand::InsertNewline]);
return Ok(EventStatus::Handled);
}
match self.validator.as_mut().map(|v| v.validate(&buffer)) {
None | Some(ValidationResult::Complete) => Ok(self.submit_buffer(prompt)?),
Some(ValidationResult::Incomplete) => {
self.run_edit_commands(&[EditCommand::InsertNewline]);
Ok(EventStatus::Handled)
}
}
}
ReedlineEvent::ExecuteHostCommand(host_command) => {
self.last_render_snapshot = None;
self.suspended_state = Some(self.painter.state_before_suspension());
Ok(EventStatus::Exits(Signal::HostCommand(host_command)))
}
ReedlineEvent::Edit(commands) => {
self.run_edit_commands(&commands);
// Check if a space was just inserted and try to expand abbreviations
if let Some(EditCommand::InsertChar(' ')) = commands.first() {
if let Some(event) = self.try_expand_abbreviation_at_cursor(false) {
return self.handle_editor_event(prompt, event);
}
}
if let Some(menu) = self.menus.iter_mut().find(|men| men.is_active()) {
if self.quick_completions && menu.can_quick_complete() {
match commands.first() {
Some(&EditCommand::Backspace)
| Some(&EditCommand::BackspaceWord)
| Some(&EditCommand::MoveToLineStart { select: false })
if !self.persistent_menus =>
{
menu.menu_event(MenuEvent::Deactivate)
}
_ => {
menu.menu_event(MenuEvent::Edit(self.quick_completions));
invalidate_anchor_if_host_completer_runs(menu, &mut self.painter);
menu.update_values(
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
if let Some(&EditCommand::Complete) = commands.first() {
if menu.get_values().len() == 1 {
return self
.handle_editor_event(prompt, ReedlineEvent::Enter);
} else if self.partial_completions
&& menu.can_partially_complete(
self.quick_completions,
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
)
{
return Ok(EventStatus::Handled);
}
}
}
}
}
if !self.persistent_menus && self.editor.line_buffer().get_buffer().is_empty() {
menu.menu_event(MenuEvent::Deactivate);
} else {
menu.menu_event(MenuEvent::Edit(self.quick_completions));
invalidate_anchor_if_host_completer_runs(menu, &mut self.painter);
}
}
Ok(EventStatus::Handled)
}
ReedlineEvent::OpenEditor => self.open_editor().map(|_| EventStatus::Handled),
ReedlineEvent::Resize(width, height) => {
self.last_render_snapshot = None;
self.painter.handle_resize(width, height);
Ok(EventStatus::Handled)
}
ReedlineEvent::Repaint => {
// A handled Event causes a repaint
Ok(EventStatus::Handled)
}
ReedlineEvent::PreviousHistory => {
self.previous_history();
Ok(EventStatus::Handled)
}
ReedlineEvent::NextHistory => {
self.next_history();
Ok(EventStatus::Handled)
}
ReedlineEvent::Up => {
self.up_command();
Ok(EventStatus::Handled)
}
ReedlineEvent::Down => {
self.down_command();
Ok(EventStatus::Handled)
}
ReedlineEvent::Left => {
self.run_edit_commands(&[EditCommand::MoveLeft { select: false }]);
Ok(EventStatus::Handled)
}
ReedlineEvent::Right => {
self.run_edit_commands(&[EditCommand::MoveRight { select: false }]);
Ok(EventStatus::Handled)
}
ReedlineEvent::ToStart => {
self.editor.move_to_start(false);
self.editor.commit_cursor();
Ok(EventStatus::Handled)
}
ReedlineEvent::ToEnd => {
self.editor.move_to_end(false);
// Settle under the rest policy: `Alt+>` is bound in vi normal too,
// where the block caret must not rest past the last grapheme.
self.editor.commit_cursor();
Ok(EventStatus::Handled)
}
ReedlineEvent::SearchHistory => {
self.enter_history_search();
Ok(EventStatus::Handled)
}
ReedlineEvent::Multiple(events) => {
let mut latest_signal = EventStatus::Inapplicable;
for event in events {
match self.handle_editor_event(prompt, event)? {
EventStatus::Handled => {
latest_signal = EventStatus::Handled;
}
EventStatus::Inapplicable => {
// NO OP
}
EventStatus::Exits(signal) => {
// TODO: Check if we want to allow execution to
// proceed if there are more events after the
// terminating
return Ok(EventStatus::Exits(signal));
}
}
}
Ok(latest_signal)
}
ReedlineEvent::UntilFound(events) => {
for event in events {
match self.handle_editor_event(prompt, event)? {
EventStatus::Inapplicable => {
// Try again with the next event handler
}
success => {
return Ok(success);
}
}
}
// Exhausting the event handlers is still considered handled
Ok(EventStatus::Inapplicable)
}
ReedlineEvent::ViChangeMode(_) => Ok(self.edit_mode.handle_mode_specific_event(event)),
ReedlineEvent::Mouse {
column,
row,
button,
} => {
if button == MouseButton::Left {
self.handle_mouse_click(column, row)?;
}
Ok(EventStatus::Handled)
}
ReedlineEvent::None => Ok(EventStatus::Inapplicable),
}
}
fn handle_mouse_click(&mut self, column: u16, row: u16) -> Result<()> {
let snapshot = match &self.last_render_snapshot {
Some(snapshot) => snapshot,
None => return Ok(()),
};
if self.input_mode != InputMode::Regular || self.menus.iter().any(|m| m.is_active()) {
return Ok(());
}
let buffer = self.editor.get_buffer();
if let Some(offset) = self.painter.screen_to_buffer_offset(snapshot, column, row) {
if buffer.is_char_boundary(offset) {
self.editor.edit_buffer(
|buf| buf.set_insertion_point(offset),
UndoBehavior::MoveCursor,
);
}
}
Ok(())
}
fn active_menu(&mut self) -> Option<&mut ReedlineMenu> {
self.menus.iter_mut().find(|menu| menu.is_active())
}
fn deactivate_menus(&mut self) {
// Nothing is left to complete into.
self.deferred_menu_completion = None;
self.menus
.iter_mut()
.for_each(|menu| menu.menu_event(MenuEvent::Deactivate));
}
fn previous_history(&mut self) {
self.history_cursor_on_excluded = false;
if self.input_mode != InputMode::HistoryTraversal {
self.input_mode = InputMode::HistoryTraversal;
self.history_cursor = HistoryCursor::new(
self.get_history_navigation_based_on_line_buffer(),
self.get_history_session_id(),
);
if self.history_excluded_item.is_some() {
self.history_cursor_on_excluded = true;
}
}
if !self.history_cursor_on_excluded {
self.history_cursor
.back(self.history.as_ref())
.expect("todo: error handling");
}
self.update_buffer_from_history();
self.editor.move_to_start(false);
self.editor.move_to_line_end(false);
// History navigation positions the cursor outside the command path, so
// settle it under the rest policy (vi-normal must not rest past the line).
self.editor.commit_cursor();
self.editor
.update_undo_state(UndoBehavior::HistoryNavigation);
}
fn next_history(&mut self) {
if self.input_mode != InputMode::HistoryTraversal {
self.input_mode = InputMode::HistoryTraversal;
self.history_cursor = HistoryCursor::new(
self.get_history_navigation_based_on_line_buffer(),
self.get_history_session_id(),
);
}
if self.history_cursor_on_excluded {
self.history_cursor_on_excluded = false;
} else {
let cursor_was_on_item = self.history_cursor.string_at_cursor().is_some();
self.history_cursor
.forward(self.history.as_ref())
.expect("todo: error handling");
if cursor_was_on_item
&& self.history_cursor.string_at_cursor().is_none()
&& self.history_excluded_item.is_some()
{
self.history_cursor_on_excluded = true;
}
}
if self.history_cursor.string_at_cursor().is_none() && !self.history_cursor_on_excluded {
self.input_mode = InputMode::Regular;
}
self.update_buffer_from_history();
self.editor.move_to_end(false);
// See `previous_history`: settle the out-of-band cursor under the policy.
self.editor.commit_cursor();
self.editor
.update_undo_state(UndoBehavior::HistoryNavigation)
}
/// Enable the search and navigation through the history from the line buffer prompt
///
/// Enables either prefix search with output in the line buffer or simple traversal
fn get_history_navigation_based_on_line_buffer(&self) -> HistoryNavigationQuery {
if self.editor.is_empty() || !self.editor.is_cursor_at_buffer_end() {
// Perform bash-style basic up/down entry walking
HistoryNavigationQuery::Normal(
// Hack: Tight coupling point to be able to restore previously typed input
self.editor.line_buffer().clone(),
)
} else {
// Prefix search like found in fish, zsh, etc.
// Search string is set once from the current buffer
// Current setup (code in other methods)
// Continuing with typing will leave the search
// but next invocation of this method will start the next search
let buffer = self.editor.get_buffer().to_string();
HistoryNavigationQuery::PrefixSearch(buffer)
}
}
/// Switch into reverse history search mode
///
/// This mode uses a separate prompt and handles keybindings slightly differently!
fn enter_history_search(&mut self) {
self.history_cursor = HistoryCursor::new(
HistoryNavigationQuery::SubstringSearch("".to_string()),
self.get_history_session_id(),
);
self.input_mode = InputMode::HistorySearch;
}
/// Dispatches the applicable [`EditCommand`] actions for editing the history search string.
///
/// Only modifies internal state, does not perform regular output!
fn run_history_commands(&mut self, commands: &[EditCommand]) {
for command in commands {
match command {
EditCommand::InsertChar(c) => {
let navigation = self.history_cursor.get_navigation();
if let HistoryNavigationQuery::SubstringSearch(mut substring) = navigation {
substring.push(*c);
self.history_cursor = HistoryCursor::new(
HistoryNavigationQuery::SubstringSearch(substring),
self.get_history_session_id(),
);
} else {
self.history_cursor = HistoryCursor::new(
HistoryNavigationQuery::SubstringSearch(String::from(*c)),
self.get_history_session_id(),
);
}
self.history_cursor
.back(self.history.as_mut())
.expect("todo: error handling");
}
EditCommand::Backspace => {
let navigation = self.history_cursor.get_navigation();
if let HistoryNavigationQuery::SubstringSearch(substring) = navigation {
let new_substring = text_manipulation::remove_last_grapheme(&substring);
self.history_cursor = HistoryCursor::new(
HistoryNavigationQuery::SubstringSearch(new_substring.to_string()),
self.get_history_session_id(),
);
self.history_cursor
.back(self.history.as_mut())
.expect("todo: error handling");
}
}
_ => {
self.input_mode = InputMode::Regular;
}
}
}
}
/// Set the buffer contents for history traversal/search in the standard prompt
///
/// When using the up/down traversal or fish/zsh style prefix search update the main line buffer accordingly.
/// Not used for the separate modal reverse search!
fn update_buffer_from_history(&mut self) {
match self.history_cursor.get_navigation() {
_ if self.history_cursor_on_excluded => self.editor.set_buffer(
self.history_excluded_item
.as_ref()
.unwrap()
.command_line
.clone(),
UndoBehavior::HistoryNavigation,
),
HistoryNavigationQuery::Normal(original) => {
if let Some(buffer_to_paint) = self.history_cursor.string_at_cursor() {
self.editor
.set_buffer(buffer_to_paint, UndoBehavior::HistoryNavigation);
} else {
// Hack
self.editor
.set_line_buffer(original, UndoBehavior::HistoryNavigation);
}
}
HistoryNavigationQuery::PrefixSearch(prefix) => {
if let Some(prefix_result) = self.history_cursor.string_at_cursor() {
self.editor
.set_buffer(prefix_result, UndoBehavior::HistoryNavigation);
} else {
self.editor
.set_buffer(prefix, UndoBehavior::HistoryNavigation);
}
}
HistoryNavigationQuery::SubstringSearch(_) => todo!(),
}
}
/// Executes [`EditCommand`] actions by modifying the internal state appropriately. Does not output itself.
pub fn run_edit_commands(&mut self, commands: &[EditCommand]) {
if self.input_mode == InputMode::HistoryTraversal {
self.input_mode = InputMode::Regular;
}
// Adopt the current edit mode's rest policy so these commands resolve
// under it (e.g. block-caret selection geometry) — but *without*
// committing the cursor first. A commit here would apply the policy's
// resting rule (e.g. `OnGrapheme` pulling an at-end point back) before
// the commands run, double-stepping a mode-transition backstep like the
// vi `Esc`→normal `MoveLeft`. The commands settle the cursor themselves,
// and the pre-paint `set_edit_mode` makes the final commit.
self.editor.sync_edit_mode(self.edit_mode.edit_mode());
// Run the commands over the edit buffer
for command in commands {
self.editor.run_edit_command(command);
}
}
fn up_command(&mut self) {
// If we're at the top, then:
if self.editor.is_cursor_at_first_line() {
// If we're at the top, move to previous history
self.previous_history();
} else {
// Through `run_edit_commands` so the cursor settles under the mode's
// rest policy — a bare `editor.move_line_up` skips the commit boundary,
// leaving a vi-normal caret past the last grapheme on a short line.
self.run_edit_commands(&[EditCommand::MoveLineUp { select: false }]);
}
}
fn down_command(&mut self) {
// If we're at the top, then:
if self.editor.is_cursor_at_last_line() {
// If we're at the top, move to previous history
self.next_history();
} else {
// See `up_command`: settle under the rest policy via the commit boundary.
self.run_edit_commands(&[EditCommand::MoveLineDown { select: false }]);
}
}
/// Checks if hints should be displayed and are able to be completed
fn hints_active(&self) -> bool {
!self.hide_hints && matches!(self.input_mode, InputMode::Regular)
}
/// Accept a trailing history hint (full hint or next word) by appending it at
/// the buffer end. `Handled` only when a non-empty hint applies: hints active,
/// cursor at the buffer end, no menu open. Appending positions past the last
/// grapheme first — a block caret (vi normal) rests *on* it, so a plain insert
/// would split it.
fn accept_history_hint(&mut self, hint: Option<String>) -> EventStatus {
let Some(hint) = hint else {
return EventStatus::Inapplicable;
};
if self.hints_active()
&& self.editor.is_cursor_at_buffer_end()
&& !hint.is_empty()
&& self.active_menu().is_none()
{
self.editor.prepare_append_at_buffer_end();
self.run_edit_commands(&[EditCommand::InsertString(hint)]);
EventStatus::Handled
} else {
EventStatus::Inapplicable
}
}
/// Repaint of either the buffer or the parts for reverse history search
fn repaint(&mut self, prompt: &dyn Prompt) -> io::Result<()> {
// Repainting
if self.input_mode == InputMode::HistorySearch {
self.history_search_paint(prompt)
} else {
self.buffer_paint(prompt)
}
}
/// Expands an abbreviation at the word before the cursor, if any exists
///
/// Calls [`Highlighter::should_expand_abbr`] with [`AbbrExpandContext::WordAbbreviation`]
/// to decide whether expansion is permitted at the cursor position
fn try_expand_abbreviation_at_cursor(&mut self, submitted: bool) -> Option<ReedlineEvent> {
let buffer = self.editor.get_buffer();
let cursor_position_in_buffer = self.editor.insertion_point();
if cursor_position_in_buffer == 0 {
return None;
}
let (offset, suffix) = match submitted {
true => (0, ""), // expand on <enter>
false => (1, " "), // expand on <space>
};
// `offset` is a raw byte count (0 on <enter>, 1 on <space>), so
// `cursor_position_in_buffer - offset` can land inside a multi-byte
// UTF-8 char sitting just before the cursor (e.g. pasted CJK text).
// Floor it down to the nearest char boundary before slicing to avoid
// a panic.
let word_end =
crate::menu_functions::floor_char_boundary(buffer, cursor_position_in_buffer - offset);
let prefix = &buffer[..word_end];
let word_start = prefix
.char_indices()
.rev()
.find(|(_, ch)| ch.is_whitespace())
.map(|(idx, ch)| idx + ch.len_utf8())
.unwrap_or(0); // byte offset of word start
if word_start >= word_end {
// The first char in the buffer is a space or there are consecutive spaces
return None;
}
if submitted
&& buffer[word_end..]
.chars()
.next()
.is_some_and(|ch| !ch.is_whitespace())
{
// The cursor is in the middle of a word, e.g. "hello|world"
return None;
}
if !self.highlighter.should_expand_abbr(
buffer,
word_start,
AbbrExpandContext::WordAbbreviation,
) {
return None;
}
let word = &buffer[word_start..word_end];
if let Some(expansion) = self.abbreviations.get(word) {
return Some(ReedlineEvent::Edit(vec![
EditCommand::MoveToPosition {
position: word_start,
select: false,
},
EditCommand::MoveToPosition {
// Select through the cursor, not just the end of the word, so
// the triggering space (already inserted on a <space> expansion)
// is replaced rather than left beside the inserted suffix.
position: cursor_position_in_buffer,
select: true,
},
EditCommand::InsertString(format!("{}{}", expansion, suffix)),
]));
}
None
}
#[cfg(feature = "bashisms")]
/// Parses the ! command to replace entries from the history
fn parse_bang_command(&mut self) -> Option<ReedlineEvent> {
let buffer = self.editor.get_buffer();
let parsed = parse_selection_char(buffer, '!');
let parsed_prefix = parsed.prefix.unwrap_or_default().to_string();
let parsed_marker = parsed.marker.unwrap_or_default().to_string();
if let Some(last) = parsed.remainder.chars().last() {
if last != ' ' {
return None;
}
}
if !self.highlighter.should_expand_abbr(
buffer,
parsed.remainder.len(),
AbbrExpandContext::BangExpansion,
) {
return None;
}
let history_result = parsed
.index
.zip(parsed.marker)
.and_then(|(index, indicator)| match parsed.action {
ParseAction::LastCommand => self
.history
.search(SearchQuery {
direction: SearchDirection::Backward,
start_time: None,
end_time: None,
start_id: None,
end_id: None,
limit: Some(1), // fetch the latest one entries
filter: SearchFilter::anything(self.get_history_session_id()),
})
.unwrap_or_else(|_| Vec::new())
.get(index.saturating_sub(1))
.map(|history| {
(
parsed.remainder.len(),
indicator.len(),
history.command_line.clone(),
)
}),
ParseAction::BackwardSearch => self
.history
.search(SearchQuery {
direction: SearchDirection::Backward,
start_time: None,
end_time: None,
start_id: None,
end_id: None,
limit: Some(index as i64), // fetch the latest n entries
filter: SearchFilter::anything(self.get_history_session_id()),
})
.unwrap_or_else(|_| Vec::new())
.get(index.saturating_sub(1))
.map(|history| {
(
parsed.remainder.len(),
indicator.len(),
history.command_line.clone(),
)
}),
ParseAction::BackwardPrefixSearch => {
let history_search_by_session = self
.history
.search(SearchQuery::last_with_prefix_and_cwd(
parsed.prefix.unwrap().to_string(),
self.cwd.clone().unwrap_or_else(|| {
std::env::current_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string()
}),
self.get_history_session_id(),
))
.unwrap_or_else(|_| Vec::new())
.get(index.saturating_sub(1))
.map(|history| {
(
parsed.remainder.len(),
parsed_prefix.len() + parsed_marker.len(),
history.command_line.clone(),
)
});
// If we don't find any history searching by session id, then let's
// search everything, otherwise use the result from the session search
if history_search_by_session.is_none() {
self.history
.search(SearchQuery::last_with_prefix(
parsed_prefix.clone(),
self.get_history_session_id(),
))
.unwrap_or_else(|_| Vec::new())
.get(index.saturating_sub(1))
.map(|history| {
(
parsed.remainder.len(),
parsed_prefix.len() + parsed_marker.len(),
history.command_line.clone(),
)
})
} else {
history_search_by_session
}
}
ParseAction::ForwardSearch => self
.history
.search(SearchQuery {
direction: SearchDirection::Forward,
start_time: None,
end_time: None,
start_id: None,
end_id: None,
limit: Some((index + 1) as i64), // fetch the oldest n entries
filter: SearchFilter::anything(self.get_history_session_id()),
})
.unwrap_or_else(|_| Vec::new())
.get(index)
.map(|history| {
(
parsed.remainder.len(),
indicator.len(),
history.command_line.clone(),
)
}),
ParseAction::LastToken => self
.history
.search(SearchQuery::last_with_search(SearchFilter::anything(
self.get_history_session_id(),
)))
.unwrap_or_else(|_| Vec::new())
.first()
//BUGBUG: This returns the wrong results with paths with spaces in them
.and_then(|history| history.command_line.split_whitespace().next_back())
.map(|token| (parsed.remainder.len(), indicator.len(), token.to_string())),
});
if let Some((start, size, history)) = history_result {
let edits = vec![
EditCommand::MoveToPosition {
position: start,
select: false,
},
EditCommand::ReplaceChars(size, history),
];
Some(ReedlineEvent::Edit(edits))
} else {
None
}
}
fn open_editor(&mut self) -> Result<()> {
match &mut self.buffer_editor {
Some(BufferEditor {
ref mut command,
ref temp_file,
}) => {
{
let mut file = File::create(temp_file)?;
write!(file, "{}", self.editor.get_buffer())?;
}
// Capture the prompt's screen range so that an editor
// that leaves the cursor untouched (e.g. an editor that
// uses the alternate screen only) re-uses the existing
// prompt rows instead of starting a new prompt a row
// below the old one.
let suspended_state = self.painter.state_before_suspension();
{
let mut child = command.spawn()?;
// The child owns the tty now; invalidate eagerly so
// any `?` early-return below still leaves the
// painter in a safe state.
self.painter.invalidate_prompt_start_row();
child.wait()?;
}
// On the success path, re-initialize position and size
// (covers a resize-during-editor with no SIGWINCH). If
// the editor moved the cursor out of the prompt's rows
// (it printed output), a fresh prompt starts below that
// output. On query failure, the eager invalidate above
// is our floor — losing the size refresh is acceptable;
// losing the user's edited buffer below is not.
let _ = self
.painter
.initialize_prompt_position(Some(&suspended_state));
let res = std::fs::read_to_string(temp_file)?;
let res = res.trim_end().to_string();
self.editor.set_buffer(res, UndoBehavior::CreateUndoPoint);
Ok(())
}
_ => Ok(()),
}
}
/// Repaint logic for the history reverse search
///
/// Overwrites the prompt indicator and highlights the search string
/// separately from the result buffer.
fn history_search_paint(&mut self, prompt: &dyn Prompt) -> Result<()> {
let navigation = self.history_cursor.get_navigation();
if let HistoryNavigationQuery::SubstringSearch(substring) = navigation {
let status =
if !substring.is_empty() && self.history_cursor.string_at_cursor().is_none() {
PromptHistorySearchStatus::Failing
} else {
PromptHistorySearchStatus::Passing
};
let prompt_history_search = PromptHistorySearch::new(status, substring.clone());
let res_string = self.history_cursor.string_at_cursor().unwrap_or_default();
// Highlight matches
let res_string = if self.use_ansi_coloring {
let match_highlighter = SimpleMatchHighlighter::new(substring);
let styled = match_highlighter.highlight(&res_string, 0);
styled.render_simple()
} else {
res_string
};
let lines = PromptLines::new(
prompt,
self.prompt_edit_mode(),
Some(prompt_history_search),
&res_string,
"",
"",
);
self.painter.repaint_buffer(
prompt,
&lines,
self.prompt_edit_mode(),
None,
self.use_ansi_coloring,
&self.cursor_shapes,
)?;
}
Ok(())
}
/// Triggers a full repaint including the prompt parts
///
/// Includes the highlighting and hinting calls.
fn buffer_paint(&mut self, prompt: &dyn Prompt) -> Result<()> {
let cursor_position_in_buffer = self.editor.insertion_point();
let buffer_to_paint = self.editor.get_buffer();
let mut styled_text = self
.highlighter
.highlight(buffer_to_paint, cursor_position_in_buffer);
if let Some((from, to)) = self.editor.get_selection() {
// With a cursor-cell style configured, the head cell gets it and
// the selection style covers the rest of the range.
match self
.visual_selection_cursor_style
.zip(self.editor.selection_head_cell())
{
Some((cursor_style, (cell_start, cell_end))) => {
if from < cell_start {
styled_text.style_range(from, cell_start, self.visual_selection_style);
}
styled_text.style_range(cell_start, cell_end, cursor_style);
if cell_end < to {
styled_text.style_range(cell_end, to, self.visual_selection_style);
}
}
None => styled_text.style_range(from, to, self.visual_selection_style),
}
}
let (before_cursor, after_cursor) = styled_text.render_around_insertion_point(
cursor_position_in_buffer,
prompt,
self.use_ansi_coloring,
self.painter.semantic_markers(),
);
let hint: String = if self.hints_active() {
self.hinter.as_mut().map_or_else(String::new, |hinter| {
hinter.handle(
buffer_to_paint,
cursor_position_in_buffer,
self.history.as_ref(),
self.use_ansi_coloring,
&self.cwd.clone().unwrap_or_else(|| {
std::env::current_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string()
}),
)
})
} else {
String::new()
};
// Needs to add return carriage to newlines because when not in raw mode
// some OS don't fully return the carriage
let mut lines = PromptLines::new(
prompt,
self.prompt_edit_mode(),
None,
&before_cursor,
&after_cursor,
&hint,
);
// Updating the working details of the active menu
for menu in self.menus.iter_mut() {
if menu.is_active() {
// A menu still waiting on its first answer stays off screen, so a Tab
// resolving to one suggestion never draws a menu it takes away again.
if menu.is_visible() {
lines.prompt_indicator = menu.indicator().to_owned().into();
}
// If the menu requires the cursor position, update it (ide menu)
let cursor_pos = lines.cursor_pos(self.painter.screen_width());
menu.set_cursor_pos(cursor_pos);
menu.update_working_details(
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
&self.painter,
);
// That update is where a first answer lands and ends the opening phase,
// so ask again: the painter picks the menu to draw below, and an
// indicator saying otherwise would draw its rows under the ordinary
// prompt. Reading it twice is the price of the loop: the indicator sets
// the prompt width that positions the cursor, which the update consumes,
// so on the frame a menu opens that width lags by one paint.
if menu.is_visible() {
lines.prompt_indicator = menu.indicator().to_owned().into();
}
}
}
let menu = self.menus.iter().find(|menu| menu.is_visible());
self.painter.repaint_buffer(
prompt,
&lines,
self.prompt_edit_mode(),
menu,
self.use_ansi_coloring,
&self.cursor_shapes,
)?;
if self.mouse_click_mode.is_enabled() {
if let Some(layout) = &self.painter.last_layout {
let buffer = self.editor.get_buffer();
let (raw_before, raw_after) = buffer.split_at(cursor_position_in_buffer);
self.last_render_snapshot = Some(
self.painter
.render_snapshot(&lines, menu, raw_before, raw_after, layout),
);
}
} else {
self.last_render_snapshot = None;
}
Ok(())
}
/// Adds an external printer
///
/// ## Required feature:
/// `external_printer`
#[cfg(feature = "external_printer")]
pub fn with_external_printer(mut self, printer: ExternalPrinter<String>) -> Self {
self.external_printer = Some(printer);
self
}
/// Sets the poll interval used when features that require periodic processing
/// are active (e.g., external printer, idle callback).
///
/// This controls how frequently Reedline yields control back to these features
/// while waiting for user input. The default is 100ms.
///
/// Common values are 33ms (~30fps) for UI updates or 100ms for less frequent tasks.
///
/// Note: This setting only takes effect when an external printer or idle callback
/// is configured. Without these features, Reedline blocks until input is received.
///
/// # Example
/// ```no_run
/// use std::time::Duration;
/// use reedline::Reedline;
///
/// let editor = Reedline::create()
/// .with_poll_interval(Duration::from_millis(50));
/// ```
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
/// Sets an idle callback that is called periodically while waiting for user input.
///
/// This is useful for applications that need to process external events
/// (such as GUI updates, network events, or timer-based operations) while
/// the user is typing or the editor is waiting for input.
///
/// Use [`with_poll_interval`](Self::with_poll_interval) to control how frequently
/// the callback is invoked (default: 100ms).
///
/// ## Required feature:
/// `idle_callback`
///
/// # Example
/// ```no_run
/// use std::time::Duration;
/// use reedline::Reedline;
///
/// let editor = Reedline::create()
/// .with_poll_interval(Duration::from_millis(33))
/// .with_idle_callback(Box::new(|| {
/// // Process external events here
/// }));
/// ```
#[cfg(feature = "idle_callback")]
pub fn with_idle_callback(mut self, callback: Box<dyn FnMut() + Send>) -> Self {
self.idle_callback = Some(callback);
self
}
#[cfg(feature = "external_printer")]
fn external_messages(external_printer: &ExternalPrinter<String>) -> Result<Vec<String>> {
let mut messages = Vec::new();
loop {
let result = external_printer.receiver().try_recv();
match result {
Ok(line) => {
let lines = line.lines().map(String::from).collect::<Vec<_>>();
messages.extend(lines);
}
Err(TryRecvError::Empty) => {
break;
}
Err(TryRecvError::Disconnected) => {
return Err(Error::new(
ErrorKind::NotConnected,
TryRecvError::Disconnected,
));
}
}
}
Ok(messages)
}
fn submit_buffer(&mut self, prompt: &dyn Prompt) -> io::Result<EventStatus> {
let buffer = self.editor.get_buffer().to_string();
self.hide_hints = true;
// Additional repaint to show the content without hints etc.
if let Some(transient_prompt) = self.transient_prompt.take() {
self.repaint(transient_prompt.as_ref())?;
self.transient_prompt = Some(transient_prompt);
} else {
self.repaint(prompt)?;
}
if !buffer.is_empty() {
let mut entry = HistoryItem::from_command_line(&buffer);
entry.session_id = self.get_history_session_id();
if self
.history_exclusion_prefix
.as_ref()
.map(|prefix| buffer.starts_with(prefix))
.unwrap_or(false)
{
entry.id = Some(Self::FILTERED_ITEM_ID);
self.history_last_run_id = entry.id;
self.history_excluded_item = Some(entry);
} else {
entry = self.history.save(entry).expect("todo: error handling");
self.history_last_run_id = entry.id;
self.history_excluded_item = None;
}
}
self.run_edit_commands(&[EditCommand::Clear]);
self.editor.reset_undo_stack();
Ok(EventStatus::Exits(Signal::Success(buffer)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::terminal_extensions::semantic_prompt::PromptKind;
use crate::{
ColumnarMenu, CompletionOrigin, CompletionResult, DefaultPrompt, MenuBuilder, PromptViMode,
Span, Suggestion,
};
use rstest::rstest;
fn seam_engine(edit_mode: Box<dyn EditMode>) -> Reedline {
let mut rl = Reedline::create().with_edit_mode(edit_mode);
rl.painter.force_prompt_anchored_for_test(0);
rl
}
fn drive(rl: &mut Reedline, keys: &[KeyEvent]) {
let prompt = DefaultPrompt::default();
let events = keys.iter().copied().map(Event::Key).collect();
let _ = rl.process_input_batch(&prompt, events).expect("batch ok");
}
fn ch(c: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
/// Drive each key as its own input batch, so vi mode transitions settle
/// between presses the way real keystrokes arrive.
fn type_each(rl: &mut Reedline, keys: &[KeyEvent]) {
for k in keys {
drive(rl, &[*k]);
}
}
// FLIP SAFETY NET (Group C) — visual operability at the engine seam.
// RED until the cursor-as-truth flip: `v` emits Esc which clears the
// selection, so visual mode starts anchorless and `d` cuts nothing. The
// flip makes the cursor an always-present range, so `v` then `d` deletes
// the grapheme under the cursor. Valid under both models, so never wasted.
#[test]
fn v_then_d_deletes_cursor_grapheme() {
let mut rl = seam_engine(Box::<crate::Vi>::default());
type_each(
&mut rl,
&[ch('a'), ch('b'), key(KeyCode::Esc), ch('v'), ch('d')],
);
assert_eq!(rl.editor.get_buffer(), "a");
}
#[test]
fn v_extend_left_then_d_deletes_selection() {
// Visual mode is min-width-1 and motions extend it: from "abc" the cursor
// rests on 'c'; `v` selects it, `h` grows the selection left over 'b',
// and `d` deletes both — leaving "a".
let mut rl = seam_engine(Box::<crate::Vi>::default());
type_each(
&mut rl,
&[
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
ch('v'),
ch('h'),
ch('d'),
],
);
assert_eq!(rl.editor.get_buffer(), "a");
}
struct FlipToNormal {
switched: bool,
}
impl EditMode for FlipToNormal {
fn parse_event(&mut self, _e: ReedlineRawEvent) -> ReedlineEvent {
self.switched = true;
ReedlineEvent::None
}
fn edit_mode(&self) -> PromptEditMode {
if self.switched {
PromptEditMode::Vi(PromptViMode::Normal)
}
// OnGrapheme
else {
PromptEditMode::Vi(PromptViMode::Insert)
}
}
}
#[test]
fn command_less_mode_transition_settles_cursor() {
let mut rl = seam_engine(Box::new(FlipToNormal { switched: false }));
rl.editor
.set_buffer("ab".into(), UndoBehavior::CreateUndoPoint);
rl.editor
.edit_buffer(|b| b.set_insertion_point(2), UndoBehavior::MoveCursor); // at len, legal under Between
drive(&mut rl, &[ch('x')]); // flipts to OnGrapheme, emits nothing
assert_eq!(rl.current_insertion_point(), 1);
}
#[test]
fn harness_drives_typed_chars_into_buffer() {
// Smoke test: proves the seam harness runs the real batch pipeline
// (parse_event -> handle_event -> repaint-to-sink) headlessly.
let mut rl = seam_engine(Box::<crate::Emacs>::default());
drive(&mut rl, &[ch('h'), ch('i')]);
assert_eq!(rl.editor.get_buffer(), "hi");
assert_eq!(rl.current_insertion_point(), 2);
}
#[test]
fn immediately_accept_submits_without_hanging() {
// Regression: the batch-processing call (which pushes the synthetic
// Submit and returns the buffer) must run even in immediately_accept
// mode. When it was gated behind `!immediately_accept`, read_line spun
// forever instead of submitting.
let mut rl = seam_engine(Box::<crate::Emacs>::default());
rl.immediately_accept = true;
rl.run_edit_commands(&[EditCommand::InsertString("hi".into())]);
let prompt = DefaultPrompt::default();
match rl.process_input_batch(&prompt, vec![]).expect("batch ok") {
ControlFlow::Break(Signal::Success(buf)) => assert_eq!(buf, "hi"),
other => panic!("expected immediate submit, got {other:?}"),
}
}
#[test]
fn reedline_is_send() {
// `Reedline` must stay `Send` so it can be moved across threads.
// The `Send` bound lives on the stored `Box<dyn Completer + Send>`
// (engine + `ReedlineMenu`), not on the `Completer`/`Menu` traits
// themselves, so this guards against that bound being dropped.
fn assert_send<T: Send>() {}
assert_send::<Reedline>();
}
#[test]
fn test_cursor_position_after_multiline_history_navigation() {
// Test for https://github.com/nushell/reedline/pull/899
// Ensure that after navigating to a multiline history entry and then
// running edit commands, the cursor doesn't jump unexpectedly.
// The fix prevents set_buffer() from being called unnecessarily,
// which would reset the insertion point.
let mut reedline = Reedline::create();
// Add a multiline entry to history
let multiline_command = "echo 'line 1'\necho 'line 2'\necho 'line 3'";
let history_item = HistoryItem::from_command_line(multiline_command);
reedline
.history
.save(history_item)
.expect("Failed to save history");
// Navigate to previous history
reedline.previous_history();
// Get the initial insertion point after history navigation
let initial_insertion_point = reedline.current_insertion_point();
// The buffer should contain our multiline command
assert_eq!(reedline.current_buffer_contents(), multiline_command);
// After the fix, previous_history() positions cursor at end of first line
// (after move_to_start + move_to_line_end)
let first_line_end = multiline_command.find('\n').unwrap();
assert_eq!(initial_insertion_point, first_line_end);
// Now simulate pressing the right arrow key, which should move cursor right
// Without the fix, set_buffer() would be called and reset the insertion point,
// causing the cursor to jump unexpectedly. With the fix, it stays where it is
// and moves correctly.
reedline.run_edit_commands(&[EditCommand::MoveRight { select: false }]);
let after_move_insertion_point = reedline.current_insertion_point();
// The cursor should have moved right by 1 from where it was
assert_eq!(after_move_insertion_point, initial_insertion_point + 1);
// The buffer should still be unchanged
assert_eq!(reedline.current_buffer_contents(), multiline_command);
}
#[test]
fn thread_safe() {
fn f<S: Send>(_: S) {}
f(Reedline::create());
}
#[test]
#[cfg(feature = "idle_callback")]
fn thread_safe_with_idle_callback() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
fn f<S: Send>(_: S) {}
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let reedline = Reedline::create()
.with_poll_interval(Duration::from_millis(100))
.with_idle_callback(Box::new(move || {
counter_clone.fetch_add(1, Ordering::SeqCst);
}));
// Verify that Reedline with idle_callback is still Send
f(reedline);
}
#[test]
#[cfg(feature = "idle_callback")]
fn idle_callback_builder_pattern() {
// Test that with_idle_callback can be chained with other builder methods
let _reedline = Reedline::create()
.with_quick_completions(true)
.with_poll_interval(Duration::from_millis(33))
.with_idle_callback(Box::new(|| {}))
.with_partial_completions(true);
}
#[test]
fn mouse_click_moves_cursor_in_regular_mode() {
let mut reedline = Reedline::create().with_mouse_click(MouseClickMode::Enabled);
let prompt = DefaultPrompt::default();
reedline
.editor
.set_buffer("hello".to_string(), UndoBehavior::CreateUndoPoint);
reedline
.editor
.edit_buffer(|buf| buf.set_insertion_point(5), UndoBehavior::MoveCursor);
reedline.last_render_snapshot = Some(RenderSnapshot {
screen_width: 20,
screen_height: 10,
prompt_start_row: 0,
prompt_height: 1,
large_buffer: false,
prompt_str_left: "".to_string(),
prompt_indicator: "".to_string(),
before_cursor: "hello".to_string(),
after_cursor: "".to_string(),
first_buffer_col: 0,
menu_active: false,
menu_start_row: None,
large_buffer_extra_rows_after_prompt: None,
large_buffer_offset: None,
right_prompt: None,
});
let result = reedline.handle_event(
&prompt,
ReedlineEvent::Mouse {
column: 0,
row: 0,
button: MouseButton::Left,
},
);
assert!(matches!(result, Ok(EventStatus::Handled)));
assert_eq!(reedline.current_insertion_point(), 0);
}
#[test]
fn mouse_click_osc133_sets_semantic_markers() {
let reedline = Reedline::create().with_mouse_click(MouseClickMode::EnabledWithOsc133);
let markers = reedline
.painter
.semantic_markers()
.expect("expected semantic markers");
assert_eq!(
markers.prompt_start(PromptKind::Primary).as_ref(),
"\x1b]133;A;k=i;click_events=1\x1b\\"
);
}
/// Drive one key per batch, stopping at the first `Signal`.
#[cfg(feature = "helix")]
fn drive_until_signal(rl: &mut Reedline, keys: &[KeyEvent]) -> Option<Signal> {
let prompt = DefaultPrompt::default();
for k in keys {
match rl
.process_input_batch(&prompt, vec![Event::Key(*k)])
.expect("batch ok")
{
ControlFlow::Break(signal) => return Some(signal),
ControlFlow::Continue(()) => {}
}
}
None
}
/// `DefaultValidator` reads an unclosed `"` as incomplete, so `Enter` breaks
/// the line instead of submitting it and leaves the buffer inspectable.
#[cfg(feature = "helix")]
fn helix_engine_with_validator() -> Reedline {
let mut rl = Reedline::create()
.with_edit_mode(Box::<crate::Helix>::default())
.with_validator(Box::new(crate::DefaultValidator));
rl.painter.force_prompt_anchored_for_test(0);
rl
}
// --- submitting from helix normal mode ---
//
// The resting cursor is a selection and outlives the `next_mode` flip to
// insert, so anything on the `Enter` path that opens with `delete_selection`
// eats the covered grapheme. `InsertNewline` does, which makes the incomplete
// branch the one that can observe it: a submitted buffer is cleared before
// anything can be asserted about it.
#[cfg(feature = "helix")]
#[test]
fn helix_normal_submit_keeps_the_grapheme_under_the_cursor() {
let mut rl = helix_engine_with_validator();
let signal = drive_until_signal(
&mut rl,
&[
ch('"'),
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
key(KeyCode::Enter),
],
);
assert!(signal.is_none(), "incomplete input must not submit");
// Not `"ab\n`: the cursor rests *on* the `c`, which is not a selection
// the break should consume.
assert_eq!(rl.editor.get_buffer(), "\"abc\n");
}
#[cfg(feature = "helix")]
#[test]
fn helix_normal_submit_breaks_at_the_cursor_not_past_it() {
let mut rl = helix_engine_with_validator();
// `hh` walks the caret back onto the `a`.
let signal = drive_until_signal(
&mut rl,
&[
ch('"'),
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
ch('h'),
ch('h'),
key(KeyCode::Enter),
],
);
assert!(signal.is_none(), "incomplete input must not submit");
// The head already sits past the covered `a`, so collapsing forward
// breaks there. A vi-style `MoveRight` would step one further and give
// `"ab\nc`; a plain deselect would land before it, at `"\nabc`.
assert_eq!(rl.editor.get_buffer(), "\"a\nbc");
}
/// Helix rests *on* the line terminator under `BlockOverNewline`, which vi
/// never does, so a break from there is a case vi's handling never answers.
#[cfg(feature = "helix")]
#[test]
fn helix_normal_submit_breaks_from_a_terminator() {
let mut rl = helix_engine_with_validator();
let signal = drive_until_signal(
&mut rl,
&[
ch('"'),
ch('a'),
key(KeyCode::Esc),
key(KeyCode::Enter),
key(KeyCode::Esc),
key(KeyCode::Enter),
],
);
assert!(signal.is_none(), "incomplete input must not submit");
assert_eq!(rl.editor.get_buffer(), "\"a\n\n");
}
/// The submitted path cannot assert on the buffer (`submit_buffer` clears
/// it), so pin it through the returned signal instead.
#[cfg(feature = "helix")]
#[test]
fn helix_normal_submit_returns_the_whole_buffer() {
let mut rl = Reedline::create().with_edit_mode(Box::<crate::Helix>::default());
rl.painter.force_prompt_anchored_for_test(0);
let signal = drive_until_signal(
&mut rl,
&[
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
key(KeyCode::Enter),
],
);
match signal {
Some(Signal::Success(buffer)) => assert_eq!(buffer, "abc"),
other => panic!("expected a submitted buffer, got {other:?}"),
}
}
// --- `j` / `k` ---
//
// These lower to `ReedlineEvent::Up`/`Down` rather than a `MotionTarget`,
// since which of line movement and history traversal applies is decided
// against the whole buffer, above where a motion resolves.
/// Two lines, built through the incomplete branch since a bare Enter would
/// submit. Leaves the caret on the second line, in insert mode.
#[cfg(feature = "helix")]
fn two_line_helix_engine() -> Reedline {
let mut rl = helix_engine_with_validator();
drive_until_signal(
&mut rl,
&[
ch('"'),
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
key(KeyCode::Enter),
ch('d'),
ch('e'),
ch('f'),
],
);
// `"abc` is 0..4, the terminator 4, `def` 5..8. Both lines are wide
// enough for a column-preserving move to differ from a line-start one.
assert_eq!(rl.editor.get_buffer(), "\"abc\ndef", "setup");
rl
}
#[cfg(feature = "helix")]
#[test]
fn helix_normal_k_moves_a_line_before_it_reaches_history() {
let mut rl = two_line_helix_engine();
drive_until_signal(&mut rl, &[key(KeyCode::Esc), ch('k')]);
assert!(
rl.editor.insertion_point() < 4,
"expected the caret on the first line, got {}",
rl.editor.insertion_point()
);
assert_eq!(
rl.editor.get_buffer(),
"\"abc\ndef",
"history must not load yet"
);
}
#[cfg(feature = "helix")]
#[test]
fn helix_normal_k_recalls_history_at_the_first_line() {
let mut rl = seam_engine(Box::<crate::Helix>::default());
let signal = drive_until_signal(
&mut rl,
&[
ch('o'),
ch('n'),
ch('e'),
key(KeyCode::Esc),
key(KeyCode::Enter),
],
);
assert!(
matches!(signal, Some(Signal::Success(ref b)) if b == "one"),
"setup: expected a submit, got {signal:?}"
);
// The buffer is empty now, so there is no line above to move to.
drive_until_signal(&mut rl, &[key(KeyCode::Esc), ch('k')]);
assert_eq!(rl.editor.get_buffer(), "one");
}
#[cfg(feature = "helix")]
#[test]
fn helix_select_extends_with_arrow_keys() {
// The original report: `v` then arrows moved the caret but dropped the
// anchor, since the arrows resolved through the mode-blind normal
// table to `MoveRight { select: false }`.
let mut rl = helix_engine_with_validator();
drive_until_signal(
&mut rl,
&[
ch('"'),
ch('a'),
ch('b'),
ch('c'),
key(KeyCode::Esc),
ch('g'),
ch('h'),
ch('v'),
],
);
drive_until_signal(&mut rl, &[key(KeyCode::Right), key(KeyCode::Right)]);
assert_eq!(
rl.editor.get_selection(),
Some((0, 3)),
"arrows must extend like `l` does"
);
}
#[cfg(feature = "helix")]
#[test]
fn helix_select_j_extends_to_the_column_normal_mode_would_land_on() {
let mut rl = two_line_helix_engine();
// `k` from the `f` (column 2) lands on the `b`, also column 2.
drive_until_signal(&mut rl, &[key(KeyCode::Esc), ch('k')]);
assert_eq!(rl.editor.insertion_point(), 2, "setup: expected the `b`");
drive_until_signal(&mut rl, &[ch('v'), ch('j')]);
assert_eq!(
rl.editor.get_buffer(),
"\"abc\ndef",
"select mode must not traverse history"
);
let (start, end) = rl.editor.get_selection().expect("expected a selection");
// Down from column 2 is the `f` at 7, not the line start at 5: the
// extension has to stop where a normal-mode `j` would land.
assert_eq!(
(start, end),
(2, 8),
"expected the selection to reach the `f`, not the line start"
);
}
#[cfg(feature = "helix")]
#[test]
fn helix_tilde_switches_case_and_keeps_the_selection() {
let mut rl = seam_engine(Box::<crate::Helix>::default());
drive_until_signal(&mut rl, &[ch('a'), ch('b'), key(KeyCode::Esc), ch('%')]);
assert_eq!(rl.editor.get_selection(), Some((0, 2)), "setup");
drive_until_signal(&mut rl, &[ch('~')]);
assert_eq!(rl.editor.get_buffer(), "AB");
// Still selected, so a second `~` acts on the same span.
assert_eq!(rl.editor.get_selection(), Some((0, 2)));
drive_until_signal(&mut rl, &[ch('~')]);
assert_eq!(rl.editor.get_buffer(), "ab");
}
#[cfg(feature = "helix")]
#[test]
fn helix_backtick_lowercases_and_alt_backtick_uppercases() {
let alt_backtick = KeyEvent::new(KeyCode::Char('`'), KeyModifiers::ALT);
let mut rl = seam_engine(Box::<crate::Helix>::default());
drive_until_signal(&mut rl, &[ch('A'), ch('b'), key(KeyCode::Esc), ch('%')]);
assert_eq!(rl.editor.get_selection(), Some((0, 2)), "setup");
drive_until_signal(&mut rl, &[ch('`')]);
assert_eq!(rl.editor.get_buffer(), "ab");
drive_until_signal(&mut rl, &[alt_backtick]);
assert_eq!(rl.editor.get_buffer(), "AB");
// Both keep the span, so they can be applied in sequence.
assert_eq!(rl.editor.get_selection(), Some((0, 2)));
}
// --- `%`, `A`, `I` ---
#[cfg(feature = "helix")]
#[test]
fn helix_percent_selects_the_whole_buffer() {
let mut rl = seam_engine(Box::<crate::Helix>::default());
drive_until_signal(
&mut rl,
&[ch('a'), ch('b'), ch('c'), key(KeyCode::Esc), ch('%')],
);
assert_eq!(rl.editor.get_selection(), Some((0, 3)));
}
/// Appending has to land *past* the last grapheme: the block cursor rests on
/// it, while insert mode sits between graphemes.
#[cfg(feature = "helix")]
#[test]
fn helix_capital_a_appends_past_the_last_grapheme() {
use crate::PromptHelixMode;
let mut rl = seam_engine(Box::<crate::Helix>::default());
drive_until_signal(
&mut rl,
&[ch(' '), ch('h'), ch('i'), key(KeyCode::Esc), ch('A')],
);
assert_eq!(rl.editor.insertion_point(), 3);
assert!(matches!(
rl.prompt_edit_mode(),
PromptEditMode::Helix(PromptHelixMode::Insert)
));
// Typing lands at the end rather than one grapheme short.
drive_until_signal(&mut rl, &[ch('!')]);
assert_eq!(rl.editor.get_buffer(), " hi!");
}
/// The leading space is what separates this from a plain line start.
#[cfg(feature = "helix")]
#[test]
fn helix_capital_i_inserts_at_the_first_non_blank() {
let mut rl = seam_engine(Box::<crate::Helix>::default());
drive_until_signal(
&mut rl,
&[ch(' '), ch('h'), ch('i'), key(KeyCode::Esc), ch('I')],
);
assert_eq!(rl.editor.insertion_point(), 1);
drive_until_signal(&mut rl, &[ch('!')]);
assert_eq!(rl.editor.get_buffer(), " !hi");
}
#[test]
#[cfg(feature = "helix")]
fn with_edit_mode_builder_accepts_custom_helix_mode() {
use crate::PromptHelixMode;
let reedline = Reedline::create().with_edit_mode(Box::new(crate::Helix::default()));
assert!(matches!(
reedline.prompt_edit_mode(),
PromptEditMode::Helix(PromptHelixMode::Insert)
));
}
#[test]
fn break_signal_builder_pattern() {
let signal = Arc::new(AtomicBool::new(false));
let _reedline = Reedline::create()
.with_quick_completions(true)
.with_break_signal(signal)
.with_partial_completions(true);
}
#[test]
fn break_signal_is_send() {
fn f<S: Send>(_: S) {}
let signal = Arc::new(AtomicBool::new(false));
f(Reedline::create().with_break_signal(signal));
}
#[test]
fn take_repaint_request_is_false_without_a_handle() {
let reedline = Reedline::create();
assert!(!reedline.take_repaint_request());
assert!(!reedline.take_repaint_request());
}
#[test]
fn take_repaint_request_consumes_the_request() {
let mut reedline = Reedline::create();
let signal = reedline.repaint_signal();
signal.request_repaint();
assert!(reedline.take_repaint_request());
// Consumed: no repaint left pending
assert!(!reedline.take_repaint_request());
// A new request is honored again
signal.request_repaint();
assert!(reedline.take_repaint_request());
assert!(!reedline.take_repaint_request());
}
#[test]
fn repaint_signal_switches_input_loop_to_polling() {
let mut reedline = Reedline::create();
assert!(
!reedline.input_needs_polling(),
"without external triggers the loop should block on input"
);
let _signal = reedline.repaint_signal();
assert!(
reedline.input_needs_polling(),
"a repaint handle must switch the loop to polling so requests are noticed"
);
}
#[test]
fn repaint_request_during_active_read_survives_while_stale_ones_are_dropped() {
// Emulates the loop's consumption pattern: read_line_helper drains any
// stale pre-read_line request before painting the initial prompt, so
// only requests raised afterwards trigger an extra repaint.
let mut reedline = Reedline::create();
let signal = reedline.repaint_signal();
// Raised while no read_line is active -> dropped by the initial drain
signal.request_repaint();
reedline.take_repaint_request();
assert!(!reedline.take_repaint_request());
// Raised "mid-edit" -> observed by the next loop iteration
signal.request_repaint();
assert!(reedline.take_repaint_request());
}
#[test]
fn repaint_signal_handles_share_one_flag() {
// Every handle returned by `repaint_signal()` (and its clones) must
// observe the same underlying flag, so a request from any of them is
// seen exactly once by the loop.
let mut reedline = Reedline::create();
let a = reedline.repaint_signal();
let b = reedline.repaint_signal();
let c = a.clone();
b.request_repaint();
assert!(reedline.take_repaint_request());
assert!(!reedline.take_repaint_request());
// A request made through the clone is also observed.
c.request_repaint();
assert!(reedline.take_repaint_request());
}
#[test]
fn repaint_signal_survives_behind_an_arc() {
// This is what a shell would be using...
// handed to a worker that knows nothing about `Reedline`.
use std::sync::Arc;
let mut reedline = Reedline::create();
let shared: Arc<RepaintSignal> = Arc::new(reedline.repaint_signal());
let worker = shared.clone();
std::thread::spawn(move || worker.request_repaint())
.join()
.expect("worker thread panicked");
assert!(reedline.take_repaint_request());
}
#[test]
fn repaint_request_collapses_rapid_fire() {
// Many requests arriving between two loop iterations must collapse into
// a single repaint, not N. `take` is a swap(false), so only one take
// should observe the request regardless of how many were raised.
let mut reedline = Reedline::create();
let signal = reedline.repaint_signal();
for _ in 0..1_000 {
signal.request_repaint();
}
assert!(reedline.take_repaint_request());
assert!(!reedline.take_repaint_request());
}
#[test]
fn repaint_signal_is_independent_of_break_signal() {
// The two out-of-band triggers must not interfere: arming a repaint
// request must not be mistaken for a break, and vice versa.
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
let mut reedline = Reedline::create().with_break_signal(Arc::new(AtomicBool::new(false)));
let repaint = reedline.repaint_signal();
repaint.request_repaint();
assert!(reedline.take_repaint_request());
assert!(
!reedline
.break_signal
.as_ref()
.unwrap()
.load(std::sync::atomic::Ordering::Relaxed),
"repaint must not toggle the break flag"
);
reedline
.break_signal
.as_ref()
.unwrap()
.store(true, std::sync::atomic::Ordering::Relaxed);
assert!(
reedline
.break_signal
.as_ref()
.unwrap()
.swap(false, std::sync::atomic::Ordering::Relaxed),
"break flag must be independently observable"
);
assert!(
!reedline.take_repaint_request(),
"break must not leave a repaint pending"
);
}
#[test]
fn signal_external_break_pattern_match() {
let buffer_content = "some partial input".to_string();
let signal = Signal::ExternalBreak(buffer_content.clone());
match signal {
Signal::ExternalBreak(buf) => assert_eq!(buf, buffer_content),
_ => panic!("Expected Signal::ExternalBreak"),
}
}
fn reedline_with_abbrevs_and_string_lit_override(abbrevs: &[(&str, &str)]) -> Reedline {
let map = abbrevs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Reedline::create()
.with_highlighter(Box::new(ExampleHighlighter::default()))
.with_abbreviations(map)
}
fn reedline_with_abbrevs_and_default_string_lit_check(abbrevs: &[(&str, &str)]) -> Reedline {
let map = abbrevs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Reedline::create()
.with_highlighter(Box::new(SimpleMatchHighlighter::default()))
.with_abbreviations(map)
}
fn set_buffer_at_end(reedline: &mut Reedline, text: &str) {
reedline.run_edit_commands(&[
EditCommand::Clear,
EditCommand::InsertString(text.to_string()),
]);
}
#[test]
fn abbreviation_expands_on_submit() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "gc");
let event = reedline.try_expand_abbreviation_at_cursor(true);
assert!(event.is_some(), "expected expansion on submit");
reedline.run_edit_commands(&match event.unwrap() {
ReedlineEvent::Edit(cmds) => cmds,
_ => panic!("expected Edit event"),
});
assert_eq!(reedline.current_buffer_contents(), "git commit");
}
#[test]
fn abbreviation_expands_on_space_without_double_space() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
// When expansion is triggered by <space>, the triggering space has
// already been inserted into the buffer before the expansion runs.
set_buffer_at_end(&mut reedline, "gc ");
let event = reedline.try_expand_abbreviation_at_cursor(false);
assert!(event.is_some(), "expected expansion on space");
reedline.run_edit_commands(&match event.unwrap() {
ReedlineEvent::Edit(cmds) => cmds,
_ => panic!("expected Edit event"),
});
// Exactly one trailing space: the triggering space must be replaced,
// not left in place alongside the inserted suffix space.
assert_eq!(reedline.current_buffer_contents(), "git commit ");
}
#[test]
fn abbreviation_no_match_returns_none() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "gx");
assert!(reedline.try_expand_abbreviation_at_cursor(true).is_none());
}
#[test]
fn abbreviation_empty_buffer_returns_none() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
assert!(reedline.try_expand_abbreviation_at_cursor(true).is_none());
}
#[test]
fn abbreviation_expands_last_word_only() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "sudo gc");
let event = reedline.try_expand_abbreviation_at_cursor(true);
assert!(event.is_some());
reedline.run_edit_commands(&match event.unwrap() {
ReedlineEvent::Edit(cmds) => cmds,
_ => panic!("expected Edit event"),
});
assert_eq!(reedline.current_buffer_contents(), "sudo git commit");
}
#[rstest]
#[case("\"hello gc", false)]
#[case("'hello gc", false)]
#[case("\"hello\" gc", true)]
#[case("'Сегодня хороший gc", false)]
#[case("'Сегодня' gc", true)]
#[case("'今日はいい日だ gc", false)]
#[case("'🔥🎉 gc", false)]
fn abbreviation_string_detection_with_override(
#[case] buffer: &str,
#[case] should_expand: bool,
) {
let mut reedline = reedline_with_abbrevs_and_string_lit_override(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, buffer);
assert_eq!(
reedline.try_expand_abbreviation_at_cursor(true).is_some(),
should_expand
);
}
#[rstest]
#[case("\"hello gc")]
#[case("'hello gc")]
#[case("\"hello\" gc")]
#[case("'Сегодня хороший gc")]
#[case("'Сегодня' gc")]
#[case("'今日はいい日だ gc")]
#[case("'🔥🎉 gc")]
fn abbreviation_string_detection_default(#[case] buffer: &str) {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, buffer);
assert!(
reedline.try_expand_abbreviation_at_cursor(true).is_some(),
"must expand when highlighter does not override should_expand_abbr"
);
}
#[test]
fn abbreviation_non_ascii_key_and_expansion() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("café", "coffee shop")]);
set_buffer_at_end(&mut reedline, "café");
let event = reedline.try_expand_abbreviation_at_cursor(true);
assert!(event.is_some(), "expected expansion for non-ASCII key");
reedline.run_edit_commands(&match event.unwrap() {
ReedlineEvent::Edit(cmds) => cmds,
_ => panic!("expected Edit event"),
});
assert_eq!(reedline.current_buffer_contents(), "coffee shop");
}
#[test]
fn try_expand_abbreviation_survives_multibyte_char_before_cursor() {
// Regression: `word_end` was a raw byte subtraction of `offset` from the
// byte cursor position. With a multi-byte char (e.g. pasted CJK) right
// before the cursor, `word_end` could land inside that char, so slicing
// the buffer panicked with "byte index N is not a char boundary".
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "中");
// Place the cursor at byte offset 1, inside the 3-byte '中'. Pre-patch,
// `&buffer[..1]` would panic here.
let mut line_buffer = LineBuffer::new();
line_buffer.set_buffer("中".to_string());
line_buffer.set_insertion_point(1);
reedline
.editor
.set_line_buffer(line_buffer, UndoBehavior::CreateUndoPoint);
// Must return without panicking (no match, so `None` is expected).
assert!(reedline.try_expand_abbreviation_at_cursor(true).is_none());
}
#[test]
fn abbreviation_leading_spaces_returns_none() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, " ");
assert!(reedline.try_expand_abbreviation_at_cursor(true).is_none());
}
#[test]
fn abbreviation_mid_word_cursor_on_submit_returns_none() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "gcsomething");
reedline.run_edit_commands(&[EditCommand::MoveToPosition {
position: 2,
select: false,
}]);
assert!(
reedline.try_expand_abbreviation_at_cursor(true).is_none(),
"must not expand the prefix of a word when the cursor is mid-word"
);
}
#[test]
fn abbreviation_expands_before_trailing_text_on_submit() {
let mut reedline =
reedline_with_abbrevs_and_default_string_lit_check(&[("gc", "git commit")]);
set_buffer_at_end(&mut reedline, "gc rest");
reedline.run_edit_commands(&[EditCommand::MoveToPosition {
position: 2,
select: false,
}]);
let event = reedline.try_expand_abbreviation_at_cursor(true);
assert!(
event.is_some(),
"expected expansion at a real word boundary"
);
reedline.run_edit_commands(&match event.unwrap() {
ReedlineEvent::Edit(cmds) => cmds,
_ => panic!("expected Edit event"),
});
assert_eq!(reedline.current_buffer_contents(), "git commit rest");
}
// Feed one key as its own batch, mirroring real interactive input where each
// keypress drives a separate `process_input_batch`.
fn step_key(rl: &mut Reedline, k: KeyEvent) -> ControlFlow<Signal> {
rl.process_input_batch(&DefaultPrompt::default(), vec![Event::Key(k)])
.expect("batch ok")
}
#[test]
fn abbreviation_expands_on_enter_in_vi_normal() {
// Regression: a vi-normal block caret rests *on* the last grapheme, so
// before the caret-release on Enter the submit-time scan saw `g` instead
// of `gc` and silently skipped expansion.
let mut abbreviations = HashMap::new();
abbreviations.insert("gc".to_string(), "git commit".to_string());
let mut rl = seam_engine(Box::<crate::Vi>::default()).with_abbreviations(abbreviations);
let _ = step_key(&mut rl, ch('g'));
let _ = step_key(&mut rl, ch('c'));
let _ = step_key(&mut rl, key(KeyCode::Esc)); // vi normal, caret on 'c'
match step_key(&mut rl, key(KeyCode::Enter)) {
ControlFlow::Break(Signal::Success(buf)) => assert_eq!(buf, "git commit"),
other => panic!("expected submit, got {other:?}"),
}
}
#[test]
fn vi_normal_enter_inserts_newline_at_end_not_mid_word() {
// Regression: the same stranded block caret made an incomplete-input
// newline land one grapheme short, splitting the last word (`ab` -> `a\nb`).
struct AlwaysIncomplete;
impl crate::Validator for AlwaysIncomplete {
fn validate(&self, _line: &str) -> ValidationResult {
ValidationResult::Incomplete
}
}
let mut rl =
seam_engine(Box::<crate::Vi>::default()).with_validator(Box::new(AlwaysIncomplete));
let _ = step_key(&mut rl, ch('a'));
let _ = step_key(&mut rl, ch('b'));
let _ = step_key(&mut rl, key(KeyCode::Esc)); // vi normal, caret on 'b'
let _ = step_key(&mut rl, key(KeyCode::Enter)); // incomplete -> insert newline
assert_eq!(rl.editor.get_buffer(), "ab\n");
}
#[cfg(feature = "bashisms")]
fn reedline_with_history_and_string_lit_check(entries: &[&str]) -> Reedline {
let mut reedline =
Reedline::create().with_highlighter(Box::new(ExampleHighlighter::default()));
for entry in entries {
reedline
.history
.save(HistoryItem::from_command_line(*entry))
.expect("failed to save history");
}
reedline
}
#[cfg(feature = "bashisms")]
fn reedline_with_history_default(entries: &[&str]) -> Reedline {
let mut reedline =
Reedline::create().with_highlighter(Box::new(SimpleMatchHighlighter::default()));
for entry in entries {
reedline
.history
.save(HistoryItem::from_command_line(*entry))
.expect("failed to save history");
}
reedline
}
#[rstest]
#[case("!!", true)]
#[case("\"echo !!", false)]
#[case("'echo !!", false)]
#[case("'echo' !!", true)]
#[case("\"echo !git", false)]
#[case("'echo !git", false)]
#[case("'Сегодня !!", false)]
#[case("'今日は !!", false)]
#[case("'🔥 !!", false)]
#[cfg(feature = "bashisms")]
fn bang_string_detection_with_override(#[case] buffer: &str, #[case] should_expand: bool) {
let mut reedline = reedline_with_history_and_string_lit_check(&["git status"]);
set_buffer_at_end(&mut reedline, buffer);
assert_eq!(reedline.parse_bang_command().is_some(), should_expand);
}
#[rstest]
#[case("\"echo !!")]
#[case("'echo !!")]
#[case("'echo' !!")]
#[case("\"echo !git")]
#[case("'echo !git")]
#[case("'Сегодня !!")]
#[case("'今日は !!")]
#[case("'🔥 !!")]
#[cfg(feature = "bashisms")]
fn bang_always_expands_without_override(#[case] buffer: &str) {
let mut reedline = reedline_with_history_default(&["git status"]);
set_buffer_at_end(&mut reedline, buffer);
assert!(
reedline.parse_bang_command().is_some(),
"must expand when highlighter does not override should_expand_abbr"
);
}
#[rstest]
#[case("")]
#[case("line of text")]
#[case(
"longgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line of text"
)]
fn test_move_to_line_start(#[case] input: &str) {
let mut reedline = Reedline::create();
// Write the string, and then move to the start of the line.
let insertion = EditCommand::InsertString(String::from(input));
reedline.run_edit_commands(&[insertion]);
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(reedline.editor.line_buffer().insertion_point(), 0);
}
#[rstest]
#[case("")]
#[case("line of text")]
#[case(
"longgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line of text"
)]
fn test_move_to_line_start_history(#[case] input: &str) {
let mut reedline = Reedline::create();
// Enter the string into history, then scroll back up and move to the start of the line.
let history = HistoryItem::from_command_line(input);
reedline.history.save(history).unwrap();
reedline.previous_history();
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(reedline.editor.line_buffer().insertion_point(), 0);
}
#[rstest]
#[case("a\nb", 2)]
#[case("123456789\n123456789\n123456789", 20)]
#[case("0\n1\n2\n3\n4\n5\n6\n7\n8\n9", 18)]
fn test_move_to_line_start_multiline(#[case] input: &str, #[case] last_line_start: usize) {
let mut reedline = Reedline::create();
// Write the string, and then move to the start of the last line.
let insertion = EditCommand::InsertString(String::from(input));
reedline.run_edit_commands(&[insertion]);
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(
reedline.editor.line_buffer().insertion_point(),
last_line_start
);
}
#[rstest]
#[case("a\nb")]
#[case("123456789\n123456789\n123456789")]
#[case("0\n1\n2\n3\n4\n5\n6\n7\n8\n9")]
fn test_move_to_line_start_multiline_history_up_start(#[case] input: &str) {
let mut reedline = Reedline::create();
// Enter the string into history, then scroll back up and move to the start of the line.
let history = HistoryItem::from_command_line(input);
reedline.history.save(history).unwrap();
reedline.previous_history();
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(reedline.editor.line_buffer().insertion_point(), 0);
}
#[rstest]
#[case("a\nb", 2)]
#[case("123456789\n123456789\n123456789", 10)]
#[case("0\n1\n2\n3\n4\n5\n6\n7\n8\n9", 2)]
fn test_move_to_line_start_multiline_history_up_down_start(
#[case] input: &str,
#[case] second_line_start: usize,
) {
let mut reedline = Reedline::create();
// Enter the string again, then scroll up in history, move down one line,
// and move to the start of the second line.
let history = HistoryItem::from_command_line(input);
reedline.history.save(history).unwrap();
reedline.previous_history();
reedline.down_command();
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(
reedline.editor.line_buffer().insertion_point(),
second_line_start
);
}
#[rstest]
#[case("a\nb", 2)]
#[case("123456789\n123456789\n123456789", 20)]
#[case("0\n1\n2\n3\n4\n5\n6\n7\n8\n9", 18)]
fn test_move_to_line_start_multiline_history_up_end_start(
#[case] input: &str,
#[case] last_line_start: usize,
) {
let mut reedline = Reedline::create();
// Enter the string again, then scroll up in history, move to the end of the text,
// and move to the start of the last line.
let history = HistoryItem::from_command_line(input);
reedline.history.save(history).unwrap();
reedline.previous_history();
let move_to_end = EditCommand::MoveToEnd { select: false };
reedline.run_edit_commands(&[move_to_end]);
let move_to_start = EditCommand::MoveToLineStart { select: false };
reedline.run_edit_commands(&[move_to_start]);
assert_eq!(
reedline.editor.line_buffer().insertion_point(),
last_line_start
);
}
#[test]
fn test_complete_line_from_history() {
let completer = Box::new(DefaultCompleter::new(Vec::from([String::from("67")])));
let completion_menu = ReedlineMenu::EngineCompleter(Box::new(
ColumnarMenu::default().with_name("completion_menu"),
));
let mut reedline = Reedline::create()
.with_quick_completions(true)
.with_completer(completer)
.with_menu(completion_menu);
// Save "6" to the history and scroll back to it
let history = HistoryItem::from_command_line("6");
reedline.history.save(history).unwrap();
reedline.previous_history();
assert_eq!(reedline.current_buffer_contents(), "6");
// Perform quick completion
let prompt = DefaultPrompt::default();
let completion = ReedlineEvent::Menu(String::from("completion_menu"));
reedline.handle_event(&prompt, completion).unwrap();
assert_eq!(reedline.current_buffer_contents(), "67");
// Insert the "x" to the prompt
let insertion = EditCommand::InsertString(String::from("x"));
reedline.run_edit_commands(&[insertion]);
assert_eq!(reedline.current_buffer_contents(), "67x");
}
/// A completer that computes in the background: the first request cannot be answered
/// for the line on screen, and only later ones carry its values. This is what a cold
/// cache looks like from the engine's side (nushell/reedline#1142).
struct DeferredCompleter {
first_answer: CompletionResult,
values: Vec<String>,
dispatched: bool,
}
impl DeferredCompleter {
/// A cold cache: nothing to show at all until the background work lands.
fn pending(values: &[&str]) -> Self {
Self::new(CompletionResult::Pending, values)
}
/// A warm-but-wrong cache: `stale` is answered from a neighbouring entry, so the
/// value is real but its span belongs to `origin_buffer` rather than the line.
fn stale(stale: &str, origin_buffer: &str, values: &[&str]) -> Self {
let first_answer = CompletionResult::Stale {
suggestions: vec![Suggestion {
value: stale.to_string(),
span: Span {
start: 0,
end: origin_buffer.len(),
},
..Default::default()
}]
.into(),
origin: CompletionOrigin::new(origin_buffer, origin_buffer.len()),
partial: None,
};
Self::new(first_answer, values)
}
fn new(first_answer: CompletionResult, values: &[&str]) -> Self {
Self {
first_answer,
values: values.iter().map(|value| value.to_string()).collect(),
dispatched: false,
}
}
}
impl Completer for DeferredCompleter {
fn complete(&mut self, _line: &str, pos: usize) -> CompletionResult {
if !self.dispatched {
self.dispatched = true;
return self.first_answer.clone();
}
CompletionResult::fresh(
self.values
.iter()
.map(|value| Suggestion {
value: value.clone(),
span: Span { start: 0, end: pos },
..Default::default()
})
.collect::<Vec<_>>(),
)
}
fn poll_completion(&mut self) -> CompletionStatus {
if self.dispatched {
CompletionStatus::Ready
} else {
CompletionStatus::Idle
}
}
}
/// [`engine_awaiting`] with partial completions off.
fn engine_awaiting_completions(values: &[&str], buffer: &str, quick: bool) -> Reedline {
engine_awaiting(values, buffer, quick, false)
}
/// Engine with `quick` and `partial` completions and a background completer over
/// `values`, with `buffer` typed and the completion menu activated — the state right
/// after Tab, while the completer is still working.
fn engine_awaiting(values: &[&str], buffer: &str, quick: bool, partial: bool) -> Reedline {
let (reedline, _) = activate_menu_over(
Box::new(DeferredCompleter::pending(values)),
buffer,
quick,
partial,
);
// Nothing could be decided yet, the premise of every test below.
assert_eq!(reedline.current_buffer_contents(), buffer);
reedline
}
/// Type `buffer` and press Tab, against a completer that answers however the test
/// needs it to. Returns the engine and how the menu activation was handled.
fn activate_menu_over(
completer: Box<dyn Completer + Send>,
buffer: &str,
quick: bool,
partial: bool,
) -> (Reedline, EventStatus) {
let completion_menu = ReedlineMenu::EngineCompleter(Box::new(
ColumnarMenu::default().with_name("completion_menu"),
));
let mut reedline = Reedline::create()
.with_completer(completer)
.with_menu(completion_menu)
.with_quick_completions(quick)
.with_partial_completions(partial);
// Settling repaints, which needs a painter that believes it is on a terminal.
// Size first: `handle_resize` invalidates the anchor the next line pins.
reedline.painter.handle_resize(80, 24);
reedline.painter.force_prompt_anchored_for_test(0);
reedline.run_edit_commands(&[EditCommand::InsertString(buffer.to_string())]);
let status = reedline
.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::Menu(String::from("completion_menu")),
)
.unwrap();
(reedline, status)
}
fn settle(reedline: &mut Reedline) {
reedline
.settle_completions(&DefaultPrompt::default())
.unwrap();
}
/// The regression: a lone suggestion that arrives after the menu opened must still be
/// accepted, exactly as a synchronous completer's would have been.
#[test]
fn quick_completion_accepts_a_lone_suggestion_that_arrives_late() {
let mut reedline = engine_awaiting_completions(&["crates"], "cr", true);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "crates");
assert!(!menu_is_active(&reedline), "accepting closes the menu");
}
/// The decision belongs to the keystroke that asked for it. Once the user has typed
/// on, a late result must not rewrite the line underneath them.
#[test]
fn a_late_lone_suggestion_is_dropped_once_the_line_moved_on() {
let mut reedline = engine_awaiting_completions(&["crates"], "cr", true);
send_edit(&mut reedline, EditCommand::InsertChar('a'));
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "cra");
}
/// Arming happens before the count is final, so settling has to re-check it: several
/// suggestions mean a menu, not an acceptance.
#[test]
fn late_results_with_several_suggestions_only_populate_the_menu() {
let mut reedline = engine_awaiting_completions(&["test", "this", "that"], "t", true);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "t");
assert!(menu_is_active(&reedline));
}
/// An arm is spent by the result that settles it, so a later request cannot inherit it.
#[test]
fn an_unsatisfied_arm_does_not_fire_on_a_later_result() {
let mut reedline = engine_awaiting_completions(&["test", "this", "that"], "t", true);
settle(&mut reedline);
assert!(reedline.deferred_menu_completion.is_none(), "arm is spent");
// A second round of results, now down to one value, with no Tab in between.
reedline.completer = Box::new(DeferredCompleter::pending(&["test"]));
reedline.completer.complete("t", 1);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "t");
}
/// The other half of the same Tab: partial completions read the same empty menu the
/// quick check did, so a shared prefix must be spliced in when the values land.
#[test]
fn late_results_splice_the_shared_prefix() {
let mut reedline = engine_awaiting(&["nu-cmd-base", "nu-cmd-lang"], "nu-cm", true, true);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "nu-cmd-");
}
/// A shared prefix is spliced under `partial` alone, with no quick completions.
#[test]
fn late_results_splice_the_shared_prefix_without_quick_completions() {
let mut reedline = engine_awaiting(&["nu-cmd-base", "nu-cmd-lang"], "nu-cm", false, true);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "nu-cmd-");
}
/// Accepting a lone value wins over splicing, as it does on activation.
#[test]
fn a_lone_late_suggestion_is_accepted_rather_than_spliced() {
let mut reedline = engine_awaiting(&["crates"], "cr", true, true);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "crates");
assert!(!menu_is_active(&reedline));
}
/// Splicing is owed to a keystroke too, and is void once the line moved on.
#[test]
fn a_late_shared_prefix_is_dropped_once_the_line_moved_on() {
let mut reedline = engine_awaiting(&["nu-cmd-base", "nu-cmd-lang"], "nu-cm", true, true);
send_edit(&mut reedline, EditCommand::InsertChar('d'));
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "nu-cmd");
}
/// With quick completions off, late results populate the menu and nothing else.
#[test]
fn late_results_never_auto_accept_without_quick_completions() {
let mut reedline = engine_awaiting_completions(&["crates"], "cr", false);
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "cr");
assert!(menu_is_active(&reedline));
}
/// A lone *stale* suggestion looks like a lone fresh one to the quick completion
/// check, but accepting it is a no-op. The Tab must still be honoured once the real
/// answer lands.
#[test]
fn a_lone_stale_suggestion_does_not_swallow_the_completion() {
let (mut reedline, _) = activate_menu_over(
Box::new(DeferredCompleter::stale("console", "co", &["crates"])),
"cr",
true,
false,
);
// The stale span is refused, so the buffer is untouched.
assert_eq!(reedline.current_buffer_contents(), "cr");
settle(&mut reedline);
assert_eq!(
reedline.current_buffer_contents(),
"crates",
"the fresh result was dropped because the stale one closed the menu first"
);
}
/// The same lone stale value through the second route: `MenuNext` with the menu
/// already open. The accept is refused downstream either way, but the `Enter` it
/// rode on would still deactivate the menu, so the pending completion had nothing
/// left to land in.
#[test]
fn menu_next_does_not_close_the_menu_over_a_lone_stale_value() {
let (mut reedline, _) = activate_menu_over(
Box::new(DeferredCompleter::stale("console", "co", &["crates"])),
"cr",
true,
false,
);
assert!(menu_is_active(&reedline), "setup");
reedline
.handle_event(&DefaultPrompt::default(), ReedlineEvent::MenuNext)
.unwrap();
assert!(
menu_is_active(&reedline),
"MenuNext accepted a provisional lone value and closed the menu"
);
assert_eq!(reedline.current_buffer_contents(), "cr");
// With the menu still open, the arm from the activation is still owed.
settle(&mut reedline);
assert_eq!(reedline.current_buffer_contents(), "crates");
}
/// The flicker: a menu opened over an answer that is not about this line stays off
/// screen, so a Tab that resolves to one suggestion never draws a menu at all.
#[test]
fn an_opening_menu_is_not_visible_until_answered() {
let (reedline, _) = activate_menu_over(
Box::new(DeferredCompleter::stale("console", "co", &["crates"])),
"cr",
true,
false,
);
let menu = reedline
.menus
.iter()
.find(|menu| menu.is_active())
.expect("the menu is open");
assert!(
menu.is_awaiting_first_answer(),
"it would only be taken away again once the real answer lands"
);
}
fn menu_is_active(reedline: &Reedline) -> bool {
reedline.menus.iter().any(|menu| menu.is_active())
}
/// Engine with a completion menu activated on a "th" buffer. "th" matches
/// two words, so quick completions don't auto-select on activation.
fn engine_with_active_menu(quick: bool, persistent: bool) -> Reedline {
let completer = Box::new(DefaultCompleter::new_with_wordlen(
vec![
String::from("test"),
String::from("this"),
String::from("that"),
],
1,
));
let completion_menu = ReedlineMenu::EngineCompleter(Box::new(
ColumnarMenu::default().with_name("completion_menu"),
));
let mut reedline = Reedline::create()
.with_completer(completer)
.with_menu(completion_menu)
.with_quick_completions(quick)
.with_persistent_menus(persistent);
reedline.run_edit_commands(&[EditCommand::InsertString(String::from("th"))]);
reedline
.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::Menu(String::from("completion_menu")),
)
.unwrap();
assert!(menu_is_active(&reedline));
reedline
}
/// Engine with a completion menu open over "th" and partial completions on, so
/// `MenuNext` reaches the completer through `can_partially_complete`.
fn engine_with_partial_completion_menu() -> Reedline {
let completer = Box::new(DefaultCompleter::new_with_wordlen(
vec![String::from("this"), String::from("that")],
1,
));
let completion_menu = ReedlineMenu::EngineCompleter(Box::new(
ColumnarMenu::default().with_name("completion_menu"),
));
let mut reedline = Reedline::create()
.with_completer(completer)
.with_menu(completion_menu)
.with_partial_completions(true);
reedline.run_edit_commands(&[EditCommand::InsertString(String::from("th"))]);
reedline
.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::Menu(String::from("completion_menu")),
)
.unwrap();
assert!(menu_is_active(&reedline));
reedline
}
/// The anchor cache exists to keep `cursor::position()` off the hot path (#1090),
/// so an event may only spend that round-trip when it actually runs a host
/// completer. Which events those are does not follow from whether the menu's
/// selection moved: `MenuNext` splices a partial completion first, `MenuPrevious`
/// does not. See #1130.
#[rstest]
#[case::next_queries_the_completer(ReedlineEvent::MenuNext, false)]
#[case::previous_only_moves(ReedlineEvent::MenuPrevious, true)]
fn menu_events_invalidate_the_anchor_only_when_they_query(
#[case] event: ReedlineEvent,
#[case] stays_verified: bool,
) {
let mut reedline = engine_with_partial_completion_menu();
reedline.painter.force_prompt_anchored_for_test(0);
reedline
.handle_event(&DefaultPrompt::default(), event)
.unwrap();
assert_eq!(
reedline.painter.prompt_anchor_is_verified_for_test(),
stays_verified
);
}
fn send_edit(reedline: &mut Reedline, command: EditCommand) {
reedline
.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::Edit(vec![command]),
)
.unwrap();
}
#[rstest]
#[case(false, false)]
#[case(false, true)]
#[case(true, false)]
#[case(true, true)]
fn test_menu_persistence_while_erasing(#[case] quick: bool, #[case] persistent: bool) {
let mut reedline = engine_with_active_menu(quick, persistent);
// quick completions close the menu on any backspace unless menus are persistent
send_edit(&mut reedline, EditCommand::Backspace);
assert_eq!(reedline.current_buffer_contents(), "t");
assert_eq!(menu_is_active(&reedline), persistent || !quick);
// emptying the buffer closes the menu unless menus are persistent
send_edit(&mut reedline, EditCommand::Backspace);
assert!(reedline.current_buffer_contents().is_empty());
assert_eq!(menu_is_active(&reedline), persistent);
}
#[rstest]
#[case(EditCommand::BackspaceWord)]
#[case(EditCommand::MoveToLineStart { select: false })]
fn test_menu_persistence_covers_all_quick_dismissal_commands(#[case] command: EditCommand) {
for persistent in [false, true] {
let mut reedline = engine_with_active_menu(true, persistent);
send_edit(&mut reedline, command.clone());
assert_eq!(menu_is_active(&reedline), persistent);
}
}
/// A hinter that always offers a fixed suggestion, so the completion flow can
/// be driven without the paint cycle that normally refreshes the hint.
struct FixedHinter(&'static str);
impl Hinter for FixedHinter {
fn handle(&mut self, _: &str, _: usize, _: &dyn History, _: bool, _: &str) -> String {
self.0.to_string()
}
fn complete_hint(&self) -> String {
self.0.to_string()
}
fn next_hint_token(&self) -> String {
self.0.to_string()
}
}
fn vi_with_hint(hint: &'static str) -> Reedline {
seam_engine(Box::<crate::Vi>::default()).with_hinter(Box::new(FixedHinter(hint)))
}
#[test]
fn vi_normal_history_hint_appends_at_buffer_end() {
// The reported bug: a block caret rests on the last grapheme, so the
// completion must append *after* it, not split it.
let mut rl = vi_with_hint("def");
rl.run_edit_commands(&[EditCommand::InsertString("abc".into())]);
drive(&mut rl, &[key(KeyCode::Esc)]); // vi normal, caret on 'c' at the end
rl.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::HistoryHintComplete,
)
.unwrap();
assert_eq!(rl.editor.get_buffer(), "abcdef");
}
#[test]
fn vi_visual_selection_blocks_hint_completion() {
// A hint completing over a selection would run through `delete_selection`
// and clobber it — the empty-cursor guard must suppress it.
let mut rl = vi_with_hint("def");
rl.run_edit_commands(&[EditCommand::InsertString("abc".into())]);
drive(&mut rl, &[key(KeyCode::Esc), ch('v')]); // visual: selection covers 'c' to len
rl.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::HistoryHintComplete,
)
.unwrap();
assert_eq!(rl.editor.get_buffer(), "abc");
}
#[test]
fn undo_removes_accepted_history_hint() {
let mut rl = vi_with_hint("def");
rl.run_edit_commands(&[EditCommand::InsertString("abc".into())]);
drive(&mut rl, &[key(KeyCode::Esc)]);
rl.handle_event(
&DefaultPrompt::default(),
ReedlineEvent::HistoryHintComplete,
)
.unwrap();
assert_eq!(rl.editor.get_buffer(), "abcdef");
rl.run_edit_commands(&[EditCommand::Undo]);
assert_eq!(rl.editor.get_buffer(), "abc");
}
#[test]
fn vi_normal_down_rests_on_last_grapheme() {
// Down onto a shorter last line must rest *on* the last grapheme, not the
// gap past it: `down_command` has to settle under the `OnGrapheme` policy.
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.run_edit_commands(&[EditCommand::InsertString("abc\nd".into())]); // a0 b1 c2 \n3 d4
drive(&mut rl, &[key(KeyCode::Esc)]); // vi normal
rl.run_edit_commands(&[
EditCommand::MoveToStart { select: false },
EditCommand::MoveRight { select: false },
EditCommand::MoveRight { select: false },
]); // caret on 'c' (col 2 of line 1)
rl.down_command();
assert_eq!(rl.editor.insertion_point(), 4); // on 'd', not 5 (past it)
}
#[test]
fn vi_normal_to_end_rests_on_last_grapheme() {
// `Alt+>` (ToEnd) is bound in vi normal; it must land on the last char.
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.run_edit_commands(&[EditCommand::InsertString("abc".into())]);
drive(&mut rl, &[key(KeyCode::Esc)]);
rl.run_edit_commands(&[EditCommand::MoveToStart { select: false }]); // 'a'
drive(
&mut rl,
&[KeyEvent::new(KeyCode::Char('>'), KeyModifiers::ALT)],
);
assert_eq!(rl.editor.insertion_point(), 2); // 'c', not 3 (past it)
}
#[test]
fn vi_normal_single_line_down_rests_on_last_grapheme() {
// Single-line buffer: `down` hits the last line and routes to history nav,
// which positions the cursor outside the command path. It must still
// settle on the last grapheme, not the gap past it.
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.run_edit_commands(&[EditCommand::InsertString("abc".into())]);
drive(&mut rl, &[key(KeyCode::Esc)]); // vi normal, on 'c'
rl.down_command(); // last line -> next_history (no forward entry -> draft)
assert_eq!(rl.editor.insertion_point(), 2); // 'c', not 3 (past it)
}
#[test]
fn vi_normal_end_of_line_rests_on_last_grapheme() {
// `$` on an interior line lands ON the last char, not the gap before `\n`.
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.run_edit_commands(&[EditCommand::InsertString("abc\ndef".into())]); // a0 b1 c2 \n3
drive(&mut rl, &[key(KeyCode::Esc)]);
rl.run_edit_commands(&[
EditCommand::MoveToStart { select: false },
EditCommand::MoveToLineEnd { select: false },
]);
assert_eq!(rl.editor.insertion_point(), 2); // 'c', not 3 (the newline gap)
}
#[test]
fn vi_normal_k_uses_prefix_search() {
// `j`/`k` in vi normal mode should use prefix search instead of plain
// history traversal
let mut rl = seam_engine(Box::<crate::Vi>::default());
let success_cond = "ls /tmp";
rl.history
.save(HistoryItem::from_command_line("ls -la"))
.unwrap();
rl.history
.save(HistoryItem::from_command_line(success_cond))
.unwrap();
rl.history
.save(HistoryItem::from_command_line("echo hi"))
.unwrap();
type_each(&mut rl, &[ch('l'), ch('s'), key(KeyCode::Esc)]);
drive(&mut rl, &[ch('k')]);
assert_eq!(rl.editor.get_buffer(), success_cond);
}
#[test]
fn vi_normal_k_off_end_uses_plain_walk() {
// The complement of the prefix case: once the caret leaves the buffer
// end (here `h` steps it onto 'l'), history nav falls back to plain
// bash-style traversal and returns the most recent entry overall, not a
// prefix match.
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.history
.save(HistoryItem::from_command_line("ls -la"))
.unwrap();
rl.history
.save(HistoryItem::from_command_line("ls /tmp"))
.unwrap();
rl.history
.save(HistoryItem::from_command_line("echo hi"))
.unwrap();
type_each(&mut rl, &[ch('l'), ch('s'), key(KeyCode::Esc)]);
drive(&mut rl, &[ch('h')]); // caret off the end, onto 'l'
drive(&mut rl, &[ch('k')]);
assert_eq!(rl.editor.get_buffer(), "echo hi");
}
#[test]
fn vi_hl_cross_newline_at_engine_seam() {
// `h`/`l` keys, driven through the vi parser, cross the line terminator
// under the default cross-line policy. Buffer "ab\ncd".
let mut rl = seam_engine(Box::<crate::Vi>::default());
rl.run_edit_commands(&[EditCommand::InsertString("ab\ncd".into())]);
drive(&mut rl, &[key(KeyCode::Esc)]); // vi normal
rl.run_edit_commands(&[EditCommand::MoveToLineStart { select: false }]);
assert_eq!(rl.editor.insertion_point(), 3); // 'c', start of line 2
drive(&mut rl, &[ch('h')]); // crosses up to 'b' (end of line 1)
assert_eq!(rl.editor.insertion_point(), 1);
drive(&mut rl, &[ch('l')]); // crosses down to 'c' (start of line 2)
assert_eq!(rl.editor.insertion_point(), 3);
}
}