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
|
/** \file reader.c
Functions for reading data from stdin and passing to the
parser. If stdin is a keyboard, it supplies a killring, history,
syntax highlighting, tab-completion and various other interactive features.
Internally the interactive mode functions rely in the functions of the
input library to read individual characters of input.
Token search is handled incrementally. Actual searches are only done
on when searching backwards, since the previous results are saved. The
last search position is remembered and a new search continues from the
last search position. All search results are saved in the list
'search_prev'. When the user searches forward, i.e. presses Alt-down,
the list is consulted for previous search result, and subsequent
backwards searches are also handled by consultiung the list up until
the end of the list is reached, at which point regular searching will
commence.
*/
#include "config.h"
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_TERMIOS_H
#include <sys/termios.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#include <time.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/poll.h>
#include <unistd.h>
#include <wctype.h>
#if HAVE_NCURSES_H
#include <ncurses.h>
#else
#include <curses.h>
#endif
#if HAVE_TERMIO_H
#include <termio.h>
#endif
#if HAVE_TERM_H
#include <term.h>
#elif HAVE_NCURSES_TERM_H
#include <ncurses/term.h>
#endif
#ifdef HAVE_SIGINFO_H
#include <siginfo.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <signal.h>
#include <fcntl.h>
#include <dirent.h>
#include <wchar.h>
#include <assert.h>
#include "fallback.h"
#include "util.h"
#include "wutil.h"
#include "highlight.h"
#include "reader.h"
#include "proc.h"
#include "parser.h"
#include "complete.h"
#include "history.h"
#include "common.h"
#include "sanity.h"
#include "env.h"
#include "exec.h"
#include "expand.h"
#include "tokenizer.h"
#include "kill.h"
#include "input_common.h"
#include "input.h"
#include "function.h"
#include "output.h"
#include "signal.h"
#include "screen.h"
#include "halloc.h"
#include "halloc_util.h"
#include "iothread.h"
#include "parse_util.h"
/**
Maximum length of prefix string when printing completion
list. Longer prefixes will be ellipsized.
*/
#define PREFIX_MAX_LEN 8
/**
A simple prompt for reading shell commands that does not rely on
fish specific commands, meaning it will work even if fish is not
installed. This is used by read_i.
*/
#define DEFAULT_PROMPT L"echo \"$USER@\"; hostname|cut -d . -f 1; echo \" \"; pwd; printf '> ';"
/**
The name of the function that prints the fish prompt
*/
#define PROMPT_FUNCTION_NAME L"fish_prompt"
/**
The default title for the reader. This is used by reader_readline.
*/
#define DEFAULT_TITLE L"echo $_ \" \"; pwd"
/**
The maximum number of characters to read from the keyboard without
repainting. Note that this readahead will only occur if new
characters are avaialble for reading, fish will never block for
more input without repainting.
*/
#define READAHEAD_MAX 256
/**
A mode for calling the reader_kill function. In this mode, the new
string is appended to the current contents of the kill buffer.
*/
#define KILL_APPEND 0
/**
A mode for calling the reader_kill function. In this mode, the new
string is prepended to the current contents of the kill buffer.
*/
#define KILL_PREPEND 1
/**
History search mode. This value means that no search is currently
performed.
*/
#define NO_SEARCH 0
/**
History search mode. This value means that we are perforing a line
history search.
*/
#define LINE_SEARCH 1
/**
History search mode. This value means that we are perforing a token
history search.
*/
#define TOKEN_SEARCH 2
/**
History search mode. This value means we are searching backwards.
*/
#define SEARCH_BACKWARD 0
/**
History search mode. This value means we are searching forwards.
*/
#define SEARCH_FORWARD 1
/**
A struct describing the state of the interactive reader. These
states can be stacked, in case reader_readline() calls are
nested. This happens when the 'read' builtin is used.
*/
class reader_data_t
{
public:
/**
Buffer containing the whole current commandline
*/
wchar_t *buff;
/**
The representation of the current screen contents
*/
screen_t screen;
/**
Buffer containing the current search item
*/
string_buffer_t search_buff;
/**
Saved position used by token history search
*/
int token_history_pos;
/**
Saved search string for token history search. Not handled by check_size.
*/
const wchar_t *token_history_buff;
/**
List for storing previous search results. Used to avoid duplicates.
*/
array_list_t search_prev;
/**
The current position in search_prev
*/
int search_pos;
/**
Current size of the buffers
*/
size_t buff_sz;
/**
Length of the command in buff. (Not the length of buff itself)
*/
size_t buff_len;
/**
The current position of the cursor in buff.
*/
size_t buff_pos;
/**
Name of the current application
*/
wcstring app_name;
/** The prompt command */
wcstring prompt;
/** The output of the last evaluation of the prompt command */
wcstring prompt_buff;
/**
Color is the syntax highlighting for buff. The format is that
color[i] is the classification (according to the enum in
highlight.h) of buff[i].
*/
int *color;
/**
An array defining the block level at each character.
*/
int *indent;
/**
Function for tab completion
*/
void (*complete_func)( const wchar_t *,
std::vector<completion_t>& );
/**
Function for syntax highlighting
*/
highlight_function_t highlight_function;
/**
Function for testing if the string can be returned
*/
int (*test_func)( wchar_t * );
/**
When this is true, the reader will exit
*/
int end_loop;
/**
If this is true, exit reader even if there are running
jobs. This happens if we press e.g. ^D twice.
*/
int prev_end_loop;
/**
The current contents of the top item in the kill ring.
*/
string_buffer_t kill_item;
/**
Pointer to previous reader_data
*/
reader_data_t *next;
/**
This variable keeps state on if we are in search mode, and
if yes, what mode
*/
int search_mode;
/**
Keep track of whether any internal code has done something
which is known to require a repaint.
*/
int repaint_needed;
};
/**
The current interactive reading context
*/
static reader_data_t *data=0;
/**
This flag is set to true when fish is interactively reading from
stdin. It changes how a ^C is handled by the fish interrupt
handler.
*/
static int is_interactive_read;
/**
Flag for ending non-interactive shell
*/
static int end_loop = 0;
/**
The list containing names of files that are being parsed
*/
static array_list_t current_filename;
/**
Store the pid of the parent process, so the exit function knows whether it should reset the terminal or not.
*/
static pid_t original_pid;
/**
This variable is set to true by the signal handler when ^C is pressed
*/
static int interrupted=0;
/*
Prototypes for a bunch of functions defined later on.
*/
/**
Stores the previous termios mode so we can reset the modes when
we execute programs and when the shell exits.
*/
static struct termios saved_modes;
static void reader_super_highlight_me_plenty( int pos, array_list_t *error );
/**
Variable to keep track of forced exits - see \c reader_exit_forced();
*/
static int exit_forced;
/**
Give up control of terminal
*/
static void term_donate()
{
set_color(FISH_COLOR_NORMAL, FISH_COLOR_NORMAL);
while( 1 )
{
if( tcsetattr(0,TCSANOW,&saved_modes) )
{
if( errno != EINTR )
{
debug( 1, _( L"Could not set terminal mode for new job" ) );
wperror( L"tcsetattr" );
break;
}
}
else
break;
}
}
/**
Grab control of terminal
*/
static void term_steal()
{
while( 1 )
{
if( tcsetattr(0,TCSANOW,&shell_modes) )
{
if( errno != EINTR )
{
debug( 1, _( L"Could not set terminal mode for shell" ) );
wperror( L"tcsetattr" );
break;
}
}
else
break;
}
common_handle_winch(0 );
}
int reader_exit_forced()
{
return exit_forced;
}
/**
Repaint the entire commandline. This means reset and clear the
commandline, write the prompt, perform syntax highlighting, write
the commandline and move the cursor.
*/
static void reader_repaint()
{
//PCA INSTANCED_PARSER what is this call for?
parser_t::principal_parser().test( data->buff, data->indent, 0, 0 );
s_write( &data->screen,
data->prompt_buff.c_str(),
data->buff,
data->color,
data->indent,
data->buff_pos );
data->repaint_needed = 0;
}
/**
Internal helper function for handling killing parts of text.
*/
static void reader_kill( wchar_t *begin, int length, int mode, int newv )
{
if( newv )
{
sb_clear( &data->kill_item );
sb_append_substring( &data->kill_item, begin, length );
kill_add( (wchar_t *)data->kill_item.buff );
}
else
{
wchar_t *old = wcsdup( (wchar_t *)data->kill_item.buff);
if( mode == KILL_APPEND )
{
sb_append_substring( &data->kill_item, begin, length );
}
else
{
sb_clear( &data->kill_item );
sb_append_substring( &data->kill_item, begin, length );
sb_append( &data->kill_item, old );
}
kill_replace( old, (wchar_t *)data->kill_item.buff );
free( old );
}
if( data->buff_pos > (size_t)(begin-data->buff) )
{
data->buff_pos = maxi( begin-data->buff, data->buff_pos-length );
}
data->buff_len -= length;
memmove( begin, begin+length, sizeof( wchar_t )*(wcslen( begin+length )+1) );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
void reader_handle_int( int sig )
{
//PCA INSTANCED_PARSER what is this?
block_t *c = NULL;//current_block;
if( !is_interactive_read )
{
while( c )
{
c->type=FAKE;
c->skip=1;
c=c->outer;
}
}
interrupted = 1;
}
wchar_t *reader_current_filename()
{
return al_get_count( ¤t_filename )?(wchar_t *)al_peek( ¤t_filename ):0;
}
void reader_push_current_filename( const wchar_t *fn )
{
al_push( ¤t_filename, fn );
}
wchar_t *reader_pop_current_filename()
{
return (wchar_t *)al_pop( ¤t_filename );
}
/**
Make sure buffers are large enough to hold current data plus one extra character.
*/
static int check_size()
{
if( data->buff_sz < data->buff_len + 2 )
{
data->buff_sz = maxi( 128, data->buff_len*2 );
data->buff = (wchar_t *)realloc( data->buff,
sizeof(wchar_t)*data->buff_sz);
data->color = (int *)realloc( data->color,
sizeof(int)*data->buff_sz);
data->indent = (int *)realloc( data->indent,
sizeof(int)*data->buff_sz);
if( data->buff==0 ||
data->color==0 ||
data->indent == 0 )
{
DIE_MEM();
}
}
return 1;
}
/**
Compare two completion entrys
*/
/*
static int completion_cmp( const void *a, const void *b )
{
completion_t *c= *((completion_t **)a);
completion_t *d= *((completion_t **)b);
return wcsfilecmp( c->completion, d->completion );
}
*/
/**
Sort an array_list_t containing compltion_t structs.
*/
/*
static void sort_completion_list( array_list_t *comp )
{
qsort( comp->arr,
al_get_count( comp ),
sizeof( void*),
&completion_cmp );
}
*/
static void sort_completion_list( std::vector<completion_t> &comp ) {
sort(comp.begin(), comp.end());
}
/**
Remove any duplicate completions in the list. This relies on the
list first beeing sorted.
*/
/*
static void remove_duplicates( array_list_t *l )
{
int in, out;
const wchar_t *prev;
completion_t *first;
if( al_get_count( l ) == 0 )
return;
first = (completion_t *)al_get( l, 0 );
prev = first->completion;
for( in=1, out=1; in < al_get_count( l ); in++ )
{
completion_t *curr = (completion_t *)al_get( l, in );
if( wcscmp( prev, curr->completion )!=0 )
{
al_set( l, out++, curr );
}
prev = curr->completion;
}
al_truncate( l, out );
}
*/
static void remove_duplicates(std::vector<completion_t> &l) {
l.erase(std::unique( l.begin(), l.end()), l.end());
}
int reader_interrupted()
{
int res=interrupted;
if( res )
interrupted=0;
return res;
}
void reader_write_title()
{
const wchar_t *title;
const env_var_t term_str = env_get_string( L"TERM" );
/*
This is a pretty lame heuristic for detecting terminals that do
not support setting the title. If we recognise the terminal name
as that of a virtual terminal, we assume it supports setting the
title. If we recognise it as that of a console, we assume it
does not support setting the title. Otherwise we check the
ttyname and see if we belive it is a virtual terminal.
One situation in which this breaks down is with screen, since
screen supports setting the terminal title if the underlying
terminal does so, but will print garbage on terminals that
don't. Since we can't see the underlying terminal below screen
there is no way to fix this.
*/
if ( term_str.missing() )
return;
const wchar_t *term = term_str.c_str();
bool recognized = false;
recognized = recognized || contains( term, L"xterm", L"screen", L"nxterm", L"rxvt" );
recognized = recognized || ! wcsncmp(term, L"xterm-", wcslen(L"xterm-"));
if( ! recognized )
{
char *n = ttyname( STDIN_FILENO );
if( contains( term, L"linux" ) )
{
return;
}
if( strstr( n, "tty" ) || strstr( n, "/vc/") )
return;
}
title = function_exists( L"fish_title" )?L"fish_title":DEFAULT_TITLE;
if( wcslen( title ) ==0 )
return;
wcstring_list_t lst;
proc_push_interactive(0);
if( exec_subshell2( title, lst ) != -1 )
{
size_t i;
if( lst.size() > 0 )
{
writestr( L"\x1b]2;" );
for( i=0; i<lst.size(); i++ )
{
writestr( lst.at(i).c_str() );
}
writestr( L"\7" );
}
}
proc_pop_interactive();
set_color( FISH_COLOR_RESET, FISH_COLOR_RESET );
}
/**
Reexecute the prompt command. The output is inserted into data->prompt_buff.
*/
static void exec_prompt()
{
size_t i;
wcstring_list_t prompt_list;
if( data->prompt.size() )
{
proc_push_interactive( 0 );
if( exec_subshell2( data->prompt.c_str(), prompt_list ) == -1 )
{
/* If executing the prompt fails, make sure we at least don't print any junk */
prompt_list.clear();
}
proc_pop_interactive();
}
reader_write_title();
data->prompt_buff.resize(0);
for( i = 0; i < prompt_list.size(); i++ )
{
if (i > 0) data->prompt_buff += L'\n';
data->prompt_buff += prompt_list.at(i);
}
}
void reader_init()
{
tcgetattr(0,&shell_modes); /* get the current terminal modes */
memcpy( &saved_modes,
&shell_modes,
sizeof(saved_modes)); /* save a copy so we can reset the terminal later */
shell_modes.c_lflag &= ~ICANON; /* turn off canonical mode */
shell_modes.c_lflag &= ~ECHO; /* turn off echo mode */
shell_modes.c_cc[VMIN]=1;
shell_modes.c_cc[VTIME]=0;
al_init( ¤t_filename);
}
void reader_destroy()
{
al_destroy( ¤t_filename);
tcsetattr(0, TCSANOW, &saved_modes);
}
void reader_exit( int do_exit, int forced )
{
if( data )
data->end_loop=do_exit;
end_loop=do_exit;
if( forced )
exit_forced = 1;
}
void reader_repaint_needed()
{
if( data )
{
data->repaint_needed = 1;
}
}
/**
Remove the previous character in the character buffer and on the
screen using syntax highlighting, etc.
*/
static void remove_backward()
{
if( data->buff_pos <= 0 )
return;
if( data->buff_pos < data->buff_len )
{
memmove( &data->buff[data->buff_pos-1],
&data->buff[data->buff_pos],
sizeof(wchar_t)*(data->buff_len-data->buff_pos+1) );
}
data->buff_pos--;
data->buff_len--;
data->buff[data->buff_len]=0;
reader_super_highlight_me_plenty( data->buff_pos,
0 );
reader_repaint();
}
/**
Insert the characters of the string into the command line buffer
and print them to the screen using syntax highlighting, etc.
*/
static int insert_str(const wchar_t *str)
{
int len = wcslen( str );
size_t old_len = data->buff_len;
assert( data->buff_pos >= 0 );
assert( data->buff_pos <= data->buff_len );
assert( len >= 0 );
data->buff_len += len;
check_size();
/* Insert space for extra characters at the right position */
if( data->buff_pos < old_len )
{
memmove( &data->buff[data->buff_pos+len],
&data->buff[data->buff_pos],
sizeof(wchar_t)*(old_len-data->buff_pos) );
}
memmove( &data->buff[data->buff_pos], str, sizeof(wchar_t)*len );
data->buff_pos += len;
data->buff[data->buff_len]='\0';
/*
Syntax highlight
*/
reader_super_highlight_me_plenty( data->buff_pos-1,
0 );
reader_repaint();
return 1;
}
/**
Insert the character into the command line buffer and print it to
the screen using syntax highlighting, etc.
*/
static int insert_char( int c )
{
wchar_t str[]=
{
0, 0
}
;
str[0] = c;
return insert_str( str );
}
/**
Calculate the length of the common prefix substring of two strings.
*/
static int comp_len( const wchar_t *a, const wchar_t *b )
{
int i;
for( i=0;
a[i] != '\0' && b[i] != '\0' && a[i]==b[i];
i++ )
;
return i;
}
/**
Calculate the case insensitive length of the common prefix substring of two strings.
*/
static int comp_ilen( const wchar_t *a, const wchar_t *b )
{
int i;
for( i=0;
a[i] != '\0' && b[i] != '\0' && towlower(a[i])==towlower(b[i]);
i++ )
;
return i;
}
/**
Find the outermost quoting style of current token. Returns 0 if
token is not quoted.
*/
static wchar_t get_quote( wchar_t *cmd, int len )
{
int i=0;
wchar_t res=0;
while( 1 )
{
if( !cmd[i] )
break;
if( cmd[i] == L'\\' )
{
i++;
if( !cmd[i] )
break;
i++;
}
else
{
if( cmd[i] == L'\'' || cmd[i] == L'\"' )
{
const wchar_t *end = quote_end( &cmd[i] );
//fwprintf( stderr, L"Jump %d\n", end-cmd );
if(( end == 0 ) || (!*end) || (end-cmd > len))
{
res = cmd[i];
break;
}
i = end-cmd+1;
}
else
i++;
}
}
return res;
}
/**
Calculates information on the parameter at the specified index.
\param cmd The command to be analyzed
\param pos An index in the string which is inside the parameter
\param quote If not 0, store the type of quote this parameter has, can be either ', " or \\0, meaning the string is not quoted.
\param offset If not 0, get_param will store a pointer to the beginning of the parameter.
\param string If not 0, get_parm will store a copy of the parameter string as returned by the tokenizer.
\param type If not 0, get_param will store the token type as returned by tok_last.
*/
static void get_param( wchar_t *cmd,
int pos,
wchar_t *quote,
wchar_t **offset,
wchar_t **string,
int *type )
{
int prev_pos=0;
wchar_t last_quote = '\0';
int unfinished;
tokenizer tok;
tok_init( &tok, cmd, TOK_ACCEPT_UNFINISHED );
for( ; tok_has_next( &tok ); tok_next( &tok ) )
{
if( tok_get_pos( &tok ) > pos )
break;
if( tok_last_type( &tok ) == TOK_STRING )
last_quote = get_quote( tok_last( &tok ),
pos - tok_get_pos( &tok ) );
if( type != 0 )
*type = tok_last_type( &tok );
if( string != 0 )
wcscpy( *string, tok_last( &tok ) );
prev_pos = tok_get_pos( &tok );
}
tok_destroy( &tok );
wchar_t c = cmd[pos];
cmd[pos]=0;
int cmdlen = wcslen( cmd );
unfinished = (cmdlen==0);
if( !unfinished )
{
unfinished = (quote != 0);
if( !unfinished )
{
if( wcschr( L" \t\n\r", cmd[cmdlen-1] ) != 0 )
{
if( ( cmdlen == 1) || (cmd[cmdlen-2] != L'\\') )
{
unfinished=1;
}
}
}
}
if( quote )
*quote = last_quote;
if( offset != 0 )
{
if( !unfinished )
{
while( (cmd[prev_pos] != 0) && (wcschr( L";|",cmd[prev_pos])!= 0) )
prev_pos++;
*offset = cmd + prev_pos;
}
else
{
*offset = cmd + pos;
}
}
cmd[pos]=c;
}
/**
Insert the string at the current cursor position. The function
checks if the string is quoted or not and correctly escapes the
string.
\param val the string to insert
\param flags A union of all flags describing the completion to insert. See the completion_t struct for more information on possible values.
*/
static void completion_insert( const wchar_t *val, int flags )
{
wchar_t *replaced;
wchar_t quote;
int add_space = !(flags & COMPLETE_NO_SPACE);
int do_replace = (flags & COMPLETE_NO_CASE);
int do_escape = !(flags & COMPLETE_DONT_ESCAPE);
// debug( 0, L"Insert completion %ls with flags %d", val, flags);
if( do_replace )
{
int tok_start, tok_len, move_cursor;
wchar_t *begin, *end;
string_buffer_t sb;
wchar_t *escaped;
parse_util_token_extent( data->buff, data->buff_pos, &begin, 0, 0, 0 );
end = data->buff+data->buff_pos;
tok_start = begin - data->buff;
tok_len = end-begin;
sb_init( &sb );
sb_append_substring( &sb, data->buff, begin - data->buff );
if( do_escape )
{
escaped = escape( val, ESCAPE_ALL | ESCAPE_NO_QUOTED );
sb_append( &sb, escaped );
move_cursor = wcslen(escaped);
free( escaped );
}
else
{
sb_append( &sb, val );
move_cursor = wcslen(val);
}
if( add_space )
{
sb_append( &sb, L" " );
move_cursor += 1;
}
sb_append( &sb, end );
reader_set_buffer( (wchar_t *)sb.buff, (begin-data->buff)+move_cursor );
sb_destroy( &sb );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
else
{
if( do_escape )
{
get_param( data->buff,
data->buff_pos,
"e,
0, 0, 0 );
if( quote == L'\0' )
{
replaced = escape( val, ESCAPE_ALL | ESCAPE_NO_QUOTED );
}
else
{
int unescapable=0;
const wchar_t *pin;
wchar_t *pout;
replaced = pout =
(wchar_t *)malloc( sizeof(wchar_t)*(wcslen(val) + 1) );
for( pin=val; *pin; pin++ )
{
switch( *pin )
{
case L'\n':
case L'\t':
case L'\b':
case L'\r':
unescapable=1;
break;
default:
*pout++ = *pin;
break;
}
}
if( unescapable )
{
free( replaced );
wchar_t *tmp = escape( val, ESCAPE_ALL | ESCAPE_NO_QUOTED );
replaced = wcsdupcat( L" ", tmp );
free( tmp);
replaced[0]=quote;
}
else
*pout = 0;
}
}
else
{
replaced = wcsdup(val);
}
if( insert_str( replaced ) )
{
/*
Print trailing space since this is the only completion
*/
if( add_space )
{
if( quote &&
(data->buff[data->buff_pos] != quote ) )
{
/*
This is a quoted parameter, first print a quote
*/
insert_char( quote );
}
insert_char( L' ' );
}
}
free(replaced);
}
}
/**
Run the fish_pager command to display the completion list. If the
fish_pager outputs any text, it is inserted into the input
backbuffer.
\param prefix the string to display before every completion.
\param is_quoted should be set if the argument is quoted. This will change the display style.
\param comp the list of completions to display
*/
static void run_pager( wchar_t *prefix, int is_quoted, const std::vector<completion_t> &comp )
{
int i;
string_buffer_t cmd;
string_buffer_t msg;
wchar_t * prefix_esc;
char *foo;
io_data_t *in;
wchar_t *escaped_separator;
int has_case_sensitive=0;
if( !prefix || (wcslen(prefix)==0))
{
prefix_esc = wcsdup(L"\"\"");
}
else
{
prefix_esc = escape( prefix,1);
}
sb_init( &cmd );
sb_init( &msg );
sb_printf( &cmd,
L"fish_pager -c 3 -r 4 %ls -p %ls",
// L"valgrind --track-fds=yes --log-file=pager.txt --leak-check=full ./fish_pager %d %ls",
is_quoted?L"-q":L"",
prefix_esc );
free( prefix_esc );
in= io_buffer_create( 1 );
in->fd = 3;
escaped_separator = escape( COMPLETE_SEP_STR, 1);
for( i=0; i< comp.size(); i++ )
{
const completion_t &el = comp.at( i );
has_case_sensitive |= !(el.flags & COMPLETE_NO_CASE );
}
for( i=0; i< comp.size(); i++ )
{
int base_len=-1;
const completion_t &el = comp.at( i );
wchar_t *foo=0;
wchar_t *baz=0;
if( has_case_sensitive && (el.flags & COMPLETE_NO_CASE ))
{
continue;
}
if( el.completion.empty() ){
continue;
}
if( el.flags & COMPLETE_NO_CASE )
{
if( base_len == -1 )
{
wchar_t *begin;
parse_util_token_extent( data->buff, data->buff_pos, &begin, 0, 0, 0 );
base_len = data->buff_pos - (begin-data->buff);
}
wcstring foo_wstr = escape_string( el.completion.c_str() + base_len, ESCAPE_ALL | ESCAPE_NO_QUOTED );
foo = wcsdup(foo_wstr.c_str());
}
else
{
wcstring foo_wstr = escape_string( el.completion, ESCAPE_ALL | ESCAPE_NO_QUOTED );
foo = wcsdup(foo_wstr.c_str());
}
if( !el.description.empty() )
{
wcstring baz_wstr = escape_string( el.description, 1 );
baz = wcsdup(baz_wstr.c_str());
}
if( !foo )
{
debug( 0, L"Run pager called with bad argument." );
bugreport();
show_stackframe();
}
else if( baz )
{
sb_printf( &msg, L"%ls%ls%ls\n",
foo,
escaped_separator,
baz );
}
else
{
sb_printf( &msg, L"%ls\n",
foo );
}
free( foo );
free( baz );
}
free( escaped_separator );
foo = wcs2str( (wchar_t *)msg.buff );
b_append( in->param2.out_buffer, foo, strlen(foo) );
free( foo );
term_donate();
io_data_t *out = io_buffer_create( 0 );
out->next = in;
out->fd = 4;
parser_t &parser = parser_t::principal_parser();
parser.eval( (wchar_t *)cmd.buff, out, TOP);
term_steal();
io_buffer_read( out );
sb_destroy( &cmd );
sb_destroy( &msg );
int nil=0;
b_append( out->param2.out_buffer, &nil, 1 );
wchar_t *tmp;
wchar_t *str = str2wcs((char *)out->param2.out_buffer->buff);
if( str )
{
for( tmp = str + wcslen(str)-1; tmp >= str; tmp-- )
{
input_unreadch( *tmp );
}
free( str );
}
io_buffer_destroy( out);
io_buffer_destroy( in);
}
/**
Flash the screen. This function only changed the color of the
current line, since the flash_screen sequnce is rather painful to
look at in most terminal emulators.
*/
static void reader_flash()
{
struct timespec pollint;
for( size_t i=0; i<data->buff_pos; i++ )
{
data->color[i] = HIGHLIGHT_SEARCH_MATCH<<16;
}
reader_repaint();
pollint.tv_sec = 0;
pollint.tv_nsec = 100 * 1000000;
nanosleep( &pollint, NULL );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
/**
Characters that may not be part of a token that is to be replaced
by a case insensitive completion.
*/
#define REPLACE_UNCLEAN L"$*?({})"
/**
Check if the specified string can be replaced by a case insensitive
complition with the specified flags.
Advanced tokens like those containing {}-style expansion can not at
the moment be replaced, other than if the new token is already an
exact replacement, e.g. if the COMPLETE_DONT_ESCAPE flag is set.
*/
int reader_can_replace( const wchar_t *in, int flags )
{
const wchar_t * str = in;
if( flags & COMPLETE_DONT_ESCAPE )
{
return 1;
}
CHECK( in, 1 );
/*
Test characters that have a special meaning in any character position
*/
while( *str )
{
if( wcschr( REPLACE_UNCLEAN, *str ) )
return 0;
str++;
}
return 1;
}
/**
Handle the list of completions. This means the following:
- If the list is empty, flash the terminal.
- If the list contains one element, write the whole element, and if
the element does not end on a '/', '@', ':', or a '=', also write a trailing
space.
- If the list contains multiple elements with a common prefix, write
the prefix.
- If the list contains multiple elements without.
a common prefix, call run_pager to display a list of completions. Depending on terminal size and the length of the list, run_pager may either show less than a screenfull and exit or use an interactive pager to allow the user to scroll through the completions.
\param comp the list of completion strings
*/
static int handle_completions( std::vector<completion_t> &comp )
{
int i;
void *context = 0;
wchar_t *base = 0;
int len = 0;
int done = 0;
int count = 0;
int flags=0;
wchar_t *begin, *end;
wchar_t *tok;
parse_util_token_extent( data->buff, data->buff_pos, &begin, 0, 0, 0 );
end = data->buff+data->buff_pos;
context = halloc( 0, 0 );
tok = halloc_wcsndup( context, begin, end-begin );
/*
Check trivial cases
*/
switch( comp.size() )
{
/*
No suitable completions found, flash screen and retur
*/
case 0:
{
reader_flash();
done = 1;
break;
}
/*
Exactly one suitable completion found - insert it
*/
case 1:
{
const completion_t &c = comp.at( 0 );
/*
If this is a replacement completion, check
that we know how to replace it, e.g. that
the token doesn't contain evil operators
like {}
*/
if( !(c.flags & COMPLETE_NO_CASE) || reader_can_replace( tok, c.flags ) )
{
completion_insert( c.completion.c_str(),
c.flags );
}
done = 1;
len = 1;
break;
}
}
if( !done )
{
/*
Try to find something to insert whith the correct case
*/
for( i=0; i< comp.size() ; i++ )
{
const completion_t &c = comp.at( i );
int new_len;
/*
Ignore case insensitive completions for now
*/
if( c.flags & COMPLETE_NO_CASE )
continue;
count++;
if( base )
{
new_len = comp_len( base, c.completion.c_str() );
len = new_len < len ? new_len: len;
}
else
{
base = wcsdup( c.completion.c_str() );
len = wcslen( base );
flags = c.flags;
}
}
/*
If we found something to insert, do it.
*/
if( len > 0 )
{
if( count > 1 )
flags = flags | COMPLETE_NO_SPACE;
base[len]=L'\0';
completion_insert(base, flags);
done = 1;
}
}
if( !done && base == 0 )
{
/*
Try to find something to insert ignoring case
*/
if( begin )
{
int offset = wcslen( tok );
count = 0;
for( i=0; i< comp.size(); i++ )
{
const completion_t &c = comp.at( i );
int new_len;
if( !(c.flags & COMPLETE_NO_CASE) )
continue;
if( !reader_can_replace( tok, c.flags ) )
{
len=0;
break;
}
count++;
if( base )
{
new_len = offset + comp_ilen( base+offset, c.completion.c_str()+offset );
len = new_len < len ? new_len: len;
}
else
{
base = wcsdup( c.completion.c_str() );
len = wcslen( base );
flags = c.flags;
}
}
if( len > offset )
{
if( count > 1 )
flags = flags | COMPLETE_NO_SPACE;
base[len]=L'\0';
completion_insert( base, flags );
done = 1;
}
}
}
free( base );
if( !done )
{
/*
There is no common prefix in the completions, and show_list
is true, so we print the list
*/
int len;
wchar_t * prefix;
wchar_t * prefix_start;
get_param( data->buff,
data->buff_pos,
0,
&prefix_start,
0,
0 );
len = &data->buff[data->buff_pos]-prefix_start+1;
if( len <= PREFIX_MAX_LEN )
{
prefix = (wchar_t *)malloc( sizeof(wchar_t)*(len+1) );
wcslcpy( prefix, prefix_start, len );
prefix[len]=L'\0';
}
else
{
wchar_t tmp[2]=
{
ellipsis_char,
0
}
;
prefix = wcsdupcat( tmp,
prefix_start + (len - PREFIX_MAX_LEN) );
prefix[PREFIX_MAX_LEN] = 0;
}
{
int is_quoted;
wchar_t quote;
get_param( data->buff, data->buff_pos, "e, 0, 0, 0 );
is_quoted = (quote != L'\0');
write_loop(1, "\n", 1 );
run_pager( prefix, is_quoted, comp );
}
free( prefix );
s_reset( &data->screen, 1 );
reader_repaint();
}
halloc_free( context );
return len;
}
/**
Initialize data for interactive use
*/
static void reader_interactive_init()
{
/* See if we are running interactively. */
pid_t shell_pgid;
input_init();
kill_init();
shell_pgid = getpgrp ();
/*
This should enable job control on fish, even if our parent process did
not enable it for us.
*/
/*
Check if we are in control of the terminal, so that we don't do
semi-expensive things like reset signal handlers unless we
really have to, which we often don't.
*/
if (tcgetpgrp( 0 ) != shell_pgid)
{
int block_count = 0;
int i;
/*
Bummer, we are not in control of the terminal. Stop until
parent has given us control of it. Stopping in fish is a bit
of a challange, what with all the signal fidgeting, we need
to reset a bunch of signal state, making this coda a but
unobvious.
In theory, reseting signal handlers could cause us to miss
signal deliveries. In practice, this code should only be run
suring startup, when we're not waiting for any signals.
*/
while (signal_is_blocked())
{
signal_unblock();
block_count++;
}
signal_reset_handlers();
/*
Ok, signal handlers are taken out of the picture. Stop ourself in a loop
until we are in control of the terminal.
*/
while (tcgetpgrp( 0 ) != shell_pgid)
{
killpg( shell_pgid, SIGTTIN);
}
signal_set_handlers();
for( i=0; i<block_count; i++ )
{
signal_block();
}
}
/* Put ourselves in our own process group. */
shell_pgid = getpid ();
if( getpgrp() != shell_pgid )
{
if (setpgid (shell_pgid, shell_pgid) < 0)
{
debug( 1,
_( L"Couldn't put the shell in its own process group" ));
wperror( L"setpgid" );
exit (1);
}
}
/* Grab control of the terminal. */
if( tcsetpgrp (STDIN_FILENO, shell_pgid) )
{
debug( 1,
_( L"Couldn't grab control of terminal" ) );
wperror( L"tcsetpgrp" );
exit(1);
}
common_handle_winch(0);
if( tcsetattr(0,TCSANOW,&shell_modes)) /* set the new modes */
{
wperror(L"tcsetattr");
}
/*
We need to know our own pid so we'll later know if we are a
fork
*/
original_pid = getpid();
env_set( L"_", L"fish", ENV_GLOBAL );
}
/**
Destroy data for interactive use
*/
static void reader_interactive_destroy()
{
kill_destroy();
writestr( L"\n" );
set_color( FISH_COLOR_RESET, FISH_COLOR_RESET );
input_destroy();
}
void reader_sanity_check()
{
if( is_interactive)
{
if( !data )
sanity_lose();
if(!( data->buff_pos <= data->buff_len ))
sanity_lose();
if(!( data->buff_len == wcslen( data->buff ) ))
sanity_lose();
}
}
void reader_replace_current_token( wchar_t *new_token )
{
wchar_t *begin, *end;
string_buffer_t sb;
int new_pos;
/*
Find current token
*/
parse_util_token_extent( data->buff, data->buff_pos, &begin, &end, 0, 0 );
if( !begin || !end )
return;
/*
Make new string
*/
sb_init( &sb );
sb_append_substring( &sb, data->buff, begin-data->buff );
sb_append( &sb, new_token );
sb_append( &sb, end );
new_pos = (begin-data->buff) + wcslen(new_token);
reader_set_buffer( (wchar_t *)sb.buff, new_pos );
sb_destroy( &sb );
}
/**
Set the specified string from the history as the current buffer. Do
not modify prefix_width.
*/
static void handle_history( const wchar_t *new_str )
{
if( new_str )
{
data->buff_len = wcslen( new_str );
check_size();
wcscpy( data->buff, new_str );
data->buff_pos=wcslen(data->buff);
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
}
/**
Check if the specified string is contained in the list, using
wcscmp as a comparison function
*/
static int contains_al( const wchar_t *needle,
array_list_t *haystack )
{
int i;
for( i=0; i<al_get_count( haystack ); i++ )
{
if( !wcscmp( needle, (const wchar_t *)al_get( haystack, i ) ) )
return 1;
}
return 0;
}
/**
Reset the data structures associated with the token search
*/
static void reset_token_history()
{
wchar_t *begin, *end;
parse_util_token_extent( data->buff, data->buff_pos, &begin, &end, 0, 0 );
sb_clear( &data->search_buff );
if( begin )
{
sb_append_substring( &data->search_buff, begin, end-begin);
}
data->token_history_pos = -1;
data->search_pos=0;
al_foreach( &data->search_prev, &free );
al_truncate( &data->search_prev, 0 );
al_push( &data->search_prev, wcsdup( (wchar_t *)data->search_buff.buff ) );
}
/**
Handles a token search command.
\param forward if the search should be forward or reverse
\param reset whether the current token should be made the new search token
*/
static void handle_token_history( int forward, int reset )
{
wchar_t *str=0;
int current_pos;
tokenizer tok;
if( reset )
{
/*
Start a new token search using the current token
*/
reset_token_history();
}
current_pos = data->token_history_pos;
if( forward || data->search_pos < (al_get_count( &data->search_prev )-1) )
{
if( forward )
{
if( data->search_pos > 0 )
{
data->search_pos--;
}
str = (wchar_t *)al_get( &data->search_prev, data->search_pos );
}
else
{
data->search_pos++;
str = (wchar_t *)al_get( &data->search_prev, data->search_pos );
}
reader_replace_current_token( str );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
else
{
if( current_pos == -1 )
{
const wchar_t *item;
/*
Move to previous line
*/
free( (void *)data->token_history_buff );
/*
Search for previous item that contains this substring
*/
item = history_prev_match( (wchar_t *)data->search_buff.buff);
/*
If there is no match, the original string is returned
If so, we clear the match string to avoid infinite loop
*/
if( wcscmp( item, (wchar_t *)data->search_buff.buff ) == 0 )
{
item=L"";
}
data->token_history_buff = wcsdup( item );
current_pos = wcslen(data->token_history_buff);
}
if( ! wcslen( data->token_history_buff ) )
{
/*
We have reached the end of the history - check if the
history already contains the search string itself, if so
return, otherwise add it.
*/
const wchar_t *last = (const wchar_t *)al_get( &data->search_prev, al_get_count( &data->search_prev ) -1 );
if( wcscmp( last, (wchar_t *)data->search_buff.buff ) )
{
str = wcsdup( (wchar_t *)data->search_buff.buff );
}
else
{
return;
}
}
else
{
//debug( 3, L"new '%ls'", data->token_history_buff );
for( tok_init( &tok, data->token_history_buff, TOK_ACCEPT_UNFINISHED );
tok_has_next( &tok);
tok_next( &tok ))
{
switch( tok_last_type( &tok ) )
{
case TOK_STRING:
{
if( wcsstr( tok_last( &tok ), (wchar_t *)data->search_buff.buff ) )
{
//debug( 3, L"Found token at pos %d\n", tok_get_pos( &tok ) );
if( tok_get_pos( &tok ) >= current_pos )
{
break;
}
//debug( 3, L"ok pos" );
if( !contains_al( tok_last( &tok ), &data->search_prev ) )
{
free(str);
data->token_history_pos = tok_get_pos( &tok );
str = wcsdup(tok_last( &tok ));
}
}
}
}
}
tok_destroy( &tok );
}
if( str )
{
reader_replace_current_token( str );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
al_push( &data->search_prev, str );
data->search_pos = al_get_count( &data->search_prev )-1;
}
else if( ! reader_interrupted() )
{
data->token_history_pos=-1;
handle_token_history( 0, 0 );
}
}
}
/**
Move buffer position one word or erase one word. This function
updates both the internal buffer and the screen. It is used by
M-left, M-right and ^W to do block movement or block erase.
\param dir Direction to move/erase. 0 means move left, 1 means move right.
\param erase Whether to erase the characters along the way or only move past them.
\param new if the new kill item should be appended to the previous kill item or not.
*/
static void move_word( int dir, int erase, int newv )
{
size_t end_buff_pos=data->buff_pos;
int step = dir?1:-1;
/*
Return if we are already at the edge
*/
if( !dir && data->buff_pos == 0 )
{
return;
}
if( dir && data->buff_pos == data->buff_len )
{
return;
}
/*
If we are beyond the last character and moving left, start by
moving one step, since otehrwise we'll start on the \0, which
should be ignored.
*/
if( !dir && (end_buff_pos == data->buff_len) )
{
if( !end_buff_pos )
return;
end_buff_pos--;
}
/*
When moving left, ignore the character under the cursor
*/
if( !dir )
{
end_buff_pos+=2*step;
}
/*
Remove all whitespace characters before finding a word
*/
while( 1 )
{
wchar_t c;
if( !dir )
{
if( end_buff_pos <= 0 )
break;
}
else
{
if( end_buff_pos >= data->buff_len )
break;
}
/*
Always eat at least one character
*/
if( end_buff_pos != data->buff_pos )
{
c = data->buff[end_buff_pos];
if( !iswspace( c ) )
{
break;
}
}
end_buff_pos+=step;
}
/*
Remove until we find a character that is not alphanumeric
*/
while( 1 )
{
wchar_t c;
if( !dir )
{
if( end_buff_pos <= 0 )
break;
}
else
{
if( end_buff_pos >= data->buff_len )
break;
}
c = data->buff[end_buff_pos];
if( !iswalnum( c ) )
{
/*
Don't gobble the boundary character when moving to the
right
*/
if( !dir )
end_buff_pos -= step;
break;
}
end_buff_pos+=step;
}
/*
Make sure we move at least one character
*/
if( end_buff_pos==data->buff_pos )
{
end_buff_pos+=step;
}
/*
Make sure we don't move beyond begining or end of buffer
*/
end_buff_pos = maxi( 0, mini( end_buff_pos, data->buff_len ) );
if( erase )
{
int remove_count = abs(data->buff_pos - end_buff_pos);
int first_char = mini( data->buff_pos, end_buff_pos );
// fwprintf( stderr, L"Remove from %d to %d\n", first_char, first_char+remove_count );
reader_kill( data->buff + first_char, remove_count, dir?KILL_APPEND:KILL_PREPEND, newv );
}
else
{
data->buff_pos = end_buff_pos;
reader_repaint();
}
}
wchar_t *reader_get_buffer(void)
{
ASSERT_IS_MAIN_THREAD();
return data?data->buff:NULL;
}
void reader_set_buffer( const wchar_t *b, int p )
{
int l = wcslen( b );
if( !data )
return;
data->buff_len = l;
check_size();
if( data->buff != b )
wcscpy( data->buff, b );
if( p>=0 )
{
data->buff_pos=mini( p, l );
}
else
{
data->buff_pos=l;
}
data->search_mode = NO_SEARCH;
sb_clear( &data->search_buff );
history_reset();
reader_super_highlight_me_plenty( data->buff_pos,
0 );
reader_repaint_needed();
}
int reader_get_cursor_pos()
{
if( !data )
return -1;
return data->buff_pos;
}
#define ENV_CMD_DURATION L"CMD_DURATION"
void set_env_cmd_duration(struct timeval *after, struct timeval *before)
{
time_t secs = after->tv_sec - before->tv_sec;
suseconds_t usecs = after->tv_usec - before->tv_usec;
wchar_t buf[16];
if (after->tv_usec < before->tv_usec) {
usecs += 1000000;
secs -= 1;
}
if (secs < 1) {
env_remove( ENV_CMD_DURATION, 0 );
} else {
if (secs < 10) { // 10 secs
swprintf(buf, 16, L"%lu.%02us", secs, usecs / 10000);
} else if (secs < 60) { // 1 min
swprintf(buf, 16, L"%lu.%01us", secs, usecs / 100000);
} else if (secs < 600) { // 10 mins
swprintf(buf, 16, L"%lum %lu.%01us", secs / 60, secs % 60, usecs / 100000);
} else if (secs < 5400) { // 1.5 hours
swprintf(buf, 16, L"%lum %lus", secs / 60, secs % 60);
} else {
swprintf(buf, 16, L"%.1fh", secs / 3600.0f);
}
env_set( ENV_CMD_DURATION, buf, ENV_EXPORT );
}
}
void reader_run_command( parser_t &parser, const wchar_t *cmd )
{
wchar_t *ft;
struct timeval time_before, time_after;
ft= tok_first( cmd );
if( ft != 0 )
env_set( L"_", ft, ENV_GLOBAL );
free(ft);
reader_write_title();
term_donate();
gettimeofday(&time_before, NULL);
parser.eval( cmd, 0, TOP );
job_reap( 1 );
gettimeofday(&time_after, NULL);
set_env_cmd_duration(&time_after, &time_before);
term_steal();
env_set( L"_", program_name, ENV_GLOBAL );
#ifdef HAVE__PROC_SELF_STAT
proc_update_jiffies();
#endif
}
int reader_shell_test( wchar_t *b )
{
int res = parser_t::principal_parser().test( b, 0, 0, 0 );
if( res & PARSER_TEST_ERROR )
{
string_buffer_t sb;
sb_init( &sb );
int tmp[1];
int tmp2[1];
s_write( &data->screen, L"", L"", tmp, tmp2, 0 );
parser_t::principal_parser().test( b, 0, &sb, L"fish" );
fwprintf( stderr, L"%ls", sb.buff );
sb_destroy( &sb );
}
return res;
}
/**
Test if the given string contains error. Since this is the error
detection for general purpose, there are no invalid strings, so
this function always returns false.
*/
static int default_test( wchar_t *b )
{
return 0;
}
void reader_push( const wchar_t *name )
{
// use placement new to guarantee zero initialization :(
void *buff = calloc(1, sizeof(reader_data_t));
if( !buff )
{
DIE_MEM();
}
reader_data_t *n = new(buff) reader_data_t;
n->app_name = name;
n->next = data;
sb_init( &n->kill_item );
data=n;
check_size();
data->buff[0]=0;
sb_init( &data->search_buff );
if( data->next == 0 )
{
reader_interactive_init();
}
exec_prompt();
reader_set_highlight_function( &highlight_universal );
reader_set_test_function( &default_test );
reader_set_prompt( L"" );
history_set_mode( name );
al_init( &data->search_prev );
data->token_history_buff=0;
}
void reader_pop()
{
reader_data_t *n = data;
if( data == 0 )
{
debug( 0, _( L"Pop null reader block" ) );
sanity_lose();
return;
}
data=data->next;
free( n->buff );
free( n->color );
free( n->indent );
sb_destroy( &n->search_buff );
sb_destroy( &n->kill_item );
/*
Clean up after history search
*/
al_foreach( &n->search_prev, &free );
al_destroy( &n->search_prev );
free( (void *)n->token_history_buff);
/* Invoke the destructor to balance our placement new */
n->~reader_data_t();
free(n);
if( data == 0 )
{
reader_interactive_destroy();
}
else
{
end_loop = 0;
history_set_mode( data->app_name.c_str() );
s_reset( &data->screen, 1 );
}
}
void reader_set_prompt( const wchar_t *new_prompt )
{
data->prompt = new_prompt;
}
void reader_set_complete_function( void (*f)( const wchar_t *,
std::vector<completion_t>& ) )
{
data->complete_func = f;
}
void reader_set_highlight_function( highlight_function_t func )
{
data->highlight_function = func;
}
void reader_set_test_function( int (*f)( wchar_t * ) )
{
data->test_func = f;
}
/** A class as the context pointer for a background (threaded) highlight operation. */
class background_highlight_context {
public:
/**
The string to highlight
*/
wcstring buff;
/**
Malloc'd color buffer (same size as buff)
*/
int *color;
/**
The position to use for bracket matching
*/
int match_highlight_pos;
/**
Function for syntax highlighting
*/
highlight_function_t highlight_function;
/**
Environment variables
*/
env_vars vars;
/**
When the request was made
*/
double when;
background_highlight_context() : vars(env_vars::highlighting_keys)
{
}
~background_highlight_context()
{
free(color);
}
};
static void highlight_complete2( wchar_t *command, const int *colors, int position, void *ctx_ptr ) {
background_highlight_context *ctx = (background_highlight_context *)ctx_ptr;
if (ctx->buff == data->buff) {
/* The data hasn't changed, so swap in our colors */
free(data->color);
data->color = ctx->color;
ctx->color = NULL;
data->repaint_needed = 1;
}
/* Free our context */
delete ctx;
}
static void highlight_complete(void *ctx_ptr, int result) {
background_highlight_context *ctx = (background_highlight_context *)ctx_ptr;
if (ctx->buff == data->buff) {
/* The data hasn't changed, so swap in our colors */
free(data->color);
data->color = ctx->color;
ctx->color = NULL;
//data->repaint_needed = 1;
//s_reset( &data->screen, 1 );
reader_repaint();
}
/* Free our context */
delete ctx;
}
static int threaded_highlight(void *ctx_ptr) {
background_highlight_context *ctx = (background_highlight_context *)ctx_ptr;
array_list_t *error = 0;
const wchar_t *delayer = ctx->vars.get(L"HIGHLIGHT_DELAY");
double secDelay = 0;
if (delayer) {
wcstring tmp = delayer;
secDelay = from_string<double>(tmp);
}
if (secDelay > 0) usleep((useconds_t)(secDelay * 1E6));
//write(0, "Start", 5);
ctx->highlight_function( ctx->buff.c_str(), ctx->color, ctx->match_highlight_pos, error, ctx->vars );
//write(0, "End", 3);
return 0;
}
/**
Call specified external highlighting function and then do search
highlighting. Lastly, clear the background color under the cursor
to avoid repaint issues on terminals where e.g. syntax highligthing
maykes characters under the sursor unreadable.
\param match_highlight_pos the position to use for bracket matching. This need not be the same as the surrent cursor position
\param error if non-null, any possible errors in the buffer are further descibed by the strings inserted into the specified arraylist
*/
static void reader_super_highlight_me_plenty( int match_highlight_pos, array_list_t *error )
{
/* Ensure we don't repaint with stale data */
size_t i;
for (i=0; i < data->buff_sz; i++) {
data->color[i] = HIGHLIGHT_NORMAL;
}
background_highlight_context *ctx = new background_highlight_context;
ctx->buff = data->buff;
ctx->color = (int *)calloc(data->buff_sz, sizeof *ctx->color);
ctx->match_highlight_pos = match_highlight_pos;
ctx->highlight_function = data->highlight_function;
ctx->when = timef();
#if 1
iothread_perform(threaded_highlight, highlight_complete, ctx);
#else
data->highlight_function( ctx->buff, ctx->color, match_highlight_pos, error, highlight_complete2, ctx );
#endif
if( wcslen((wchar_t *)data->search_buff.buff) )
{
wchar_t * match = wcsstr( data->buff, (wchar_t *)data->search_buff.buff );
if( match )
{
int start = match-data->buff;
int count = wcslen( (wchar_t *)data->search_buff.buff );
int i;
for( i=0; i<count; i++ )
{
data->color[start+i] |= HIGHLIGHT_SEARCH_MATCH<<16;
}
}
}
}
int exit_status()
{
if( is_interactive )
return job_list().empty() && data->end_loop;
else
return end_loop;
}
/**
This function is called when the main loop notices that end_loop
has been set while in interactive mode. It checks if it is ok to
exit.
*/
static void handle_end_loop()
{
job_t *j;
int job_count=0;
int is_breakpoint=0;
block_t *b;
parser_t &parser = parser_t::principal_parser();
for( b = parser.current_block;
b;
b = b->outer )
{
if( b->type == BREAKPOINT )
{
is_breakpoint = 1;
break;
}
}
job_iterator_t jobs;
while ((j = jobs.next()))
{
if( !job_is_completed(j) )
{
job_count++;
break;
}
}
if( !reader_exit_forced() && !data->prev_end_loop && job_count && !is_breakpoint )
{
writestr(_( L"There are stopped jobs. A second attempt to exit will enforce their termination.\n" ));
reader_exit( 0, 0 );
data->prev_end_loop=1;
}
else
{
if( !isatty(0) )
{
/*
We already know that stdin is a tty since we're
in interactive mode. If isatty returns false, it
means stdin must have been closed.
*/
job_iterator_t jobs;
while ((j = jobs.next()))
{
if( ! job_is_completed( j ) )
{
job_signal( j, SIGHUP );
}
}
}
}
}
/**
Read interactively. Read input from stdin while providing editing
facilities.
*/
static int read_i()
{
event_fire_generic(L"fish_prompt");
reader_push(L"fish");
reader_set_complete_function( &complete2 );
reader_set_highlight_function( &highlight_shell );
reader_set_test_function( &reader_shell_test );
parser_t &parser = parser_t::principal_parser();
data->prev_end_loop=0;
while( (!data->end_loop) && (!sanity_check()) )
{
wchar_t *tmp;
if( function_exists( PROMPT_FUNCTION_NAME ) )
reader_set_prompt( PROMPT_FUNCTION_NAME );
else
reader_set_prompt( DEFAULT_PROMPT );
/*
Put buff in temporary string and clear buff, so
that we can handle a call to reader_set_buffer
during evaluation.
*/
tmp = reader_readline();
if( data->end_loop)
{
handle_end_loop();
}
else if( tmp )
{
tmp = wcsdup( tmp );
data->buff_pos=data->buff_len=0;
data->buff[data->buff_len]=L'\0';
reader_run_command( parser, tmp );
free( tmp );
if( data->end_loop)
{
handle_end_loop();
}
else
{
data->prev_end_loop=0;
}
}
}
reader_pop();
return 0;
}
/**
Test if there are bytes available for reading on the specified file
descriptor
*/
static int can_read( int fd )
{
struct timeval can_read_timeout = { 0, 0 };
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
return select(fd + 1, &fds, 0, 0, &can_read_timeout) == 1;
}
/**
Test if the specified character is in the private use area that
fish uses to store internal characters
*/
static int wchar_private( wchar_t c )
{
return ( (c >= 0xe000) && (c <= 0xf8ff ) );
}
/**
Test if the specified character in the specified string is
backslashed.
*/
static int is_backslashed( const wchar_t *str, int pos )
{
int count = 0;
int i;
for( i=pos-1; i>=0; i-- )
{
if( str[i] != L'\\' )
break;
count++;
}
return count %2;
}
wchar_t *reader_readline()
{
wint_t c;
int i;
int last_char=0, yank=0;
const wchar_t *yank_str;
std::vector<completion_t> comp;
int comp_empty=1;
int finished=0;
struct termios old_modes;
check_size();
sb_clear( &data->search_buff );
data->buff[data->buff_len]='\0';
data->search_mode = NO_SEARCH;
exec_prompt();
reader_super_highlight_me_plenty( data->buff_pos, 0 );
s_reset( &data->screen, 1 );
reader_repaint();
/*
get the current terminal modes. These will be restored when the
function returns.
*/
tcgetattr(0,&old_modes);
/* set the new modes */
if( tcsetattr(0,TCSANOW,&shell_modes))
{
wperror(L"tcsetattr");
}
while( !finished && !data->end_loop)
{
int regular_char = 0;
/*
Sometimes strange input sequences seem to generate a zero
byte. I believe these simply mean a character was pressed
but it should be ignored. (Example: Trying to add a tilde
(~) to digit)
*/
while( 1 )
{
int was_interactive_read = is_interactive_read;
is_interactive_read = 1;
c=input_readch();
is_interactive_read = was_interactive_read;
if( ( (!wchar_private(c))) && (c>31) && (c != 127) )
{
if( can_read(0) )
{
wchar_t arr[READAHEAD_MAX+1];
int i;
memset( arr, 0, sizeof( arr ) );
arr[0] = c;
for( i=1; i<READAHEAD_MAX; i++ )
{
if( !can_read( 0 ) )
{
c = 0;
break;
}
c = input_readch();
if( (!wchar_private(c)) && (c>31) && (c != 127) )
{
arr[i]=c;
c=0;
}
else
break;
}
insert_str( arr );
}
}
if( c != 0 )
break;
}
/*
if( (last_char == R_COMPLETE) && (c != R_COMPLETE) && (!comp_empty) )
{
halloc_destroy( comp );
comp = 0;
}
*/
if( last_char != R_YANK && last_char != R_YANK_POP )
yank=0;
switch( c )
{
/* go to beginning of line*/
case R_BEGINNING_OF_LINE:
{
while( ( data->buff_pos>0 ) &&
( data->buff[data->buff_pos-1] != L'\n' ) )
{
data->buff_pos--;
}
reader_repaint();
break;
}
case R_END_OF_LINE:
{
while( data->buff[data->buff_pos] &&
data->buff[data->buff_pos] != L'\n' )
{
data->buff_pos++;
}
reader_repaint();
break;
}
case R_BEGINNING_OF_BUFFER:
{
data->buff_pos = 0;
reader_repaint();
break;
}
/* go to EOL*/
case R_END_OF_BUFFER:
{
data->buff_pos = data->buff_len;
reader_repaint();
break;
}
case R_NULL:
{
if( data->repaint_needed )
reader_repaint();
break;
}
case R_REPAINT:
{
exec_prompt();
write_loop( 1, "\r", 1 );
s_reset( &data->screen, 0 );
reader_repaint();
break;
}
case R_EOF:
{
exit_forced = 1;
data->end_loop=1;
break;
}
/* complete */
case R_COMPLETE:
{
if( !data->complete_func )
break;
if( comp_empty || last_char != R_COMPLETE)
{
wchar_t *begin, *end;
wchar_t *token_begin, *token_end;
wchar_t *buffcpy;
int len;
int cursor_steps;
parse_util_cmdsubst_extent( data->buff, data->buff_pos, &begin, &end );
parse_util_token_extent( begin, data->buff_pos - (begin-data->buff), &token_begin, &token_end, 0, 0 );
cursor_steps = token_end - data->buff- data->buff_pos;
data->buff_pos += cursor_steps;
if( is_backslashed( data->buff, data->buff_pos ) )
{
remove_backward();
}
reader_repaint();
len = data->buff_pos - (begin-data->buff);
buffcpy = wcsndup( begin, len );
// comp = al_halloc( 0 );
data->complete_func( buffcpy, comp );
sort_completion_list( comp );
remove_duplicates( comp );
free( buffcpy );
comp_empty = handle_completions( comp );
comp.clear();
// halloc_free( comp );
// comp = 0;
}
break;
}
/* kill */
case R_KILL_LINE:
{
wchar_t *begin = &data->buff[data->buff_pos];
wchar_t *end = begin;
int len;
while( *end && *end != L'\n' )
end++;
if( end==begin && *end )
end++;
len = end-begin;
if( len )
{
reader_kill( begin, len, KILL_APPEND, last_char!=R_KILL_LINE );
}
break;
}
case R_BACKWARD_KILL_LINE:
{
if( data->buff_pos > 0 )
{
wchar_t *end = &data->buff[data->buff_pos];
wchar_t *begin = end;
int len;
while( begin > data->buff && *begin != L'\n' )
begin--;
if( *begin == L'\n' )
begin++;
len = maxi( end-begin, 1 );
begin = end - len;
reader_kill( begin, len, KILL_PREPEND, last_char!=R_BACKWARD_KILL_LINE );
}
break;
}
case R_KILL_WHOLE_LINE:
{
wchar_t *end = &data->buff[data->buff_pos];
wchar_t *begin = end;
int len;
while( begin > data->buff && *begin != L'\n' )
begin--;
if( *begin == L'\n' )
begin++;
len = maxi( end-begin, 0 );
begin = end - len;
while( *end && *end != L'\n' )
end++;
if( begin == end && *end )
end++;
len = end-begin;
if( len )
{
reader_kill( begin, len, KILL_APPEND, last_char!=R_KILL_WHOLE_LINE );
}
break;
}
/* yank*/
case R_YANK:
{
yank_str = kill_yank();
insert_str( yank_str );
yank = wcslen( yank_str );
break;
}
/* rotate killring*/
case R_YANK_POP:
{
if( yank )
{
for( i=0; i<yank; i++ )
remove_backward();
yank_str = kill_yank_rotate();
insert_str(yank_str);
yank = wcslen(yank_str);
}
break;
}
/* Escape was pressed */
case L'\x1b':
{
if( data->search_mode )
{
data->search_mode= NO_SEARCH;
if( data->token_history_pos==-1 )
{
history_reset();
reader_set_buffer( (wchar_t *)data->search_buff.buff,
wcslen( (wchar_t *)data->search_buff.buff ) );
}
else
{
reader_replace_current_token( (wchar_t *)data->search_buff.buff );
}
sb_clear( &data->search_buff );
reader_super_highlight_me_plenty( data->buff_pos, 0 );
reader_repaint();
}
break;
}
/* delete backward*/
case R_BACKWARD_DELETE_CHAR:
{
remove_backward();
break;
}
/* delete forward*/
case R_DELETE_CHAR:
{
/**
Remove the current character in the character buffer and on the
screen using syntax highlighting, etc.
*/
if( data->buff_pos < data->buff_len )
{
data->buff_pos++;
remove_backward();
}
break;
}
/*
Evaluate. If the current command is unfinished, or if
the charater is escaped using a backslash, insert a
newline
*/
case R_EXECUTE:
{
/*
Allow backslash-escaped newlines
*/
if( is_backslashed( data->buff, data->buff_pos ) )
{
insert_char( '\n' );
break;
}
switch( data->test_func( data->buff ) )
{
case 0:
{
/*
Finished commend, execute it
*/
if( wcslen( data->buff ) )
{
// wcscpy(data->search_buff,L"");
history_add( data->buff );
}
finished=1;
data->buff_pos=data->buff_len;
reader_repaint();
break;
}
/*
We are incomplete, continue editing
*/
case PARSER_TEST_INCOMPLETE:
{
insert_char( '\n' );
break;
}
/*
Result must be some combination including an
error. The error message will already be
printed, all we need to do is repaint
*/
default:
{
s_reset( &data->screen, 1 );
reader_repaint();
break;
}
}
break;
}
/* History functions */
case R_HISTORY_SEARCH_BACKWARD:
case R_HISTORY_TOKEN_SEARCH_BACKWARD:
case R_HISTORY_SEARCH_FORWARD:
case R_HISTORY_TOKEN_SEARCH_FORWARD:
{
int reset = 0;
if( data->search_mode == NO_SEARCH )
{
reset = 1;
if( ( c == R_HISTORY_SEARCH_BACKWARD ) ||
( c == R_HISTORY_SEARCH_FORWARD ) )
{
data->search_mode = LINE_SEARCH;
}
else
{
data->search_mode = TOKEN_SEARCH;
}
sb_append( &data->search_buff, data->buff );
}
switch( data->search_mode )
{
case LINE_SEARCH:
{
const wchar_t *it = 0;
if( ( c == R_HISTORY_SEARCH_BACKWARD ) ||
( c == R_HISTORY_TOKEN_SEARCH_BACKWARD ) )
{
it = history_prev_match((wchar_t *)data->search_buff.buff);
}
else
{
it = history_next_match((wchar_t *)data->search_buff.buff);
}
handle_history( it );
break;
}
case TOKEN_SEARCH:
{
if( ( c == R_HISTORY_SEARCH_BACKWARD ) ||
( c == R_HISTORY_TOKEN_SEARCH_BACKWARD ) )
{
handle_token_history( SEARCH_BACKWARD, reset );
}
else
{
handle_token_history( SEARCH_FORWARD, reset );
}
break;
}
}
break;
}
/* Move left*/
case R_BACKWARD_CHAR:
{
if( data->buff_pos > 0 )
{
data->buff_pos--;
reader_repaint();
}
break;
}
/* Move right*/
case R_FORWARD_CHAR:
{
if( data->buff_pos < data->buff_len )
{
data->buff_pos++;
reader_repaint();
}
break;
}
/* kill one word left */
case R_BACKWARD_KILL_WORD:
{
move_word(0,1, last_char!=R_BACKWARD_KILL_WORD);
break;
}
/* kill one word right */
case R_KILL_WORD:
{
move_word(1,1, last_char!=R_KILL_WORD);
break;
}
/* move one word left*/
case R_BACKWARD_WORD:
{
move_word(0,0,0);
break;
}
/* move one word right*/
case R_FORWARD_WORD:
{
move_word( 1,0,0);
break;
}
case R_BEGINNING_OF_HISTORY:
{
history_first();
break;
}
case R_END_OF_HISTORY:
{
history_reset();
break;
}
case R_UP_LINE:
case R_DOWN_LINE:
{
int line_old = parse_util_get_line_from_offset( data->buff,
data->buff_pos );
int line_new;
if( c == R_UP_LINE )
line_new = line_old-1;
else
line_new = line_old+1;
int line_count = parse_util_lineno( data->buff, data->buff_len )-1;
if( line_new >= 0 && line_new <= line_count)
{
int base_pos_new;
int base_pos_old;
int indent_old;
int indent_new;
int line_offset_old;
int total_offset_new;
base_pos_new = parse_util_get_offset_from_line( data->buff,
line_new );
base_pos_old = parse_util_get_offset_from_line( data->buff,
line_old );
indent_old = data->indent[base_pos_old];
indent_new = data->indent[base_pos_new];
line_offset_old = data->buff_pos - parse_util_get_offset_from_line( data->buff,
line_old );
total_offset_new = parse_util_get_offset( data->buff, line_new, line_offset_old - 4*(indent_new-indent_old));
data->buff_pos = total_offset_new;
reader_repaint();
}
break;
}
/* Other, if a normal character, we add it to the command */
default:
{
if( (!wchar_private(c)) && (( (c>31) || (c==L'\n'))&& (c != 127)) )
{
regular_char = 1;
insert_char( c );
}
else
{
/*
Low priority debug message. These can happen if
the user presses an unefined control
sequnece. No reason to report.
*/
debug( 2, _( L"Unknown keybinding %d" ), c );
}
break;
}
}
if( (c != R_HISTORY_SEARCH_BACKWARD) &&
(c != R_HISTORY_SEARCH_FORWARD) &&
(c != R_HISTORY_TOKEN_SEARCH_BACKWARD) &&
(c != R_HISTORY_TOKEN_SEARCH_FORWARD) &&
(c != R_NULL) )
{
data->search_mode = NO_SEARCH;
sb_clear( &data->search_buff );
history_reset();
data->token_history_pos=-1;
}
last_char = c;
}
writestr( L"\n" );
/*
if( comp )
halloc_free( comp );
*/
if( !reader_exit_forced() )
{
if( tcsetattr(0,TCSANOW,&old_modes)) /* return to previous mode */
{
wperror(L"tcsetattr");
}
set_color( FISH_COLOR_RESET, FISH_COLOR_RESET );
}
return finished ? data->buff : 0;
}
int reader_search_mode()
{
if( !data )
{
return -1;
}
return !!data->search_mode;
}
/**
Read non-interactively. Read input from stdin without displaying
the prompt, using syntax highlighting. This is used for reading
scripts and init files.
*/
static int read_ni( int fd, io_data_t *io )
{
parser_t &parser = parser_t::principal_parser();
FILE *in_stream;
wchar_t *buff=0;
buffer_t acc;
int des = fd == 0 ? dup(0) : fd;
int res=0;
if (des == -1)
{
wperror( L"dup" );
return 1;
}
b_init( &acc );
in_stream = fdopen( des, "r" );
if( in_stream != 0 )
{
wchar_t *str;
int acc_used;
while(!feof( in_stream ))
{
char buff[4096];
int c;
c = fread(buff, 1, 4096, in_stream);
if( ferror( in_stream ) && ( errno != EINTR ) )
{
debug( 1,
_( L"Error while reading from file descriptor" ) );
/*
Reset buffer on error. We won't evaluate incomplete files.
*/
acc.used=0;
break;
}
b_append( &acc, buff, c );
}
b_append( &acc, "\0", 1 );
acc_used = acc.used;
str = str2wcs( acc.buff );
b_destroy( &acc );
if( fclose( in_stream ))
{
debug( 1,
_( L"Error while closing input stream" ) );
wperror( L"fclose" );
res = 1;
}
if( str )
{
string_buffer_t sb;
sb_init( &sb );
if( ! parser.test( str, 0, &sb, L"fish" ) )
{
parser.eval( str, io, TOP );
}
else
{
fwprintf( stderr, L"%ls", sb.buff );
res = 1;
}
sb_destroy( &sb );
free( str );
}
else
{
if( acc_used > 1 )
{
debug( 1,
_( L"Could not convert input. Read %d bytes." ),
acc_used-1 );
}
else
{
debug( 1,
_( L"Could not read input stream" ) );
}
res=1;
}
}
else
{
debug( 1,
_( L"Error while opening input stream" ) );
wperror( L"fdopen" );
free( buff );
res=1;
}
return res;
}
int reader_read( int fd, io_data_t *io )
{
int res;
/*
If reader_read is called recursively through the '.' builtin, we
need to preserve is_interactive. This, and signal handler setup
is handled by proc_push_interactive/proc_pop_interactive.
*/
int inter = ((fd == STDIN_FILENO) && isatty(STDIN_FILENO));
proc_push_interactive( inter );
res= is_interactive?read_i():read_ni( fd, io );
/*
If the exit command was called in a script, only exit the
script, not the program.
*/
if( data )
data->end_loop = 0;
end_loop = 0;
proc_pop_interactive();
return res;
}
|