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
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
|
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
include ../Makefile.lib
HDRS = libtecla.h
CHECKHDRS =
HDRDIR = .
# Hammerhead: amd64-only
SUBDIRS = $(MACH64)
all : TARGET = all
clean : TARGET = clean
clobber : TARGET = clobber
install : TARGET = install
.KEEP_STATE:
all clean clobber install: $(SUBDIRS)
install_h: $(ROOTHDRS)
check: $(CHECKHDRS)
$(SUBDIRS): FRC
@cd $@; pwd; $(MAKE) $(TARGET)
FRC:
include ../Makefile.targ
include ../../Makefile.msg.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# Copyright (c) 2018, Joyent, Inc.
LIBRARY= libtecla.a
VERS= .1
OBJECTS= getline.o keytab.o freelist.o strngmem.o hash.o history.o \
direader.o homedir.o pathutil.o expand.o stringrp.o cplfile.o \
cplmatch.o pcache.o version.o chrqueue.o ioutil.o errmsg.o
include ../../Makefile.lib
SRCDIR = ../common
LIBS = $(DYNLIB)
LDLIBS += -lc
$(DYNLIB) : LDLIBS += -lcurses
CPPFLAGS += -I$(SRCDIR) -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 \
-DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 \
-DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 \
-DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DUSE_TERMINFO=1 -DHAVE_CURSES_H=1 \
-DHAVE_TERM_H=1 -DHAVE_SYS_SELECT_H=1 -DHAVE_SELECT=1 \
-DHAVE_SYSV_PTY=1 -D__EXTENSIONS__=1 -D_POSIX_C_SOURCE=199506L \
-DPREFER_REENTRANT
CERRWARN += -Wno-type-limits
# not linted
SMATCH=off
.KEEP_STATE:
all: $(LIBS)
include ../../Makefile.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# ident "%Z%%M% %I% %E% SMI"
#
# lib/libtecla/README
#
The source code here is derived from libtecla version 1.6 plus one bug
fix (6353321) from 1.6.1 .
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
TECLA SOFTWARE
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2004 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
include ../Makefile.com
include ../../Makefile.lib.64
install: all $(ROOTLIBS64) $(ROOTLINKS64)
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "ioutil.h"
#include "chrqueue.h"
#include "freelist.h"
#include "errmsg.h"
/*
* Set the number of bytes allocated to each node of the list of
* character buffers. This facility is designed principally as
* an expandible I/O output buffer, so use the stdio buffer size
* where available.
*/
#ifdef BUFSIZ
#define GL_CQ_SIZE BUFSIZ
#else
#define GL_CQ_SIZE 512
#endif
/*
* The queue is contained in a list of fixed sized buffers. New nodes
* are appended to this list as needed to accomodate newly added bytes.
* Old nodes at the head of the list are removed as they are emptied.
*/
typedef struct CqCharBuff CqCharBuff;
struct CqCharBuff {
CqCharBuff *next; /* The next node in the list of buffers */
char bytes[GL_CQ_SIZE]; /* The fixed size buffer of this node */
};
/*
* Define the structure that is used to contain a list of character
* buffers.
*/
struct GlCharQueue {
ErrMsg *err; /* A buffer in which to record error messages */
FreeList *bufmem; /* A free-list of CqCharBuff structures */
struct {
CqCharBuff *head; /* The head of the list of output buffers */
CqCharBuff *tail; /* The tail of the list of output buffers */
} buffers;
int nflush; /* The total number of characters that have been */
/* flushed from the start of the queue since */
/* _glq_empty_queue() was last called. */
int ntotal; /* The total number of characters that have been */
/* appended to the queue since _glq_empty_queue() */
/* was last called. */
};
/*.......................................................................
* Create a new GlCharQueue object.
*
* Output:
* return GlCharQueue * The new object, or NULL on error.
*/
GlCharQueue *_new_GlCharQueue(void)
{
GlCharQueue *cq; /* The object to be returned */
/*
* Allocate the container.
*/
cq = malloc(sizeof(GlCharQueue));
if(!cq) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_GlCharQueue().
*/
cq->err = NULL;
cq->bufmem = NULL;
cq->buffers.head = NULL;
cq->buffers.tail = NULL;
cq->nflush = cq->ntotal = 0;
/*
* Allocate a place to record error messages.
*/
cq->err = _new_ErrMsg();
if(!cq->err)
return _del_GlCharQueue(cq);
/*
* Allocate the freelist of CqCharBuff structures.
*/
cq->bufmem = _new_FreeList(sizeof(CqCharBuff), 1);
if(!cq->bufmem)
return _del_GlCharQueue(cq);
return cq;
}
/*.......................................................................
* Delete a GlCharQueue object.
*
* Input:
* cq GlCharQueue * The object to be deleted.
* Output:
* return GlCharQueue * The deleted object (always NULL).
*/
GlCharQueue *_del_GlCharQueue(GlCharQueue *cq)
{
if(cq) {
cq->err = _del_ErrMsg(cq->err);
cq->bufmem = _del_FreeList(cq->bufmem, 1);
free(cq);
};
return NULL;
}
/*.......................................................................
* Append an array of n characters to a character queue.
*
* Input:
* cq GlCharQueue * The queue to append to.
* chars const char * The array of n characters to be appended.
* n int The number of characters in chars[].
* write_fn GL_WRITE_FN * The function to call to output characters,
* or 0 to simply discard the contents of the
* queue. This will be called whenever the
* buffer becomes full. If it fails to release
* any space, the buffer will be extended.
* data void * Anonymous data to pass to write_fn().
* Output:
* return int The number of characters successfully
* appended. This will only be < n on error.
*/
int _glq_append_chars(GlCharQueue *cq, const char *chars, int n,
GlWriteFn *write_fn, void *data)
{
int ndone = 0; /* The number of characters appended so far */
/*
* Check the arguments.
*/
if(!cq || !chars) {
errno = EINVAL;
return 0;
};
/*
* The appended characters may have to be split between multiple
* buffers, so loop for each buffer.
*/
while(ndone < n) {
int ntodo; /* The number of characters remaining to be appended */
int nleft; /* The amount of space remaining in cq->buffers.tail */
int nnew; /* The number of characters to append to cq->buffers.tail */
/*
* Compute the offset at which the next character should be written
* into the tail buffer segment.
*/
int boff = cq->ntotal % GL_CQ_SIZE;
/*
* Since we don't allocate a new buffer until we have at least one
* character to write into it, if boff is 0 at this point, it means
* that we hit the end of the tail buffer segment on the last append,
* so we need to allocate a new one.
*
* If allocating this new node will require a call to malloc(), as
* opposed to using a currently unused node in the freelist, first try
* flushing the current contents of the buffer to the terminal. When
* write_fn() uses blocking I/O, this stops the buffer size ever getting
* bigger than a single buffer node. When it is non-blocking, it helps
* to keep the amount of memory, but it isn't gauranteed to do so.
*/
if(boff == 0 && _idle_FreeListNodes(cq->bufmem) == 0) {
switch(_glq_flush_queue(cq, write_fn, data)) {
case GLQ_FLUSH_DONE:
break;
case GLQ_FLUSH_AGAIN:
errno = 0; /* Don't confuse the caller */
break;
default:
return ndone; /* Error */
};
boff = cq->ntotal % GL_CQ_SIZE;
};
/*
* Since we don't allocate a new buffer until we have at least one
* character to write into it, if boff is 0 at this point, it means
* that we hit the end of the tail buffer segment on the last append,
* so we need to allocate a new one.
*/
if(boff == 0) {
/*
* Allocate the new node.
*/
CqCharBuff *node = (CqCharBuff *) _new_FreeListNode(cq->bufmem);
if(!node) {
_err_record_msg(cq->err, "Insufficient memory to buffer output.",
END_ERR_MSG);
return ndone;
};
/*
* Initialize the node.
*/
node->next = NULL;
/*
* Append the new node to the tail of the list.
*/
if(cq->buffers.tail)
cq->buffers.tail->next = node;
else
cq->buffers.head = node;
cq->buffers.tail = node;
};
/*
* How much room is there for new characters in the current tail node?
*/
nleft = GL_CQ_SIZE - boff;
/*
* How many characters remain to be appended?
*/
ntodo = n - ndone;
/*
* How many characters should we append to the current tail node?
*/
nnew = nleft < ntodo ? nleft : ntodo;
/*
* Append the latest prefix of nnew characters.
*/
memcpy(cq->buffers.tail->bytes + boff, chars + ndone, nnew);
cq->ntotal += nnew;
ndone += nnew;
};
/*
* Return the count of the number of characters successfully appended.
*/
return ndone;
}
/*.......................................................................
* Discard the contents of a queue of characters.
*
* Input:
* cq GlCharQueue * The queue to clear.
*/
void _glq_empty_queue(GlCharQueue *cq)
{
if(cq) {
/*
* Return all list nodes to their respective free-lists.
*/
_rst_FreeList(cq->bufmem);
/*
* Mark the lists as empty.
*/
cq->buffers.head = cq->buffers.tail = NULL;
cq->nflush = cq->ntotal = 0;
};
}
/*.......................................................................
* Return a count of the number of characters currently in the queue.
*
* Input:
* cq GlCharQueue * The queue of interest.
* Output:
* return int The number of characters in the queue.
*/
int _glq_char_count(GlCharQueue *cq)
{
return (cq && cq->buffers.head) ? (cq->ntotal - cq->nflush) : 0;
}
/*.......................................................................
* Write as many characters as possible from the start of a character
* queue via a given output callback function, removing those written
* from the queue.
*
* Input:
* cq GlCharQueue * The queue to write characters from.
* write_fn GL_WRITE_FN * The function to call to output characters,
* or 0 to simply discard the contents of the
* queue.
* data void * Anonymous data to pass to write_fn().
* Output:
* return GlFlushState The status of the flush operation:
* GLQ_FLUSH_DONE - The flush operation
* completed successfully.
* GLQ_FLUSH_AGAIN - The flush operation
* couldn't be completed
* on this call. Call this
* function again when the
* output channel can accept
* further output.
* GLQ_FLUSH_ERROR Unrecoverable error.
*/
GlqFlushState _glq_flush_queue(GlCharQueue *cq, GlWriteFn *write_fn,
void *data)
{
/*
* Check the arguments.
*/
if(!cq) {
errno = EINVAL;
return GLQ_FLUSH_ERROR;
};
/*
* If possible keep writing until all of the chained buffers have been
* emptied and removed from the list.
*/
while(cq->buffers.head) {
/*
* Are we looking at the only node in the list?
*/
int is_tail = cq->buffers.head == cq->buffers.tail;
/*
* How many characters more than an exact multiple of the buffer-segment
* size have been added to the buffer so far?
*/
int nmodulo = cq->ntotal % GL_CQ_SIZE;
/*
* How many characters of the buffer segment at the head of the list
* have been used? Note that this includes any characters that have
* already been flushed. Also note that if nmodulo==0, this means that
* the tail buffer segment is full. The reason for this is that we
* don't allocate new tail buffer segments until there is at least one
* character to be added to them.
*/
int nhead = (!is_tail || nmodulo == 0) ? GL_CQ_SIZE : nmodulo;
/*
* How many characters remain to be flushed from the buffer
* at the head of the list?
*/
int nbuff = nhead - (cq->nflush % GL_CQ_SIZE);
/*
* Attempt to write this number.
*/
int nnew = write_fn(data, cq->buffers.head->bytes +
cq->nflush % GL_CQ_SIZE, nbuff);
/*
* Was anything written?
*/
if(nnew > 0) {
/*
* Increment the count of the number of characters that have
* been flushed from the head of the queue.
*/
cq->nflush += nnew;
/*
* If we succeded in writing all of the contents of the current
* buffer segment, remove it from the queue.
*/
if(nnew == nbuff) {
/*
* If we just emptied the last node left in the list, then the queue is
* now empty and should be reset.
*/
if(is_tail) {
_glq_empty_queue(cq);
} else {
/*
* Get the node to be removed from the head of the list.
*/
CqCharBuff *node = cq->buffers.head;
/*
* Make the node that follows it the new head of the queue.
*/
cq->buffers.head = node->next;
/*
* Return it to the freelist.
*/
node = (CqCharBuff *) _del_FreeListNode(cq->bufmem, node);
};
};
/*
* If the write blocked, request that this function be called again
* when space to write next becomes available.
*/
} else if(nnew==0) {
return GLQ_FLUSH_AGAIN;
/*
* I/O error.
*/
} else {
_err_record_msg(cq->err, "Error writing to terminal", END_ERR_MSG);
return GLQ_FLUSH_ERROR;
};
};
/*
* To get here the queue must now be empty.
*/
return GLQ_FLUSH_DONE;
}
/*.......................................................................
* Return extra information (ie. in addition to that provided by errno)
* about the last error to occur in any of the public functions of this
* module.
*
* Input:
* cq GlCharQueue * The container of the history list.
* Output:
* return const char * A pointer to the internal buffer in which
* the error message is temporarily stored.
*/
const char *_glq_last_error(GlCharQueue *cq)
{
return cq ? _err_get_msg(cq->err) : "NULL GlCharQueue argument";
}
#ifndef chrqueue_h
#define chrqueue_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*-----------------------------------------------------------------------
* This module implements a queue of characters to be processed in some
* way. It is used by gl_get_line() to maintain a queue of characters
* to be sent to a remote terminal. Characters are recorded in a
* dynamically extensible list of fixed sized buffers.
*/
typedef struct GlCharQueue GlCharQueue;
/*
* Create a new character queue.
*/
GlCharQueue *_new_GlCharQueue(void);
/*
* Delete a redundant character queue.
*/
GlCharQueue *_del_GlCharQueue(GlCharQueue *cq);
/*
* Append an array of n characters to a character queue.
*/
int _glq_append_chars(GlCharQueue *cq, const char *chars, int n,
GlWriteFn *write_fn, void *data);
/*
* Clear a character queue.
*/
void _glq_empty_queue(GlCharQueue *cq);
/*
* Return a count of the number of characters in the queue.
*/
int _glq_char_count(GlCharQueue *cq);
/*
* A structure of the following type is used by _glq_peek_chars() to
* return characters at the start of the queue.
*/
typedef struct {
const char *buff; /* A pointer to the first undeleted byte in the */
/* first buffer of the queue. */
int nbuff; /* The number of characters in buff[] */
} GlCharQueueBuff;
/*
* Enumerator values of the following type are returned by
* _glq_flush_queue() to indicate the status of the flush operation.
*/
typedef enum {
GLQ_FLUSH_DONE, /* The flush operation completed successfully */
GLQ_FLUSH_AGAIN, /* The flush operation couldn't be completed on this */
/* call. Call this function again when the output */
/* channel can accept further output. */
GLQ_FLUSH_ERROR /* Unrecoverable error. */
} GlqFlushState;
/*
* Transfer as much of the contents of a character queue to an output
* channel as possible, returning before the queue is empty if the
* write_fn() callback says that it can't currently write anymore.
*/
GlqFlushState _glq_flush_queue(GlCharQueue *cq, GlWriteFn *write_fn,
void *data);
/*
* Provide information about the last error that occurred while calling
* any of the above functions.
*/
const char *_glq_last_error(GlCharQueue *cq);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
/*
* Standard includes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
/*
* Local includes.
*/
#include "libtecla.h"
#include "direader.h"
#include "homedir.h"
#include "pathutil.h"
#include "cplfile.h"
#include "errmsg.h"
/*
* Set the maximum length allowed for usernames.
* names.
*/
#define USR_LEN 100
/*
* Set the maximum length allowed for environment variable names.
*/
#define ENV_LEN 100
/*
* The resources needed to complete a filename are maintained in objects
* of the following type.
*/
struct CompleteFile {
ErrMsg *err; /* The error reporting buffer */
DirReader *dr; /* A directory reader */
HomeDir *home; /* A home directory expander */
PathName *path; /* The buffer in which to accumulate the path */
PathName *buff; /* A pathname work buffer */
char usrnam[USR_LEN+1]; /* The buffer used when reading the names of */
/* users. */
char envnam[ENV_LEN+1]; /* The buffer used when reading the names of */
/* environment variables. */
};
static int cf_expand_home_dir(CompleteFile *cf, const char *user);
static int cf_complete_username(CompleteFile *cf, WordCompletion *cpl,
const char *prefix, const char *line,
int word_start, int word_end, int escaped);
static HOME_DIR_FN(cf_homedir_callback);
static int cf_complete_entry(CompleteFile *cf, WordCompletion *cpl,
const char *line, int word_start, int word_end,
int escaped, CplCheckFn *check_fn,
void *check_data);
static char *cf_read_name(CompleteFile *cf, const char *type,
const char *string, int slen,
char *nambuf, int nammax);
static int cf_prepare_suffix(CompleteFile *cf, const char *suffix,
int add_escapes);
/*
* A stack based object of the following type is used to pass data to the
* cf_homedir_callback() function.
*/
typedef struct {
CompleteFile *cf; /* The file-completion resource object */
WordCompletion *cpl; /* The string-completion rsource object */
size_t prefix_len; /* The length of the prefix being completed */
const char *line; /* The line from which the prefix was extracted */
int word_start; /* The index in line[] of the start of the username */
int word_end; /* The index in line[] following the end of the prefix */
int escaped; /* If true, add escapes to the completion suffixes */
} CfHomeArgs;
/*.......................................................................
* Create a new file-completion object.
*
* Output:
* return CompleteFile * The new object, or NULL on error.
*/
CompleteFile *_new_CompleteFile(void)
{
CompleteFile *cf; /* The object to be returned */
/*
* Allocate the container.
*/
cf = (CompleteFile *) malloc(sizeof(CompleteFile));
if(!cf) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_CompleteFile().
*/
cf->err = NULL;
cf->dr = NULL;
cf->home = NULL;
cf->path = NULL;
cf->buff = NULL;
cf->usrnam[0] = '\0';
cf->envnam[0] = '\0';
/*
* Allocate a place to record error messages.
*/
cf->err = _new_ErrMsg();
if(!cf->err)
return _del_CompleteFile(cf);
/*
* Create the object that is used for reading directories.
*/
cf->dr = _new_DirReader();
if(!cf->dr)
return _del_CompleteFile(cf);
/*
* Create the object that is used to lookup home directories.
*/
cf->home = _new_HomeDir();
if(!cf->home)
return _del_CompleteFile(cf);
/*
* Create the buffer in which the completed pathname is accumulated.
*/
cf->path = _new_PathName();
if(!cf->path)
return _del_CompleteFile(cf);
/*
* Create a pathname work buffer.
*/
cf->buff = _new_PathName();
if(!cf->buff)
return _del_CompleteFile(cf);
return cf;
}
/*.......................................................................
* Delete a file-completion object.
*
* Input:
* cf CompleteFile * The object to be deleted.
* Output:
* return CompleteFile * The deleted object (always NULL).
*/
CompleteFile *_del_CompleteFile(CompleteFile *cf)
{
if(cf) {
cf->err = _del_ErrMsg(cf->err);
cf->dr = _del_DirReader(cf->dr);
cf->home = _del_HomeDir(cf->home);
cf->path = _del_PathName(cf->path);
cf->buff = _del_PathName(cf->buff);
free(cf);
};
return NULL;
}
/*.......................................................................
* Look up the possible completions of the incomplete filename that
* lies between specified indexes of a given command-line string.
*
* Input:
* cpl WordCompletion * The object in which to record the completions.
* cf CompleteFile * The filename-completion resource object.
* line const char * The string containing the incomplete filename.
* word_start int The index of the first character in line[]
* of the incomplete filename.
* word_end int The index of the character in line[] that
* follows the last character of the incomplete
* filename.
* escaped int If true, backslashes in line[] are
* interpreted as escaping the characters
* that follow them, and any spaces, tabs,
* backslashes, or wildcard characters in the
* returned suffixes will be similarly escaped.
* If false, backslashes will be interpreted as
* literal parts of the file name, and no
* backslashes will be added to the returned
* suffixes.
* check_fn CplCheckFn * If not zero, this argument specifies a
* function to call to ask whether a given
* file should be included in the list
* of completions.
* check_data void * Anonymous data to be passed to check_fn().
* Output:
* return int 0 - OK.
* 1 - Error. A description of the error can be
* acquired by calling _cf_last_error(cf).
*/
int _cf_complete_file(WordCompletion *cpl, CompleteFile *cf,
const char *line, int word_start, int word_end,
int escaped, CplCheckFn *check_fn, void *check_data)
{
const char *lptr; /* A pointer into line[] */
int nleft; /* The number of characters still to be processed */
/* in line[]. */
/*
* Check the arguments.
*/
if(!cpl || !cf || !line || word_end < word_start) {
if(cf) {
_err_record_msg(cf->err, "_cf_complete_file: Invalid arguments",
END_ERR_MSG);
};
return 1;
};
/*
* Clear the buffer in which the filename will be constructed.
*/
_pn_clear_path(cf->path);
/*
* How many characters are to be processed?
*/
nleft = word_end - word_start;
/*
* Get a pointer to the start of the incomplete filename.
*/
lptr = line + word_start;
/*
* If the first character is a tilde, then perform home-directory
* interpolation.
*/
if(nleft > 0 && *lptr == '~') {
int slen;
if(!cf_read_name(cf, "User", ++lptr, --nleft, cf->usrnam, USR_LEN))
return 1;
/*
* Advance over the username in the input line.
*/
slen = strlen(cf->usrnam);
lptr += slen;
nleft -= slen;
/*
* If we haven't hit the end of the input string then we have a complete
* username to translate to the corresponding home directory.
*/
if(nleft > 0) {
if(cf_expand_home_dir(cf, cf->usrnam))
return 1;
/*
* ~user and ~ are usually followed by a directory separator to
* separate them from the file contained in the home directory.
* If the home directory is the root directory, then we don't want
* to follow the home directory by a directory separator, so we should
* skip over it so that it doesn't get copied into the filename.
*/
if(strcmp(cf->path->name, FS_ROOT_DIR) == 0 &&
strncmp(lptr, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
lptr += FS_DIR_SEP_LEN;
nleft -= FS_DIR_SEP_LEN;
};
/*
* If we have reached the end of the input string, then the username
* may be incomplete, and we should attempt to complete it.
*/
} else {
/*
* Look up the possible completions of the username.
*/
return cf_complete_username(cf, cpl, cf->usrnam, line, word_start+1,
word_end, escaped);
};
};
/*
* Copy the rest of the path, stopping to expand $envvar expressions
* where encountered.
*/
while(nleft > 0) {
int seglen; /* The length of the next segment to be copied */
/*
* Find the length of the next segment to be copied, stopping if an
* unescaped '$' is seen, or the end of the path is reached.
*/
for(seglen=0; seglen < nleft; seglen++) {
int c = lptr[seglen];
if(escaped && c == '\\')
seglen++;
else if(c == '$')
break;
/*
* We will be completing the last component of the file name,
* so whenever a directory separator is seen, assume that it
* might be the start of the last component, and mark the character
* that follows it as the start of the name that is to be completed.
*/
if(nleft >= FS_DIR_SEP_LEN &&
strncmp(lptr + seglen, FS_DIR_SEP, FS_DIR_SEP_LEN)==0) {
word_start = (lptr + seglen) - line + FS_DIR_SEP_LEN;
};
};
/*
* We have reached either the end of the filename or the start of
* $environment_variable expression. Record the newly checked
* segment of the filename in the output filename, removing
* backslash-escapes where needed.
*/
if(_pn_append_to_path(cf->path, lptr, seglen, escaped) == NULL) {
_err_record_msg(cf->err, "Insufficient memory to complete filename",
END_ERR_MSG);
return 1;
};
lptr += seglen;
nleft -= seglen;
/*
* If the above loop finished before we hit the end of the filename,
* then this was because an unescaped $ was seen. In this case, interpolate
* the value of the environment variable that follows it into the output
* filename.
*/
if(nleft > 0) {
char *value; /* The value of the environment variable */
int vlen; /* The length of the value string */
int nlen; /* The length of the environment variable name */
/*
* Read the name of the environment variable.
*/
if(!cf_read_name(cf, "Environment", ++lptr, --nleft, cf->envnam, ENV_LEN))
return 1;
/*
* Advance over the environment variable name in the input line.
*/
nlen = strlen(cf->envnam);
lptr += nlen;
nleft -= nlen;
/*
* Get the value of the environment variable.
*/
value = getenv(cf->envnam);
if(!value) {
_err_record_msg(cf->err, "Unknown environment variable: ", cf->envnam,
END_ERR_MSG);
return 1;
};
vlen = strlen(value);
/*
* If we are at the start of the filename and the first character of the
* environment variable value is a '~', attempt home-directory
* interpolation.
*/
if(cf->path->name[0] == '\0' && value[0] == '~') {
if(!cf_read_name(cf, "User", value+1, vlen-1, cf->usrnam, USR_LEN) ||
cf_expand_home_dir(cf, cf->usrnam))
return 1;
/*
* If the home directory is the root directory, and the ~usrname expression
* was followed by a directory separator, prevent the directory separator
* from being appended to the root directory by skipping it in the
* input line.
*/
if(strcmp(cf->path->name, FS_ROOT_DIR) == 0 &&
strncmp(lptr, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
lptr += FS_DIR_SEP_LEN;
nleft -= FS_DIR_SEP_LEN;
};
} else {
/*
* Append the value of the environment variable to the output path.
*/
if(_pn_append_to_path(cf->path, value, strlen(value), escaped)==NULL) {
_err_record_msg(cf->err, "Insufficient memory to complete filename",
END_ERR_MSG);
return 1;
};
/*
* Prevent extra directory separators from being added.
*/
if(nleft >= FS_DIR_SEP_LEN &&
strcmp(cf->path->name, FS_ROOT_DIR) == 0 &&
strncmp(lptr, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
lptr += FS_DIR_SEP_LEN;
nleft -= FS_DIR_SEP_LEN;
} else if(vlen > FS_DIR_SEP_LEN &&
strcmp(value + vlen - FS_DIR_SEP_LEN, FS_DIR_SEP)==0) {
cf->path->name[vlen-FS_DIR_SEP_LEN] = '\0';
};
};
/*
* If adding the environment variable didn't form a valid directory,
* we can't complete the line, since there is no way to separate append
* a partial filename to an environment variable reference without
* that appended part of the name being seen later as part of the
* environment variable name. Thus if the currently constructed path
* isn't a directory, quite now with no completions having been
* registered.
*/
if(!_pu_path_is_dir(cf->path->name))
return 0;
/*
* For the reasons given above, if we have reached the end of the filename
* with the expansion of an environment variable, the only allowed
* completion involves the addition of a directory separator.
*/
if(nleft == 0) {
if(cpl_add_completion(cpl, line, lptr-line, word_end, FS_DIR_SEP,
"", "")) {
_err_record_msg(cf->err, cpl_last_error(cpl), END_ERR_MSG);
return 1;
};
return 0;
};
};
};
/*
* Complete the filename if possible.
*/
return cf_complete_entry(cf, cpl, line, word_start, word_end, escaped,
check_fn, check_data);
}
/*.......................................................................
* Return a description of the last path-completion error that occurred.
*
* Input:
* cf CompleteFile * The path-completion resource object.
* Output:
* return const char * The description of the last error.
*/
const char *_cf_last_error(CompleteFile *cf)
{
return cf ? _err_get_msg(cf->err) : "NULL CompleteFile argument";
}
/*.......................................................................
* Lookup the home directory of the specified user, or the current user
* if no name is specified, appending it to output pathname.
*
* Input:
* cf CompleteFile * The pathname completion resource object.
* user const char * The username to lookup, or "" to lookup the
* current user.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int cf_expand_home_dir(CompleteFile *cf, const char *user)
{
/*
* Attempt to lookup the home directory.
*/
const char *home_dir = _hd_lookup_home_dir(cf->home, user);
/*
* Failed?
*/
if(!home_dir) {
_err_record_msg(cf->err, _hd_last_home_dir_error(cf->home), END_ERR_MSG);
return 1;
};
/*
* Append the home directory to the pathname string.
*/
if(_pn_append_to_path(cf->path, home_dir, -1, 0) == NULL) {
_err_record_msg(cf->err, "Insufficient memory for home directory expansion",
END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Lookup and report all completions of a given username prefix.
*
* Input:
* cf CompleteFile * The filename-completion resource object.
* cpl WordCompletion * The object in which to record the completions.
* prefix const char * The prefix of the usernames to lookup.
* line const char * The command-line in which the username appears.
* word_start int The index within line[] of the start of the
* username that is being completed.
* word_end int The index within line[] of the character which
* follows the incomplete username.
* escaped int True if the completions need to have special
* characters escaped.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int cf_complete_username(CompleteFile *cf, WordCompletion *cpl,
const char *prefix, const char *line,
int word_start, int word_end, int escaped)
{
/*
* Set up a container of anonymous arguments to be sent to the
* username-lookup iterator.
*/
CfHomeArgs args;
args.cf = cf;
args.cpl = cpl;
args.prefix_len = strlen(prefix);
args.line = line;
args.word_start = word_start;
args.word_end = word_end;
args.escaped = escaped;
/*
* Iterate through the list of users, recording those which start
* with the specified prefix.
*/
if(_hd_scan_user_home_dirs(cf->home, prefix, &args, cf_homedir_callback)) {
_err_record_msg(cf->err, _hd_last_home_dir_error(cf->home), END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* The user/home-directory scanner callback function (see homedir.h)
* used by cf_complete_username().
*/
static HOME_DIR_FN(cf_homedir_callback)
{
/*
* Get the file-completion resources from the anonymous data argument.
*/
CfHomeArgs *args = (CfHomeArgs *) data;
WordCompletion *cpl = args->cpl;
CompleteFile *cf = args->cf;
/*
* Copy the username into the pathname work buffer, adding backslash
* escapes where needed.
*/
if(cf_prepare_suffix(cf, usrnam+args->prefix_len, args->escaped)) {
strncpy(errmsg, _err_get_msg(cf->err), maxerr);
errmsg[maxerr] = '\0';
return 1;
};
/*
* Report the completion suffix that was copied above.
*/
if(cpl_add_completion(cpl, args->line, args->word_start, args->word_end,
cf->buff->name, FS_DIR_SEP, FS_DIR_SEP)) {
strncpy(errmsg, cpl_last_error(cpl), maxerr);
errmsg[maxerr] = '\0';
return 1;
};
return 0;
}
/*.......................................................................
* Report possible completions of the filename in cf->path->name[].
*
* Input:
* cf CompleteFile * The file-completion resource object.
* cpl WordCompletion * The object in which to record the completions.
* line const char * The input line, as received by the callback
* function.
* word_start int The index within line[] of the start of the
* last component of the filename that is being
* completed.
* word_end int The index within line[] of the character which
* follows the incomplete filename.
* escaped int If true, escape special characters in the
* completion suffixes.
* check_fn CplCheckFn * If not zero, this argument specifies a
* function to call to ask whether a given
* file should be included in the list
* of completions.
* check_data void * Anonymous data to be passed to check_fn().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int cf_complete_entry(CompleteFile *cf, WordCompletion *cpl,
const char *line, int word_start, int word_end,
int escaped, CplCheckFn *check_fn,
void *check_data)
{
const char *dirpath; /* The name of the parent directory */
int start; /* The index of the start of the last filename */
/* component in the transcribed filename. */
const char *prefix; /* The filename prefix to be completed */
int prefix_len; /* The length of the filename prefix */
const char *file_name; /* The lastest filename being compared */
int waserr = 0; /* True after errors */
int terminated=0; /* True if the directory part had to be terminated */
/*
* Get the pathname string and its current length.
*/
char *pathname = cf->path->name;
int pathlen = strlen(pathname);
/*
* Locate the start of the final component of the pathname.
*/
for(start=pathlen - 1; start >= 0 &&
strncmp(pathname + start, FS_DIR_SEP, FS_DIR_SEP_LEN) != 0; start--)
;
/*
* Is the parent directory the root directory?
*/
if(start==0 ||
(start < 0 && strncmp(pathname, FS_ROOT_DIR, FS_ROOT_DIR_LEN) == 0)) {
dirpath = FS_ROOT_DIR;
start += FS_ROOT_DIR_LEN;
/*
* If we found a directory separator then the part which precedes the
* last component is the name of the directory to be opened.
*/
} else if(start > 0) {
/*
* The _dr_open_dir() function requires the directory name to be '\0'
* terminated, so temporarily do this by overwriting the first character
* of the directory separator.
*/
pathname[start] = '\0';
dirpath = pathname;
terminated = 1;
/*
* We reached the start of the pathname before finding a directory
* separator, so arrange to open the current working directory.
*/
} else {
start = 0;
dirpath = FS_PWD;
};
/*
* Attempt to open the directory.
*/
if(_dr_open_dir(cf->dr, dirpath, NULL)) {
_err_record_msg(cf->err, "Can't open directory: ", dirpath, END_ERR_MSG);
return 1;
};
/*
* If removed above, restore the directory separator and skip over it
* to the start of the filename.
*/
if(terminated) {
memcpy(pathname + start, FS_DIR_SEP, FS_DIR_SEP_LEN);
start += FS_DIR_SEP_LEN;
};
/*
* Get the filename prefix and its length.
*/
prefix = pathname + start;
prefix_len = strlen(prefix);
/*
* Traverse the directory, looking for files who's prefixes match the
* last component of the pathname.
*/
while((file_name = _dr_next_file(cf->dr)) != NULL && !waserr) {
int name_len = strlen(file_name);
/*
* Is the latest filename a possible completion of the filename prefix?
*/
if(name_len >= prefix_len && strncmp(prefix, file_name, prefix_len)==0) {
/*
* When listing all files in a directory, don't list files that start
* with '.'. This is how hidden files are denoted in UNIX.
*/
if(prefix_len > 0 || file_name[0] != '.') {
/*
* Copy the completion suffix into the work pathname cf->buff->name,
* adding backslash escapes if needed.
*/
if(cf_prepare_suffix(cf, file_name + prefix_len, escaped)) {
waserr = 1;
} else {
/*
* We want directories to be displayed with directory suffixes,
* and other fully completed filenames to be followed by spaces.
* To check the type of the file, append the current suffix
* to the path being completed, check the filetype, then restore
* the path to its original form.
*/
const char *cont_suffix = ""; /* The suffix to add if fully */
/* completed. */
const char *type_suffix = ""; /* The suffix to add when listing */
if(_pn_append_to_path(cf->path, file_name + prefix_len,
-1, escaped) == NULL) {
_err_record_msg(cf->err,
"Insufficient memory to complete filename.",
END_ERR_MSG);
return 1;
};
/*
* Specify suffixes according to the file type.
*/
if(_pu_path_is_dir(cf->path->name)) {
cont_suffix = FS_DIR_SEP;
type_suffix = FS_DIR_SEP;
} else if(!check_fn || check_fn(check_data, cf->path->name)) {
cont_suffix = " ";
} else {
cf->path->name[pathlen] = '\0';
continue;
};
/*
* Remove the temporarily added suffix.
*/
cf->path->name[pathlen] = '\0';
/*
* Record the latest completion.
*/
if(cpl_add_completion(cpl, line, word_start, word_end, cf->buff->name,
type_suffix, cont_suffix))
waserr = 1;
};
};
};
};
/*
* Close the directory.
*/
_dr_close_dir(cf->dr);
return waserr;
}
/*.......................................................................
* Read a username or environment variable name, stopping when a directory
* separator is seen, when the end of the string is reached, or the
* output buffer overflows.
*
* Input:
* cf CompleteFile * The file-completion resource object.
* type char * The capitalized name of the type of name being read.
* string char * The string who's prefix contains the name.
* slen int The number of characters in string[].
* nambuf char * The output name buffer.
* nammax int The longest string that will fit in nambuf[], excluding
* the '\0' terminator.
* Output:
* return char * A pointer to nambuf on success. On error NULL is
* returned and a description of the error is recorded
* in cf->err.
*/
static char *cf_read_name(CompleteFile *cf, const char *type,
const char *string, int slen,
char *nambuf, int nammax)
{
int namlen; /* The number of characters in nambuf[] */
const char *sptr; /* A pointer into string[] */
/*
* Work out the max number of characters that should be copied.
*/
int nmax = nammax < slen ? nammax : slen;
/*
* Get the environment variable name that follows the dollar.
*/
for(sptr=string,namlen=0;
namlen < nmax && (slen-namlen < FS_DIR_SEP_LEN ||
strncmp(sptr, FS_DIR_SEP, FS_DIR_SEP_LEN) != 0);
namlen++) {
nambuf[namlen] = *sptr++;
};
/*
* Did the name overflow the buffer?
*/
if(namlen >= nammax) {
_err_record_msg(cf->err, type, " name too long", END_ERR_MSG);
return NULL;
};
/*
* Terminate the string.
*/
nambuf[namlen] = '\0';
return nambuf;
}
/*.......................................................................
* Using the work buffer cf->buff, make a suitably escaped copy of a
* given completion suffix, ready to be passed to cpl_add_completion().
*
* Input:
* cf CompleteFile * The file-completion resource object.
* suffix char * The suffix to be copied.
* add_escapes int If true, escape special characters.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int cf_prepare_suffix(CompleteFile *cf, const char *suffix,
int add_escapes)
{
const char *sptr; /* A pointer into suffix[] */
int nbsl; /* The number of backslashes to add to the suffix */
int i;
/*
* How long is the suffix?
*/
int suffix_len = strlen(suffix);
/*
* Clear the work buffer.
*/
_pn_clear_path(cf->buff);
/*
* Count the number of backslashes that will have to be added to
* escape spaces, tabs, backslashes and wildcard characters.
*/
nbsl = 0;
if(add_escapes) {
for(sptr = suffix; *sptr; sptr++) {
switch(*sptr) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
nbsl++;
break;
};
};
};
/*
* Arrange for the output path buffer to have sufficient room for the
* both the suffix and any backslashes that have to be inserted.
*/
if(_pn_resize_path(cf->buff, suffix_len + nbsl) == NULL) {
_err_record_msg(cf->err, "Insufficient memory to complete filename",
END_ERR_MSG);
return 1;
};
/*
* If the suffix doesn't need any escapes, copy it directly into the
* work buffer.
*/
if(nbsl==0) {
strlcpy(cf->buff->name, suffix, cf->buff->dim);
} else {
/*
* Make a copy with special characters escaped?
*/
if(nbsl > 0) {
const char *src = suffix;
char *dst = cf->buff->name;
for(i=0; i<suffix_len; i++) {
switch(*src) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
*dst++ = '\\';
};
*dst++ = *src++;
};
*dst = '\0';
};
};
return 0;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
#ifndef cplfile_h
#define cplfile_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
typedef struct CompleteFile CompleteFile;
/*
* Create a file-completion resource object.
*/
CompleteFile *_new_CompleteFile(void);
/*
* Delete a file-completion resource object.
*/
CompleteFile *_del_CompleteFile(CompleteFile *cf);
/*.......................................................................
* Complete the string between path[0] and path[len-1] as a pathname,
* leaving the last component uncompleted if it is potentially ambiguous,
* and returning an array of possible completions. Note that the returned
* container belongs to the 'cf' object and its contents will change on
* subsequent calls to this function.
*
* Input:
* cpl WordCompletion * The object in which to record the completions.
* cf CompleteFile * The filename-completion resource object.
* line const char * The string containing the incomplete filename.
* word_start int The index of the first character in line[]
* of the incomplete filename.
* word_end int The index of the character in line[] that
* follows the last character of the incomplete
* filename.
* escaped int If true, backslashes in path[] are
* interpreted as escaping the characters
* that follow them, and any spaces, tabs,
* backslashes, or wildcard characters in the
* returned suffixes will be similarly be escaped.
* If false, backslashes will be interpreted as
* literal parts of the file name, and no
* backslashes will be added to the returned
* suffixes.
* check_fn CplCheckFn * If not zero, this argument specifies a
* function to call to ask whether a given
* file should be included in the list
* of completions.
* check_data void * Anonymous data to be passed to check_fn().
* Output:
* return int 0 - OK.
* 1 - Error. A description of the error can be
* acquired by calling cf_last_error(cf).
*/
int _cf_complete_file(WordCompletion *cpl, CompleteFile *cf,
const char *line, int word_start, int word_end,
int escaped, CplCheckFn *check_fn, void *check_data);
/*.......................................................................
* Return a description of the error that occurred on the last call to
* cf_complete_file().
*
* Input:
* cf CompleteFile * The path-completion resource object.
* Output:
* return char * The description of the last error.
*/
const char *_cf_last_error(CompleteFile *cf);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Standard includes.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
/*
* Local includes.
*/
#include "libtecla.h"
#include "ioutil.h"
#include "stringrp.h"
#include "pathutil.h"
#include "cplfile.h"
#include "cplmatch.h"
#include "errmsg.h"
/*
* Specify the number of strings to allocate when the string free-list
* is exhausted. This also sets the number of elements to expand the
* matches[] array by whenever it is found to be too small.
*/
#define STR_BLK_FACT 100
/*
* Set the default number of spaces place between columns when listing
* a set of completions.
*/
#define CPL_COL_SEP 2
/*
* Completion matches are recorded in containers of the following
* type.
*/
struct WordCompletion {
ErrMsg *err; /* The error reporting buffer */
StringGroup *sg; /* Memory for a group of strings */
int matches_dim; /* The allocated size of result.matches[] */
CplMatches result; /* Completions to be returned to the caller */
#ifndef WITHOUT_FILE_SYSTEM
CompleteFile *cf; /* The resources used for filename completion */
#endif
};
static void cpl_sort_matches(WordCompletion *cpl);
static void cpl_zap_duplicates(WordCompletion *cpl);
static void cpl_clear_completions(WordCompletion *cpl);
static int cpl_cmp_matches(const void *v1, const void *v2);
static int cpl_cmp_suffixes(const void *v1, const void *v2);
/*
* The new_CplFileConf() constructor sets the integer first member of
* the returned object to the following magic number. On seeing this,
* cpl_file_completions() knows when it is passed a valid CplFileConf
* object.
*/
#define CFC_ID_CODE 4568
#ifndef WITHOUT_FILE_SYSTEM
/*
* A pointer to a structure of the following type can be passed to
* the builtin file-completion callback function to modify its behavior.
*/
struct CplFileConf {
int id; /* new_CplFileConf() sets this to CFC_ID_CODE */
int escaped; /* If none-zero, backslashes in the input line are */
/* interpreted as escaping special characters and */
/* spaces, and any special characters and spaces in */
/* the listed completions will also be escaped with */
/* added backslashes. This is the default behaviour. */
/* If zero, backslashes are interpreted as being */
/* literal parts of the filename, and none are added */
/* to the completion suffixes. */
int file_start; /* The index in the input line of the first character */
/* of the filename. If you specify -1 here, */
/* cpl_file_completions() identifies the */
/* the start of the filename by looking backwards for */
/* an unescaped space, or the beginning of the line. */
CplCheckFn *chk_fn; /* If not zero, this argument specifies a */
/* function to call to ask whether a given */
/* file should be included in the list */
/* of completions. */
void *chk_data; /* Anonymous data to be passed to check_fn(). */
};
static void cpl_init_FileConf(CplFileConf *cfc);
/*
* When file-system access is being excluded, define a dummy structure
* to satisfy the typedef in libtecla.h.
*/
#else
struct CplFileConf {int dummy;};
#endif
/*
* Encapsulate the formatting information needed to layout a
* multi-column listing of completions.
*/
typedef struct {
int term_width; /* The width of the terminal (characters) */
int column_width; /* The number of characters within in each column. */
int ncol; /* The number of columns needed */
int nline; /* The number of lines needed */
} CplListFormat;
/*
* Given the current terminal width, and a list of completions, determine
* how to best use the terminal width to display a multi-column listing
* of completions.
*/
static void cpl_plan_listing(CplMatches *result, int term_width,
CplListFormat *fmt);
/*
* Display a given line of a multi-column list of completions.
*/
static int cpl_format_line(CplMatches *result, CplListFormat *fmt, int lnum,
GlWriteFn *write_fn, void *data);
/*.......................................................................
* Create a new string-completion object.
*
* Output:
* return WordCompletion * The new object, or NULL on error.
*/
WordCompletion *new_WordCompletion(void)
{
WordCompletion *cpl; /* The object to be returned */
/*
* Allocate the container.
*/
cpl = (WordCompletion *) malloc(sizeof(WordCompletion));
if(!cpl) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_WordCompletion().
*/
cpl->err = NULL;
cpl->sg = NULL;
cpl->matches_dim = 0;
cpl->result.suffix = NULL;
cpl->result.cont_suffix = NULL;
cpl->result.matches = NULL;
cpl->result.nmatch = 0;
#ifndef WITHOUT_FILE_SYSTEM
cpl->cf = NULL;
#endif
/*
* Allocate a place to record error messages.
*/
cpl->err = _new_ErrMsg();
if(!cpl->err)
return del_WordCompletion(cpl);
/*
* Allocate an object that allows a group of strings to be allocated
* efficiently by placing many of them in contiguous string segments.
*/
#ifdef WITHOUT_FILE_SYSTEM
cpl->sg = _new_StringGroup(MAX_PATHLEN_FALLBACK);
#else
cpl->sg = _new_StringGroup(_pu_pathname_dim());
#endif
if(!cpl->sg)
return del_WordCompletion(cpl);
/*
* Allocate an array for matching completions. This will be extended later
* if needed.
*/
cpl->matches_dim = STR_BLK_FACT;
cpl->result.matches = (CplMatch *) malloc(sizeof(cpl->result.matches[0]) *
cpl->matches_dim);
if(!cpl->result.matches) {
errno = ENOMEM;
return del_WordCompletion(cpl);
};
/*
* Allocate a filename-completion resource object.
*/
#ifndef WITHOUT_FILE_SYSTEM
cpl->cf = _new_CompleteFile();
if(!cpl->cf)
return del_WordCompletion(cpl);
#endif
return cpl;
}
/*.......................................................................
* Delete a string-completion object.
*
* Input:
* cpl WordCompletion * The object to be deleted.
* Output:
* return WordCompletion * The deleted object (always NULL).
*/
WordCompletion *del_WordCompletion(WordCompletion *cpl)
{
if(cpl) {
cpl->err = _del_ErrMsg(cpl->err);
cpl->sg = _del_StringGroup(cpl->sg);
if(cpl->result.matches) {
free(cpl->result.matches);
cpl->result.matches = NULL;
#ifndef WITHOUT_FILE_SYSTEM
cpl->cf = _del_CompleteFile(cpl->cf);
#endif
};
free(cpl);
};
return NULL;
}
/*.......................................................................
* This function is designed to be called by CplMatchFn callback
* functions. It adds one possible completion of the token that is being
* completed to an array of completions. If the completion needs any
* special quoting to be valid when displayed in the input line, this
* quoting must be included in the string.
*
* Input:
* cpl WordCompletion * The argument of the same name that was passed
* to the calling CplMatchFn callback function.
* line const char * The input line, as received by the callback
* function.
* word_start int The index within line[] of the start of the
* word that is being completed.
* word_end int The index within line[] of the character which
* follows the incomplete word, as received by the
* calling callback function.
* suffix const char * The appropriately quoted string that could
* be appended to the incomplete token to complete
* it. A copy of this string will be allocated
* internally.
* type_suffix const char * When listing multiple completions, gl_get_line()
* appends this string to the completion to indicate
* its type to the user. If not pertinent pass "".
* Otherwise pass a literal or static string.
* cont_suffix const char * If this turns out to be the only completion,
* gl_get_line() will append this string as
* a continuation. For example, the builtin
* file-completion callback registers a directory
* separator here for directory matches, and a
* space otherwise. If the match were a function
* name you might want to append an open
* parenthesis, etc.. If not relevant pass "".
* Otherwise pass a literal or static string.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int cpl_add_completion(WordCompletion *cpl, const char *line,
int word_start, int word_end, const char *suffix,
const char *type_suffix, const char *cont_suffix)
{
CplMatch *match; /* The container of the new match */
char *string; /* A newly allocated copy of the completion string */
size_t len;
/*
* Check the arguments.
*/
if(!cpl)
return 1;
if(!suffix)
return 0;
if(!type_suffix)
type_suffix = "";
if(!cont_suffix)
cont_suffix = "";
/*
* Do we need to extend the array of matches[]?
*/
if(cpl->result.nmatch+1 > cpl->matches_dim) {
int needed = cpl->matches_dim + STR_BLK_FACT;
CplMatch *matches = (CplMatch *) realloc(cpl->result.matches,
sizeof(cpl->result.matches[0]) * needed);
if(!matches) {
_err_record_msg(cpl->err,
"Insufficient memory to extend array of matches.",
END_ERR_MSG);
return 1;
};
cpl->result.matches = matches;
cpl->matches_dim = needed;
};
/*
* Allocate memory to store the combined completion prefix and the
* new suffix.
*/
len = strlen(suffix);
string = _sg_alloc_string(cpl->sg, word_end-word_start + len);
if(!string) {
_err_record_msg(cpl->err, "Insufficient memory to extend array of matches.",
END_ERR_MSG);
return 1;
};
/*
* Compose the string.
*/
strncpy(string, line + word_start, word_end - word_start);
strlcpy(string + word_end - word_start, suffix, len + 1);
/*
* Record the new match.
*/
match = cpl->result.matches + cpl->result.nmatch++;
match->completion = string;
match->suffix = string + word_end - word_start;
match->type_suffix = type_suffix;
/*
* Record the continuation suffix.
*/
cpl->result.cont_suffix = cont_suffix;
return 0;
}
/*.......................................................................
* Sort the array of matches.
*
* Input:
* cpl WordCompletion * The completion resource object.
*/
static void cpl_sort_matches(WordCompletion *cpl)
{
qsort(cpl->result.matches, cpl->result.nmatch,
sizeof(cpl->result.matches[0]), cpl_cmp_matches);
}
/*.......................................................................
* This is a qsort() comparison function used to sort matches.
*
* Input:
* v1, v2 void * Pointers to the two matches to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int cpl_cmp_matches(const void *v1, const void *v2)
{
const CplMatch *m1 = (const CplMatch *) v1;
const CplMatch *m2 = (const CplMatch *) v2;
return strcmp(m1->completion, m2->completion);
}
/*.......................................................................
* Sort the array of matches in order of their suffixes.
*
* Input:
* cpl WordCompletion * The completion resource object.
*/
static void cpl_sort_suffixes(WordCompletion *cpl)
{
qsort(cpl->result.matches, cpl->result.nmatch,
sizeof(cpl->result.matches[0]), cpl_cmp_suffixes);
}
/*.......................................................................
* This is a qsort() comparison function used to sort matches in order of
* their suffixes.
*
* Input:
* v1, v2 void * Pointers to the two matches to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int cpl_cmp_suffixes(const void *v1, const void *v2)
{
const CplMatch *m1 = (const CplMatch *) v1;
const CplMatch *m2 = (const CplMatch *) v2;
return strcmp(m1->suffix, m2->suffix);
}
/*.......................................................................
* Find the common prefix of all of the matching completion matches,
* and record a pointer to it in cpl->result.suffix. Note that this has
* the side effect of sorting the matches into suffix order.
*
* Input:
* cpl WordCompletion * The completion resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int cpl_common_suffix(WordCompletion *cpl)
{
CplMatches *result; /* The result container */
const char *first, *last; /* The first and last matching suffixes */
int length; /* The length of the common suffix */
/*
* Get the container of the array of matching files.
*/
result = &cpl->result;
/*
* No matching completions?
*/
if(result->nmatch < 1)
return 0;
/*
* Sort th matches into suffix order.
*/
cpl_sort_suffixes(cpl);
/*
* Given that the array of matches is sorted, the first and last
* suffixes are those that differ most in their prefixes, so the common
* prefix of these strings is the longest common prefix of all of the
* suffixes.
*/
first = result->matches[0].suffix;
last = result->matches[result->nmatch - 1].suffix;
/*
* Find the point at which the first and last matching strings
* first difffer.
*/
while(*first && *first == *last) {
first++;
last++;
};
/*
* How long is the common suffix?
*/
length = first - result->matches[0].suffix;
/*
* Allocate memory to record the common suffix.
*/
result->suffix = _sg_alloc_string(cpl->sg, length);
if(!result->suffix) {
_err_record_msg(cpl->err,
"Insufficient memory to record common completion suffix.",
END_ERR_MSG);
return 1;
};
/*
* Record the common suffix.
*/
strncpy(result->suffix, result->matches[0].suffix, length);
result->suffix[length] = '\0';
return 0;
}
/*.......................................................................
* Discard the contents of the array of possible completion matches.
*
* Input:
* cpl WordCompletion * The word-completion resource object.
*/
static void cpl_clear_completions(WordCompletion *cpl)
{
/*
* Discard all of the strings.
*/
_clr_StringGroup(cpl->sg);
/*
* Record the fact that the array is now empty.
*/
cpl->result.nmatch = 0;
cpl->result.suffix = NULL;
cpl->result.cont_suffix = "";
/*
* Also clear the error message.
*/
_err_clear_msg(cpl->err);
return;
}
/*.......................................................................
* Given an input line and the point at which it completion is to be
* attempted, return an array of possible completions.
*
* Input:
* cpl WordCompletion * The completion resource object.
* line char * The current input line.
* word_end int The index of the character in line[] which
* follows the end of the token that is being
* completed.
* data void * Anonymous 'data' to be passed to match_fn().
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* record completion matches.
* Output:
* return CplMatches * The container of the array of possible
* completions. The returned pointer refers
* to a container owned by the parent WordCompletion
* object, and its contents thus potentially
* change on every call to cpl_matches().
* On error, NULL is returned, and a description
* of the error can be acquired by calling
* cpl_last_error(cpl).
*/
CplMatches *cpl_complete_word(WordCompletion *cpl, const char *line,
int word_end, void *data,
CplMatchFn *match_fn)
{
int line_len; /* The total length of the input line */
/*
* How long is the input line?
*/
line_len = strlen(line);
/*
* Check the arguments.
*/
if(!cpl || !line || !match_fn || word_end < 0 || word_end > line_len) {
if(cpl) {
_err_record_msg(cpl->err, "cpl_complete_word: Invalid arguments.",
END_ERR_MSG);
};
return NULL;
};
/*
* Clear the return container.
*/
cpl_clear_completions(cpl);
/*
* Have the matching function record possible completion matches in
* cpl->result.matches.
*/
if(match_fn(cpl, data, line, word_end)) {
if(_err_get_msg(cpl->err)[0] == '\0')
_err_record_msg(cpl->err, "Error completing word.", END_ERR_MSG);
return NULL;
};
/*
* Record a copy of the common initial part of all of the prefixes
* in cpl->result.common.
*/
if(cpl_common_suffix(cpl))
return NULL;
/*
* Sort the matches into lexicographic order.
*/
cpl_sort_matches(cpl);
/*
* Discard any duplicate matches.
*/
cpl_zap_duplicates(cpl);
/*
* If there is more than one match, discard the continuation suffix.
*/
if(cpl->result.nmatch > 1)
cpl->result.cont_suffix = "";
/*
* Return the array of matches.
*/
return &cpl->result;
}
/*.......................................................................
* Recall the return value of the last call to cpl_complete_word().
*
* Input:
* cpl WordCompletion * The completion resource object.
* Output:
* return CplMatches * The container of the array of possible
* completions, as returned by the last call to
* cpl_complete_word(). The returned pointer refers
* to a container owned by the parent WordCompletion
* object, and its contents thus potentially
* change on every call to cpl_complete_word().
* On error, either in the execution of this
* function, or in the last call to
* cpl_complete_word(), NULL is returned, and a
* description of the error can be acquired by
* calling cpl_last_error(cpl).
*/
CplMatches *cpl_recall_matches(WordCompletion *cpl)
{
return (!cpl || *_err_get_msg(cpl->err)!='\0') ? NULL : &cpl->result;
}
/*.......................................................................
* Print out an array of matching completions.
*
* Input:
* result CplMatches * The container of the sorted array of
* completions.
* fp FILE * The output stream to write to.
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int cpl_list_completions(CplMatches *result, FILE *fp, int term_width)
{
return _cpl_output_completions(result, _io_write_stdio, fp, term_width);
}
/*.......................................................................
* Print an array of matching completions via a callback function.
*
* Input:
* result CplMatches * The container of the sorted array of
* completions.
* write_fn GlWriteFn * The function to call to write the completions,
* or 0 to discard the output.
* data void * Anonymous data to pass to write_fn().
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _cpl_output_completions(CplMatches *result, GlWriteFn *write_fn, void *data,
int term_width)
{
CplListFormat fmt; /* List formatting information */
int lnum; /* The sequential number of the line to print next */
/*
* Not enough space to list anything?
*/
if(term_width < 1)
return 0;
/*
* Do we have a callback to write via, and any completions to be listed?
*/
if(write_fn && result && result->nmatch>0) {
/*
* Work out how to arrange the listing into fixed sized columns.
*/
cpl_plan_listing(result, term_width, &fmt);
/*
* Print the listing via the specified callback.
*/
for(lnum=0; lnum < fmt.nline; lnum++) {
if(cpl_format_line(result, &fmt, lnum, write_fn, data))
return 1;
};
};
return 0;
}
/*.......................................................................
* Return a description of the string-completion error that occurred.
*
* Input:
* cpl WordCompletion * The string-completion resource object.
* Output:
* return const char * The description of the last error.
*/
const char *cpl_last_error(WordCompletion *cpl)
{
return cpl ? _err_get_msg(cpl->err) : "NULL WordCompletion argument";
}
/*.......................................................................
* When an error occurs while performing a completion, you registerf a
* terse description of the error by calling cpl_record_error(). This
* message will then be returned on the next call to cpl_last_error().
*
* Input:
* cpl WordCompletion * The string-completion resource object that was
* originally passed to the callback.
* errmsg const char * The description of the error.
*/
void cpl_record_error(WordCompletion *cpl, const char *errmsg)
{
if(cpl && errmsg)
_err_record_msg(cpl->err, errmsg, END_ERR_MSG);
}
/*.......................................................................
* This is the builtin completion callback function which performs file
* completion.
*
* Input:
* cpl WordCompletion * An opaque pointer to the object that will
* contain the matches. This should be filled
* via zero or more calls to cpl_add_completion().
* data void * Either NULL to request the default
* file-completion behavior, or a pointer to a
* CplFileConf structure, whose members specify
* a different behavior.
* line char * The current input line.
* word_end int The index of the character in line[] which
* follows the end of the token that is being
* completed.
* Output
* return int 0 - OK.
* 1 - Error.
*/
CPL_MATCH_FN(cpl_file_completions)
{
#ifdef WITHOUT_FILE_SYSTEM
return 0;
#else
const char *start_path; /* The pointer to the start of the pathname */
/* in line[]. */
CplFileConf *conf; /* The new-style configuration object. */
/*
* The following configuration object will be used if the caller didn't
* provide one.
*/
CplFileConf default_conf;
/*
* This function can be called externally, so check its arguments.
*/
if(!cpl)
return 1;
if(!line || word_end < 0) {
_err_record_msg(cpl->err, "cpl_file_completions: Invalid arguments.",
END_ERR_MSG);
return 1;
};
/*
* The 'data' argument is either a CplFileConf pointer, identifiable
* by having an integer id code as its first member, or the deprecated
* CplFileArgs pointer, or can be NULL to request the default
* configuration.
*/
if(data && *(int *)data == CFC_ID_CODE) {
conf = (CplFileConf *) data;
} else {
/*
* Select the defaults.
*/
conf = &default_conf;
cpl_init_FileConf(&default_conf);
/*
* If we have been passed an instance of the deprecated CplFileArgs
* structure, copy its configuration parameters over the defaults.
*/
if(data) {
CplFileArgs *args = (CplFileArgs *) data;
conf->escaped = args->escaped;
conf->file_start = args->file_start;
};
};
/*
* Get the start of the filename. If not specified by the caller
* identify it by searching backwards in the input line for an
* unescaped space or the start of the line.
*/
if(conf->file_start < 0) {
start_path = _pu_start_of_path(line, word_end);
if(!start_path) {
_err_record_msg(cpl->err, "Unable to find the start of the filename.",
END_ERR_MSG);
return 1;
};
} else {
start_path = line + conf->file_start;
};
/*
* Perform the completion.
*/
if(_cf_complete_file(cpl, cpl->cf, line, start_path - line, word_end,
conf->escaped, conf->chk_fn, conf->chk_data)) {
cpl_record_error(cpl, _cf_last_error(cpl->cf));
return 1;
};
return 0;
#endif
}
/*.......................................................................
* Initialize a CplFileArgs structure with default configuration
* parameters. Note that the CplFileArgs configuration type is
* deprecated. The opaque CplFileConf object should be used in future
* applications.
*
* Input:
* cfa CplFileArgs * The configuration object of the
* cpl_file_completions() callback.
*/
void cpl_init_FileArgs(CplFileArgs *cfa)
{
if(cfa) {
cfa->escaped = 1;
cfa->file_start = -1;
};
}
#ifndef WITHOUT_FILE_SYSTEM
/*.......................................................................
* Initialize a CplFileConf structure with default configuration
* parameters.
*
* Input:
* cfc CplFileConf * The configuration object of the
* cpl_file_completions() callback.
*/
static void cpl_init_FileConf(CplFileConf *cfc)
{
if(cfc) {
cfc->id = CFC_ID_CODE;
cfc->escaped = 1;
cfc->file_start = -1;
cfc->chk_fn = 0;
cfc->chk_data = NULL;
};
}
#endif
/*.......................................................................
* Create a new CplFileConf object and initialize it with defaults.
*
* Output:
* return CplFileConf * The new object, or NULL on error.
*/
CplFileConf *new_CplFileConf(void)
{
#ifdef WITHOUT_FILE_SYSTEM
errno = EINVAL;
return NULL;
#else
CplFileConf *cfc; /* The object to be returned */
/*
* Allocate the container.
*/
cfc = (CplFileConf *)malloc(sizeof(CplFileConf));
if(!cfc)
return NULL;
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_CplFileConf().
*/
cpl_init_FileConf(cfc);
return cfc;
#endif
}
/*.......................................................................
* Delete a CplFileConf object.
*
* Input:
* cfc CplFileConf * The object to be deleted.
* Output:
* return CplFileConf * The deleted object (always NULL).
*/
CplFileConf *del_CplFileConf(CplFileConf *cfc)
{
#ifndef WITHOUT_FILE_SYSTEM
if(cfc) {
/*
* Delete the container.
*/
free(cfc);
};
#endif
return NULL;
}
/*.......................................................................
* If backslashes in the filename should be treated as literal
* characters, call the following function with literal=1. Otherwise
* the default is to treat them as escape characters, used for escaping
* spaces etc..
*
* Input:
* cfc CplFileConf * The cpl_file_completions() configuration object
* to be configured.
* literal int Pass non-zero here to enable literal interpretation
* of backslashes. Pass 0 to turn off literal
* interpretation.
*/
void cfc_literal_escapes(CplFileConf *cfc, int literal)
{
#ifndef WITHOUT_FILE_SYSTEM
if(cfc)
cfc->escaped = !literal;
#endif
}
/*.......................................................................
* Call this function if you know where the index at which the
* filename prefix starts in the input line. Otherwise by default,
* or if you specify start_index to be -1, the filename is taken
* to start after the first unescaped space preceding the cursor,
* or the start of the line, which ever comes first.
*
* Input:
* cfc CplFileConf * The cpl_file_completions() configuration object
* to be configured.
* start_index int The index of the start of the filename in
* the input line, or -1 to select the default.
*/
void cfc_file_start(CplFileConf *cfc, int start_index)
{
#ifndef WITHOUT_FILE_SYSTEM
if(cfc)
cfc->file_start = start_index;
#endif
}
/*.......................................................................
* If you only want certain types of files to be included in the
* list of completions, you use the following function to specify a
* callback function which will be called to ask whether a given file
* should be included.
*
* Input:
* cfc CplFileConf * The cpl_file_completions() configuration object
* to be configured.
* chk_fn CplCheckFn * Zero to disable filtering, or a pointer to a
* function that returns 1 if a given file should
* be included in the list of completions.
* chk_data void * Anonymous data to be passed to chk_fn()
* every time that it is called.
*/
void cfc_set_check_fn(CplFileConf *cfc, CplCheckFn *chk_fn, void *chk_data)
{
#ifndef WITHOUT_FILE_SYSTEM
if(cfc) {
cfc->chk_fn = chk_fn;
cfc->chk_data = chk_data;
};
#endif
}
/*.......................................................................
* The following CplCheckFn callback returns non-zero if the specified
* filename is that of an executable.
*/
CPL_CHECK_FN(cpl_check_exe)
{
#ifdef WITHOUT_FILE_SYSTEM
return 0;
#else
return _pu_path_is_exe(pathname);
#endif
}
/*.......................................................................
* Remove duplicates from a sorted array of matches.
*
* Input:
* cpl WordCompletion * The completion resource object.
*/
static void cpl_zap_duplicates(WordCompletion *cpl)
{
CplMatch *matches; /* The array of matches */
int nmatch; /* The number of elements in matches[] */
const char *completion; /* The completion string of the last unique match */
const char *type_suffix; /* The type of the last unique match */
int src; /* The index of the match being considered */
int dst; /* The index at which to record the next */
/* unique match. */
/*
* Get the array of matches and the number of matches that it
* contains.
*/
matches = cpl->result.matches;
nmatch = cpl->result.nmatch;
/*
* No matches?
*/
if(nmatch < 1)
return;
/*
* Initialize the comparison strings with the first match.
*/
completion = matches[0].completion;
type_suffix = matches[0].type_suffix;
/*
* Go through the array of matches, copying each new unrecorded
* match at the head of the array, while discarding duplicates.
*/
for(src=dst=1; src<nmatch; src++) {
CplMatch *match = matches + src;
if(strcmp(completion, match->completion) != 0 ||
strcmp(type_suffix, match->type_suffix) != 0) {
if(src != dst)
matches[dst] = *match;
dst++;
completion = match->completion;
type_suffix = match->type_suffix;
};
};
/*
* Record the number of unique matches that remain.
*/
cpl->result.nmatch = dst;
return;
}
/*.......................................................................
* Work out how to arrange a given array of completions into a listing
* of one or more fixed size columns.
*
* Input:
* result CplMatches * The set of completions to be listed.
* term_width int The width of the terminal. A lower limit of
* zero is quietly enforced.
* Input/Output:
* fmt CplListFormat * The formatting information will be assigned
* to the members of *fmt.
*/
static void cpl_plan_listing(CplMatches *result, int term_width,
CplListFormat *fmt)
{
int maxlen; /* The length of the longest matching string */
int i;
/*
* Ensure that term_width >= 0.
*/
if(term_width < 0)
term_width = 0;
/*
* Start by assuming the worst case, that either nothing will fit
* on the screen, or that there are no matches to be listed.
*/
fmt->term_width = term_width;
fmt->column_width = 0;
fmt->nline = fmt->ncol = 0;
/*
* Work out the maximum length of the matching strings.
*/
maxlen = 0;
for(i=0; i<result->nmatch; i++) {
CplMatch *match = result->matches + i;
int len = strlen(match->completion) + strlen(match->type_suffix);
if(len > maxlen)
maxlen = len;
};
/*
* Nothing to list?
*/
if(maxlen == 0)
return;
/*
* Split the available terminal width into columns of
* maxlen + CPL_COL_SEP characters.
*/
fmt->column_width = maxlen;
fmt->ncol = fmt->term_width / (fmt->column_width + CPL_COL_SEP);
/*
* If the column width is greater than the terminal width, zero columns
* will have been selected. Set a lower limit of one column. Leave it
* up to the caller how to deal with completions who's widths exceed
* the available terminal width.
*/
if(fmt->ncol < 1)
fmt->ncol = 1;
/*
* How many lines of output will be needed?
*/
fmt->nline = (result->nmatch + fmt->ncol - 1) / fmt->ncol;
return;
}
/*.......................................................................
* Render one line of a multi-column listing of completions, using a
* callback function to pass the output to an arbitrary destination.
*
* Input:
* result CplMatches * The container of the sorted array of
* completions.
* fmt CplListFormat * Formatting information.
* lnum int The index of the line to print, starting
* from 0, and incrementing until the return
* value indicates that there is nothing more
* to be printed.
* write_fn GlWriteFn * The function to call to write the line, or
* 0 to discard the output.
* data void * Anonymous data to pass to write_fn().
* Output:
* return int 0 - Line printed ok.
* 1 - Nothing to print.
*/
static int cpl_format_line(CplMatches *result, CplListFormat *fmt, int lnum,
GlWriteFn *write_fn, void *data)
{
int col; /* The index of the list column being output */
/*
* If the line index is out of bounds, there is nothing to be written.
*/
if(lnum < 0 || lnum >= fmt->nline)
return 1;
/*
* If no output function has been provided, return as though the
* line had been printed.
*/
if(!write_fn)
return 0;
/*
* Print the matches in 'ncol' columns, sorted in line order within each
* column.
*/
for(col=0; col < fmt->ncol; col++) {
int m = col*fmt->nline + lnum;
/*
* Is there another match to be written? Note that in general
* the last line of a listing will have fewer filled columns
* than the initial lines.
*/
if(m < result->nmatch) {
CplMatch *match = result->matches + m;
/*
* How long are the completion and type-suffix strings?
*/
int clen = strlen(match->completion);
int tlen = strlen(match->type_suffix);
/*
* Write the completion string.
*/
if(write_fn(data, match->completion, clen) != clen)
return 1;
/*
* Write the type suffix, if any.
*/
if(tlen > 0 && write_fn(data, match->type_suffix, tlen) != tlen)
return 1;
/*
* If another column follows the current one, pad to its start with spaces.
*/
if(col+1 < fmt->ncol) {
/*
* The following constant string of spaces is used to pad the output.
*/
static const char spaces[] = " ";
static const int nspace = sizeof(spaces) - 1;
/*
* Pad to the next column, using as few sub-strings of the spaces[]
* array as possible.
*/
int npad = fmt->column_width + CPL_COL_SEP - clen - tlen;
while(npad>0) {
int n = npad > nspace ? nspace : npad;
if(write_fn(data, spaces + nspace - n, n) != n)
return 1;
npad -= n;
};
};
};
};
/*
* Start a new line.
*/
{
char s[] = "\r\n";
int n = strlen(s);
if(write_fn(data, s, n) != n)
return 1;
};
return 0;
}
#ifndef cplmatch_h
#define cplmatch_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* This header is not for use by external applicatons. It contains
* internal immplementation features of the libtecla library, which
* may change incompatibly between releases.
*/
/*
* Display a list of completions via a callback function.
*/
int _cpl_output_completions(CplMatches *result, GlWriteFn *write_fn, void *data,
int term_width);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
/*
* Standard includes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/*
* Operating system includes.
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "direader.h"
#include "errmsg.h"
/*
* Use the reentrant POSIX threads version of readdir()?
*/
#if defined(PREFER_REENTRANT) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L
#define USE_READDIR_R 1
#endif
/*
* Objects of the following type are used to maintain the resources
* needed to read directories.
*/
struct DirReader {
ErrMsg *err; /* The error reporting buffer */
DIR *dir; /* The directory stream (if open, NULL otherwise) */
struct dirent *file; /* The latest directory entry */
#ifdef USE_READDIR_R
struct dirent *buffer; /* A buffer used by the threaded version of */
/* readdir() */
int buffer_dim; /* The allocated size of buffer[] */
#endif
};
static int _dr_path_is_dir(const char *pathname);
/*.......................................................................
* Create a new DirReader object.
*
* Output:
* return DirReader * The new object, or NULL on error.
*/
DirReader *_new_DirReader(void)
{
DirReader *dr; /* The object to be returned */
/*
* Allocate the container.
*/
dr = (DirReader *) malloc(sizeof(DirReader));
if(!dr) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_DirReader().
*/
dr->err = NULL;
dr->dir = NULL;
dr->file = NULL;
#ifdef USE_READDIR_R
dr->buffer = NULL;
dr->buffer_dim = 0;
#endif
/*
* Allocate a place to record error messages.
*/
dr->err = _new_ErrMsg();
if(!dr->err)
return _del_DirReader(dr);
return dr;
}
/*.......................................................................
* Delete a DirReader object.
*
* Input:
* dr DirReader * The object to be deleted.
* Output:
* return DirReader * The deleted object (always NULL).
*/
DirReader *_del_DirReader(DirReader *dr)
{
if(dr) {
_dr_close_dir(dr);
#ifdef USE_READDIR_R
free(dr->buffer);
#endif
dr->err = _del_ErrMsg(dr->err);
free(dr);
};
return NULL;
}
/*.......................................................................
* Open a new directory.
*
* Input:
* dr DirReader * The directory reader resource object.
* path const char * The directory to be opened.
* Input/Output:
* errmsg char ** If an error occurs and errmsg isn't NULL, a
* pointer to an error description will be assigned
* to *errmsg.
* Output:
* return int 0 - OK.
* 1 - Error (see *errmsg for a description).
*/
int _dr_open_dir(DirReader *dr, const char *path, char **errmsg)
{
DIR *dir = NULL; /* The directory stream */
/*
* If a directory is already open, close it first.
*/
(void) _dr_close_dir(dr);
/*
* Is the path a directory?
*/
if(!_dr_path_is_dir(path)) {
if(errmsg) {
_err_record_msg(dr->err, "Can't open directory: ", path, END_ERR_MSG);
*errmsg = _err_get_msg(dr->err);
};
return 1;
};
/*
* Attempt to open the directory.
*/
dir = opendir(path);
if(!dir) {
if(errmsg) {
_err_record_msg(dr->err, "Can't open directory: ", path, END_ERR_MSG);
*errmsg = _err_get_msg(dr->err);
};
return 1;
};
/*
* If using POSIX threads, allocate a buffer for readdir_r().
*/
#ifdef USE_READDIR_R
{
size_t size;
int name_max = pathconf(path, _PC_NAME_MAX);
#ifdef NAME_MAX
if(name_max < 0)
name_max = NAME_MAX;
#endif
if(name_max < 0) {
if(errmsg) {
_err_record_msg(dr->err, "Unable to deduce readdir() buffer size.",
END_ERR_MSG);
*errmsg = _err_get_msg(dr->err);
};
closedir(dir);
return 1;
};
/*
* How big a buffer do we need to allocate?
*/
size = sizeof(struct dirent) + name_max;
/*
* Extend the buffer?
*/
if(size > dr->buffer_dim || !dr->buffer) {
struct dirent *buffer = (struct dirent *) (dr->buffer ?
realloc(dr->buffer, size) :
malloc(size));
if(!buffer) {
if(errmsg) {
_err_record_msg(dr->err, "Insufficient memory for readdir() buffer.",
END_ERR_MSG);
*errmsg = _err_get_msg(dr->err);
};
closedir(dir);
errno = ENOMEM;
return 1;
};
dr->buffer = buffer;
dr->buffer_dim = size;
};
};
#endif
/*
* Record the successfully opened directory.
*/
dr->dir = dir;
return 0;
}
/*.......................................................................
* If the DirReader object is currently contains an open directory,
* close it.
*
* Input:
* dr DirReader * The directory reader resource object.
*/
void _dr_close_dir(DirReader *dr)
{
if(dr && dr->dir) {
closedir(dr->dir);
dr->dir = NULL;
dr->file = NULL;
_err_clear_msg(dr->err);
};
}
/*.......................................................................
* Read the next file from the directory opened with _dr_open_dir().
*
* Input:
* dr DirReader * The directory reader resource object.
* Output:
* return char * The name of the new file, or NULL if we reached
* the end of the directory.
*/
char *_dr_next_file(DirReader *dr)
{
/*
* Are we currently reading a directory?
*/
if(dr->dir) {
/*
* Read the next directory entry.
*/
#ifdef USE_READDIR_R
if(readdir_r(dr->dir, dr->buffer, &dr->file) == 0 && dr->file)
return dr->file->d_name;
#else
dr->file = readdir(dr->dir);
if(dr->file)
return dr->file->d_name;
#endif
};
/*
* When the end of a directory is reached, close it.
*/
_dr_close_dir(dr);
return NULL;
}
/*.......................................................................
* Return 1 if the specified pathname refers to a directory.
*
* Input:
* pathname const char * The path to test.
* Output:
* return int 0 - Not a directory.
* 1 - pathname[] refers to a directory.
*/
static int _dr_path_is_dir(const char *pathname)
{
struct stat statbuf; /* The file-statistics return buffer */
/*
* Look up the file attributes.
*/
if(stat(pathname, &statbuf) < 0)
return 0;
/*
* Is the file a directory?
*/
return S_ISDIR(statbuf.st_mode) != 0;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
#ifndef dirreader_h
#define dirreader_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
typedef struct DirReader DirReader;
DirReader *_new_DirReader(void);
DirReader *_del_DirReader(DirReader *dr);
int _dr_open_dir(DirReader *dr, const char *pathname, char **errmsg);
char *_dr_next_file(DirReader *dr);
void _dr_close_dir(DirReader *dr);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include "errmsg.h"
/*
* Encapsulate the error reporting buffer in an opaque object.
*/
struct ErrMsg {
char msg[ERR_MSG_LEN+1]; /* An error message */
};
/*.......................................................................
* Create a new error-message object.
*
* Output:
* return ErrMsg * The new object, or NULL on error.
*/
ErrMsg *_new_ErrMsg(void)
{
ErrMsg *err; /* The object to be returned */
/*
* Allocate the container.
*/
err = malloc(sizeof(ErrMsg));
if(!err) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_ErrMsg().
*/
err->msg[0] = '\0';
return err;
}
/*.......................................................................
* Delete an error-message object.
*
* Input:
* err ErrMsg * The object to be deleted.
* Output:
* return ErrMsg * The deleted object (always NULL).
*/
ErrMsg *_del_ErrMsg(ErrMsg *err)
{
if(err) {
free(err);
};
return NULL;
}
/*.......................................................................
* Record the concatenation of a list of string arguments in an error
* message object. The last argument must be END_ERR_MSG to terminate
* the argument list.
*
* Input:
* err ErrMsg * The error-message container.
* ... const char * Zero or more strings to be concatenated in buff[].
* ... const char * The last argument must always be END_ERR_MSG to
* terminate the argument list.
*/
void _err_record_msg(ErrMsg *err, ...)
{
va_list ap; /* The variable argument list */
const char *s; /* The string being printed */
size_t msglen = 0; /* The total length of the message */
/*
* Nowhere to record the result?
*/
if(!err) {
errno = EINVAL;
return;
};
/*
* Concatenate the list of argument strings in err->msg[].
*/
va_start(ap, err);
while((s = va_arg(ap, const char *)) != END_ERR_MSG) {
/*
* How much room is left in the output buffer (note that the output
* buffer has ERR_MSG_LEN+1 elements).
*/
int nleft = ERR_MSG_LEN - msglen;
/*
* How long is the next string to be appended?
*/
size_t slen = strlen(s);
/*
* If there is any room left, append as much of the string
* as will fit.
*/
if(nleft > 0) {
int nnew = slen < nleft ? slen : nleft;
strncpy(err->msg + msglen, s, nnew);
msglen += nnew;
};
};
va_end(ap);
/*
* Terminate the message.
*/
err->msg[msglen] = '\0';
return;
}
/*.......................................................................
* Return a pointer to the error message buffer.
*
* Input:
* err ErrMsg * The container of the error message buffer.
* Output:
* return char * The current error message, or NULL if err==NULL.
*/
char *_err_get_msg(ErrMsg *err)
{
return err ? err->msg : NULL;
}
/*.......................................................................
* Replace the current error message with an empty string.
*
* Input:
* err ErrMsg * The container of the error message buffer.
*/
void _err_clear_msg(ErrMsg *err)
{
if(err)
err->msg[0] = '\0';
}
#ifndef errmsg_h
#define errmsg_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Set the longest expected length of an error message (excluding its
* '\0' terminator. Since any message over a nominal terminal width of
* 80 characters is going to look a mess, it makes no sense to support
* huge lengths. Note that many uses of strings declared with this
* macro assume that it will be at least 81, so don't reduce it below
* this limit.
*/
#define ERR_MSG_LEN 128
/*
* Provide an opaque typedef to the error-message object.
*/
typedef struct ErrMsg ErrMsg;
/*
* The following token is used to terminate the argument lists of calls
* to _err_record_msg().
*/
#define END_ERR_MSG ((const char *)0)
/*
* Allocate a new error-message buffer.
*/
ErrMsg *_new_ErrMsg(void);
/*
* Delete an error message buffer.
*/
ErrMsg *_del_ErrMsg(ErrMsg *err);
/*
* Concatenate a list of string arguments into the specified buffer, buff[],
* which has an allocated size of buffdim characters.
* The last argument must be END_ERR_MSG to terminate the argument list.
*/
void _err_record_msg(ErrMsg *err, ...);
/*
* Replace the current error message with an empty string.
*/
void _err_clear_msg(ErrMsg *err);
/*
* Return a pointer to the error message buffer. This is
* a '\0' terminated character array containing ERR_MSG_LEN+1
* elements.
*/
char *_err_get_msg(ErrMsg *err);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "freelist.h"
#include "direader.h"
#include "pathutil.h"
#include "homedir.h"
#include "stringrp.h"
#include "libtecla.h"
#include "ioutil.h"
#include "expand.h"
#include "errmsg.h"
/*
* Specify the number of elements to extend the files[] array by
* when it proves to be too small. This also sets the initial size
* of the array.
*/
#define MATCH_BLK_FACT 256
/*
* A list of directory iterators is maintained using nodes of the
* following form.
*/
typedef struct DirNode DirNode;
struct DirNode {
DirNode *next; /* The next directory in the list */
DirNode *prev; /* The node that precedes this node in the list */
DirReader *dr; /* The directory reader object */
};
typedef struct {
FreeList *mem; /* Memory for DirNode list nodes */
DirNode *head; /* The head of the list of used and unused cache nodes */
DirNode *next; /* The next unused node between head and tail */
DirNode *tail; /* The tail of the list of unused cache nodes */
} DirCache;
/*
* Specify how many directory cache nodes to allocate at a time.
*/
#define DIR_CACHE_BLK 20
/*
* Set the maximum length allowed for usernames.
*/
#define USR_LEN 100
/*
* Set the maximum length allowed for environment variable names.
*/
#define ENV_LEN 100
/*
* Set the default number of spaces place between columns when listing
* a set of expansions.
*/
#define EF_COL_SEP 2
struct ExpandFile {
ErrMsg *err; /* The error reporting buffer */
StringGroup *sg; /* A list of string segments in which */
/* matching filenames are stored. */
DirCache cache; /* The cache of directory reader objects */
PathName *path; /* The pathname being matched */
HomeDir *home; /* Home-directory lookup object */
int files_dim; /* The allocated dimension of result.files[] */
char usrnam[USR_LEN+1]; /* A user name */
char envnam[ENV_LEN+1]; /* An environment variable name */
FileExpansion result; /* The container used to return the results of */
/* expanding a path. */
};
static int ef_record_pathname(ExpandFile *ef, const char *pathname,
int remove_escapes);
static char *ef_cache_pathname(ExpandFile *ef, const char *pathname,
int remove_escapes);
static void ef_clear_files(ExpandFile *ef);
static DirNode *ef_open_dir(ExpandFile *ef, const char *pathname);
static DirNode *ef_close_dir(ExpandFile *ef, DirNode *node);
static char *ef_expand_special(ExpandFile *ef, const char *path, int pathlen);
static int ef_match_relative_pathname(ExpandFile *ef, DirReader *dr,
const char *pattern, int separate);
static int ef_matches_range(int c, const char *pattern, const char **endp);
static int ef_string_matches_pattern(const char *file, const char *pattern,
int xplicit, const char *nextp);
static int ef_cmp_strings(const void *v1, const void *v2);
/*
* Encapsulate the formatting information needed to layout a
* multi-column listing of expansions.
*/
typedef struct {
int term_width; /* The width of the terminal (characters) */
int column_width; /* The number of characters within in each column. */
int ncol; /* The number of columns needed */
int nline; /* The number of lines needed */
} EfListFormat;
/*
* Given the current terminal width, and a list of file expansions,
* determine how to best use the terminal width to display a multi-column
* listing of expansions.
*/
static void ef_plan_listing(FileExpansion *result, int term_width,
EfListFormat *fmt);
/*
* Display a given line of a multi-column list of file-expansions.
*/
static int ef_format_line(FileExpansion *result, EfListFormat *fmt, int lnum,
GlWriteFn *write_fn, void *data);
/*.......................................................................
* Create the resources needed to expand filenames.
*
* Output:
* return ExpandFile * The new object, or NULL on error.
*/
ExpandFile *new_ExpandFile(void)
{
ExpandFile *ef; /* The object to be returned */
/*
* Allocate the container.
*/
ef = (ExpandFile *) malloc(sizeof(ExpandFile));
if(!ef) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_ExpandFile().
*/
ef->err = NULL;
ef->sg = NULL;
ef->cache.mem = NULL;
ef->cache.head = NULL;
ef->cache.next = NULL;
ef->cache.tail = NULL;
ef->path = NULL;
ef->home = NULL;
ef->result.files = NULL;
ef->result.nfile = 0;
ef->usrnam[0] = '\0';
ef->envnam[0] = '\0';
/*
* Allocate a place to record error messages.
*/
ef->err = _new_ErrMsg();
if(!ef->err)
return del_ExpandFile(ef);
/*
* Allocate a list of string segments for storing filenames.
*/
ef->sg = _new_StringGroup(_pu_pathname_dim());
if(!ef->sg)
return del_ExpandFile(ef);
/*
* Allocate a freelist for allocating directory cache nodes.
*/
ef->cache.mem = _new_FreeList(sizeof(DirNode), DIR_CACHE_BLK);
if(!ef->cache.mem)
return del_ExpandFile(ef);
/*
* Allocate a pathname buffer.
*/
ef->path = _new_PathName();
if(!ef->path)
return del_ExpandFile(ef);
/*
* Allocate an object for looking up home-directories.
*/
ef->home = _new_HomeDir();
if(!ef->home)
return del_ExpandFile(ef);
/*
* Allocate an array for files. This will be extended later if needed.
*/
ef->files_dim = MATCH_BLK_FACT;
ef->result.files = (char **) malloc(sizeof(ef->result.files[0]) *
ef->files_dim);
if(!ef->result.files) {
errno = ENOMEM;
return del_ExpandFile(ef);
};
return ef;
}
/*.......................................................................
* Delete a ExpandFile object.
*
* Input:
* ef ExpandFile * The object to be deleted.
* Output:
* return ExpandFile * The deleted object (always NULL).
*/
ExpandFile *del_ExpandFile(ExpandFile *ef)
{
if(ef) {
DirNode *dnode;
/*
* Delete the string segments.
*/
ef->sg = _del_StringGroup(ef->sg);
/*
* Delete the cached directory readers.
*/
for(dnode=ef->cache.head; dnode; dnode=dnode->next)
dnode->dr = _del_DirReader(dnode->dr);
/*
* Delete the memory from which the DirNode list was allocated, thus
* deleting the list at the same time.
*/
ef->cache.mem = _del_FreeList(ef->cache.mem, 1);
ef->cache.head = ef->cache.tail = ef->cache.next = NULL;
/*
* Delete the pathname buffer.
*/
ef->path = _del_PathName(ef->path);
/*
* Delete the home-directory lookup object.
*/
ef->home = _del_HomeDir(ef->home);
/*
* Delete the array of pointers to files.
*/
if(ef->result.files) {
free(ef->result.files);
ef->result.files = NULL;
};
/*
* Delete the error report buffer.
*/
ef->err = _del_ErrMsg(ef->err);
/*
* Delete the container.
*/
free(ef);
};
return NULL;
}
/*.......................................................................
* Expand a pathname, converting ~user/ and ~/ patterns at the start
* of the pathname to the corresponding home directories, replacing
* $envvar with the value of the corresponding environment variable,
* and then, if there are any wildcards, matching these against existing
* filenames.
*
* If no errors occur, a container is returned containing the array of
* files that resulted from the expansion. If there were no wildcards
* in the input pathname, this will contain just the original pathname
* after expansion of ~ and $ expressions. If there were any wildcards,
* then the array will contain the files that matched them. Note that
* if there were any wildcards but no existing files match them, this
* is counted as an error and NULL is returned.
*
* The supported wildcards and their meanings are:
* * - Match any sequence of zero or more characters.
* ? - Match any single character.
* [chars] - Match any single character that appears in 'chars'.
* If 'chars' contains an expression of the form a-b,
* then any character between a and b, including a and b,
* matches. The '-' character looses its special meaning
* as a range specifier when it appears at the start
* of the sequence of characters.
* [^chars] - The same as [chars] except that it matches any single
* character that doesn't appear in 'chars'.
*
* Wildcard expressions are applied to individual filename components.
* They don't match across directory separators. A '.' character at
* the beginning of a filename component must also be matched
* explicitly by a '.' character in the input pathname, since these
* are UNIX's hidden files.
*
* Input:
* ef ExpandFile * The pathname expansion resource object.
* path char * The path name to be expanded.
* pathlen int The length of the suffix of path[] that
* constitutes the filename to be expanded,
* or -1 to specify that the whole of the
* path string should be used. Note that
* regardless of the value of this argument,
* path[] must contain a '\0' terminated
* string, since this function checks that
* pathlen isn't mistakenly too long.
* Output:
* return FileExpansion * A pointer to a container within the given
* ExpandFile object. This contains an array
* of the pathnames that resulted from expanding
* ~ and $ expressions and from matching any
* wildcards, sorted into lexical order.
* This container and its contents will be
* recycled on subsequent calls, so if you need
* to keep the results of two successive runs,
* you will either have to allocate a private
* copy of the array, or use two ExpandFile
* objects.
*
* On error NULL is returned. A description
* of the error can be acquired by calling the
* ef_last_error() function.
*/
FileExpansion *ef_expand_file(ExpandFile *ef, const char *path, int pathlen)
{
DirNode *dnode; /* A directory-reader cache node */
const char *dirname; /* The name of the top level directory of the search */
const char *pptr; /* A pointer into path[] */
int wild; /* True if the path contains any wildcards */
/*
* Check the arguments.
*/
if(!ef || !path) {
if(ef) {
_err_record_msg(ef->err, "ef_expand_file: NULL path argument",
END_ERR_MSG);
};
errno = EINVAL;
return NULL;
};
/*
* If the caller specified that the whole of path[] be matched,
* work out the corresponding length.
*/
if(pathlen < 0 || pathlen > strlen(path))
pathlen = strlen(path);
/*
* Discard previous expansion results.
*/
ef_clear_files(ef);
/*
* Preprocess the path, expanding ~/, ~user/ and $envvar references,
* using ef->path as a work directory and returning a pointer to
* a copy of the resulting pattern in the cache.
*/
path = ef_expand_special(ef, path, pathlen);
if(!path)
return NULL;
/*
* Clear the pathname buffer.
*/
_pn_clear_path(ef->path);
/*
* Does the pathname contain any wildcards?
*/
for(wild=0,pptr=path; !wild && *pptr; pptr++) {
switch(*pptr) {
case '\\': /* Skip escaped characters */
if(pptr[1])
pptr++;
break;
case '*': case '?': case '[': /* A wildcard character? */
wild = 1;
break;
};
};
/*
* If there are no wildcards to match, copy the current expanded
* path into the output array, removing backslash escapes while doing so.
*/
if(!wild) {
if(ef_record_pathname(ef, path, 1))
return NULL;
/*
* Does the filename exist?
*/
ef->result.exists = _pu_file_exists(ef->result.files[0]);
/*
* Match wildcards against existing files.
*/
} else {
/*
* Only existing files that match the pattern will be returned in the
* cache.
*/
ef->result.exists = 1;
/*
* Treat matching of the root-directory as a special case since it
* isn't contained in a directory.
*/
if(strcmp(path, FS_ROOT_DIR) == 0) {
if(ef_record_pathname(ef, FS_ROOT_DIR, 0))
return NULL;
} else {
/*
* What should the top level directory of the search be?
*/
if(strncmp(path, FS_ROOT_DIR, FS_ROOT_DIR_LEN) == 0) {
dirname = FS_ROOT_DIR;
if(!_pn_append_to_path(ef->path, FS_ROOT_DIR, -1, 0)) {
_err_record_msg(ef->err, "Insufficient memory to record path",
END_ERR_MSG);
return NULL;
};
path += FS_ROOT_DIR_LEN;
} else {
dirname = FS_PWD;
};
/*
* Open the top-level directory of the search.
*/
dnode = ef_open_dir(ef, dirname);
if(!dnode)
return NULL;
/*
* Recursively match successive directory components of the path.
*/
if(ef_match_relative_pathname(ef, dnode->dr, path, 0)) {
dnode = ef_close_dir(ef, dnode);
return NULL;
};
/*
* Cleanup.
*/
dnode = ef_close_dir(ef, dnode);
};
/*
* No files matched?
*/
if(ef->result.nfile < 1) {
_err_record_msg(ef->err, "No files match", END_ERR_MSG);
return NULL;
};
/*
* Sort the pathnames that matched.
*/
qsort(ef->result.files, ef->result.nfile, sizeof(ef->result.files[0]),
ef_cmp_strings);
};
/*
* Return the result container.
*/
return &ef->result;
}
/*.......................................................................
* Attempt to recursively match the given pattern with the contents of
* the current directory, descending sub-directories as needed.
*
* Input:
* ef ExpandFile * The pathname expansion resource object.
* dr DirReader * The directory reader object of the directory
* to be searched.
* pattern const char * The pattern to match with files in the current
* directory.
* separate int When appending a filename from the specified
* directory to ef->pathname, insert a directory
* separator between the existing pathname and
* the filename, unless separate is zero.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int ef_match_relative_pathname(ExpandFile *ef, DirReader *dr,
const char *pattern, int separate)
{
const char *nextp; /* The pointer to the character that follows the part */
/* of the pattern that is to be matched with files */
/* in the current directory. */
char *file; /* The name of the file being matched */
int pathlen; /* The length of ef->pathname[] on entry to this */
/* function */
/*
* Record the current length of the pathname string recorded in
* ef->pathname[].
*/
pathlen = strlen(ef->path->name);
/*
* Get a pointer to the character that follows the end of the part of
* the pattern that should be matched to files within the current directory.
* This will either point to a directory separator, or to the '\0' terminator
* of the pattern string.
*/
for(nextp=pattern; *nextp && strncmp(nextp, FS_DIR_SEP, FS_DIR_SEP_LEN) != 0;
nextp++)
;
/*
* Read each file from the directory, attempting to match it to the
* current pattern.
*/
while((file=_dr_next_file(dr)) != NULL) {
/*
* Does the latest file match the pattern up to nextp?
*/
if(ef_string_matches_pattern(file, pattern, file[0]=='.', nextp)) {
/*
* Append the new directory entry to the current matching pathname.
*/
if((separate && _pn_append_to_path(ef->path, FS_DIR_SEP, -1, 0)==NULL) ||
_pn_append_to_path(ef->path, file, -1, 0)==NULL) {
_err_record_msg(ef->err, "Insufficient memory to record path",
END_ERR_MSG);
return 1;
};
/*
* If we have reached the end of the pattern, record the accumulated
* pathname in the list of matching files.
*/
if(*nextp == '\0') {
if(ef_record_pathname(ef, ef->path->name, 0))
return 1;
/*
* If the matching directory entry is a subdirectory, and the
* next character of the pattern is a directory separator,
* recursively call the current function to scan the sub-directory
* for matches.
*/
} else if(_pu_path_is_dir(ef->path->name) &&
strncmp(nextp, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
/*
* If the pattern finishes with the directory separator, then
* record the pathame as matching.
*/
if(nextp[FS_DIR_SEP_LEN] == '\0') {
if(ef_record_pathname(ef, ef->path->name, 0))
return 1;
/*
* Match files within the directory.
*/
} else {
DirNode *subdnode = ef_open_dir(ef, ef->path->name);
if(subdnode) {
if(ef_match_relative_pathname(ef, subdnode->dr,
nextp+FS_DIR_SEP_LEN, 1)) {
subdnode = ef_close_dir(ef, subdnode);
return 1;
};
subdnode = ef_close_dir(ef, subdnode);
};
};
};
/*
* Remove the latest filename from the pathname string, so that
* another matching file can be appended.
*/
ef->path->name[pathlen] = '\0';
};
};
return 0;
}
/*.......................................................................
* Record a new matching filename.
*
* Input:
* ef ExpandFile * The filename-match resource object.
* pathname const char * The pathname to record.
* remove_escapes int If true, remove backslash escapes in the
* recorded copy of the pathname.
* Output:
* return int 0 - OK.
* 1 - Error (ef->err will contain a
* description of the error).
*/
static int ef_record_pathname(ExpandFile *ef, const char *pathname,
int remove_escapes)
{
char *copy; /* The recorded copy of pathname[] */
/*
* Attempt to make a copy of the pathname in the cache.
*/
copy = ef_cache_pathname(ef, pathname, remove_escapes);
if(!copy)
return 1;
/*
* If there isn't room to record a pointer to the recorded pathname in the
* array of files, attempt to extend the array.
*/
if(ef->result.nfile + 1 > ef->files_dim) {
int files_dim = ef->files_dim + MATCH_BLK_FACT;
char **files = (char **) realloc(ef->result.files,
files_dim * sizeof(files[0]));
if(!files) {
_err_record_msg(ef->err,
"Insufficient memory to record all of the matching filenames",
END_ERR_MSG);
errno = ENOMEM;
return 1;
};
ef->result.files = files;
ef->files_dim = files_dim;
};
/*
* Record a pointer to the new match.
*/
ef->result.files[ef->result.nfile++] = copy;
return 0;
}
/*.......................................................................
* Record a pathname in the cache.
*
* Input:
* ef ExpandFile * The filename-match resource object.
* pathname char * The pathname to record.
* remove_escapes int If true, remove backslash escapes in the
* copy of the pathname.
* Output:
* return char * The pointer to the copy of the pathname.
* On error NULL is returned and a description
* of the error is left in ef->err.
*/
static char *ef_cache_pathname(ExpandFile *ef, const char *pathname,
int remove_escapes)
{
char *copy = _sg_store_string(ef->sg, pathname, remove_escapes);
if(!copy)
_err_record_msg(ef->err, "Insufficient memory to store pathname",
END_ERR_MSG);
return copy;
}
/*.......................................................................
* Clear the results of the previous expansion operation, ready for the
* next.
*
* Input:
* ef ExpandFile * The pathname expansion resource object.
*/
static void ef_clear_files(ExpandFile *ef)
{
_clr_StringGroup(ef->sg);
_pn_clear_path(ef->path);
ef->result.exists = 0;
ef->result.nfile = 0;
_err_clear_msg(ef->err);
return;
}
/*.......................................................................
* Get a new directory reader object from the cache.
*
* Input:
* ef ExpandFile * The pathname expansion resource object.
* pathname const char * The pathname of the directory.
* Output:
* return DirNode * The cache entry of the new directory reader,
* or NULL on error. On error, ef->err will
* contain a description of the error.
*/
static DirNode *ef_open_dir(ExpandFile *ef, const char *pathname)
{
char *errmsg = NULL; /* An error message from a called function */
DirNode *node; /* The cache node used */
/*
* Get the directory reader cache.
*/
DirCache *cache = &ef->cache;
/*
* Extend the cache if there are no free cache nodes.
*/
if(!cache->next) {
node = (DirNode *) _new_FreeListNode(cache->mem);
if(!node) {
_err_record_msg(ef->err, "Insufficient memory to open a new directory",
END_ERR_MSG);
return NULL;
};
/*
* Initialize the cache node.
*/
node->next = NULL;
node->prev = NULL;
node->dr = NULL;
/*
* Allocate a directory reader object.
*/
node->dr = _new_DirReader();
if(!node->dr) {
_err_record_msg(ef->err, "Insufficient memory to open a new directory",
END_ERR_MSG);
node = (DirNode *) _del_FreeListNode(cache->mem, node);
return NULL;
};
/*
* Append the node to the cache list.
*/
node->prev = cache->tail;
if(cache->tail)
cache->tail->next = node;
else
cache->head = node;
cache->next = cache->tail = node;
};
/*
* Get the first unused node, but don't remove it from the list yet.
*/
node = cache->next;
/*
* Attempt to open the specified directory.
*/
if(_dr_open_dir(node->dr, pathname, &errmsg)) {
_err_record_msg(ef->err, errmsg, END_ERR_MSG);
return NULL;
};
/*
* Now that we have successfully opened the specified directory,
* remove the cache node from the list, and relink the list around it.
*/
cache->next = node->next;
if(node->prev)
node->prev->next = node->next;
else
cache->head = node->next;
if(node->next)
node->next->prev = node->prev;
else
cache->tail = node->prev;
node->next = node->prev = NULL;
/*
* Return the successfully initialized cache node to the caller.
*/
return node;
}
/*.......................................................................
* Return a directory reader object to the cache, after first closing
* the directory that it was managing.
*
* Input:
* ef ExpandFile * The pathname expansion resource object.
* node DirNode * The cache entry of the directory reader, as returned
* by ef_open_dir().
* Output:
* return DirNode * The deleted DirNode (ie. allways NULL).
*/
static DirNode *ef_close_dir(ExpandFile *ef, DirNode *node)
{
/*
* Get the directory reader cache.
*/
DirCache *cache = &ef->cache;
/*
* Close the directory.
*/
_dr_close_dir(node->dr);
/*
* Return the node to the tail of the cache list.
*/
node->next = NULL;
node->prev = cache->tail;
if(cache->tail)
cache->tail->next = node;
else
cache->head = cache->tail = node;
if(!cache->next)
cache->next = node;
return NULL;
}
/*.......................................................................
* Return non-zero if the specified file name matches a given glob
* pattern.
*
* Input:
* file const char * The file-name component to be matched to the pattern.
* pattern const char * The start of the pattern to match against file[].
* xplicit int If non-zero, the first character must be matched
* explicitly (ie. not with a wildcard).
* nextp const char * The pointer to the the character following the
* end of the pattern in pattern[].
* Output:
* return int 0 - Doesn't match.
* 1 - The file-name string matches the pattern.
*/
static int ef_string_matches_pattern(const char *file, const char *pattern,
int xplicit, const char *nextp)
{
const char *pptr = pattern; /* The pointer used to scan the pattern */
const char *fptr = file; /* The pointer used to scan the filename string */
/*
* Match each character of the pattern in turn.
*/
while(pptr < nextp) {
/*
* Handle the next character of the pattern.
*/
switch(*pptr) {
/*
* A match zero-or-more characters wildcard operator.
*/
case '*':
/*
* Skip the '*' character in the pattern.
*/
pptr++;
/*
* If wildcards aren't allowed, the pattern doesn't match.
*/
if(xplicit)
return 0;
/*
* If the pattern ends with a the '*' wildcard, then the
* rest of the filename matches this.
*/
if(pptr >= nextp)
return 1;
/*
* Using the wildcard to match successively longer sections of
* the remaining characters of the filename, attempt to match
* the tail of the filename against the tail of the pattern.
*/
for( ; *fptr; fptr++) {
if(ef_string_matches_pattern(fptr, pptr, 0, nextp))
return 1;
};
return 0; /* The pattern following the '*' didn't match */
break;
/*
* A match-one-character wildcard operator.
*/
case '?':
/*
* If there is a character to be matched, skip it and advance the
* pattern pointer.
*/
if(!xplicit && *fptr) {
fptr++;
pptr++;
/*
* If we hit the end of the filename string, there is no character
* matching the operator, so the string doesn't match.
*/
} else {
return 0;
};
break;
/*
* A character range operator, with the character ranges enclosed
* in matching square brackets.
*/
case '[':
if(xplicit || !ef_matches_range(*fptr++, ++pptr, &pptr))
return 0;
break;
/*
* A backslash in the pattern prevents the following character as
* being seen as a special character.
*/
case '\\':
pptr++;
/* Note fallthrough to default */
/*
* A normal character to be matched explicitly.
*/
/* FALLTHROUGH */
default:
if(*fptr == *pptr) {
fptr++;
pptr++;
} else {
return 0;
};
break;
};
/*
* After passing the first character, turn off the explicit match
* requirement.
*/
xplicit = 0;
};
/*
* To get here the pattern must have been exhausted. If the filename
* string matched, then the filename string must also have been
* exhausted.
*/
return *fptr == '\0';
}
/*.......................................................................
* Match a character range expression terminated by an unescaped close
* square bracket.
*
* Input:
* c int The character to be matched with the range
* pattern.
* pattern const char * The range pattern to be matched (ie. after the
* initiating '[' character).
* endp const char ** On output a pointer to the character following the
* range expression will be assigned to *endp.
* Output:
* return int 0 - Doesn't match.
* 1 - The character matched.
*/
static int ef_matches_range(int c, const char *pattern, const char **endp)
{
const char *pptr = pattern; /* The pointer used to scan the pattern */
int invert = 0; /* True to invert the sense of the match */
int matched = 0; /* True if the character matched the pattern */
/*
* If the first character is a caret, the sense of the match is
* inverted and only if the character isn't one of those in the
* range, do we say that it matches.
*/
if(*pptr == '^') {
pptr++;
invert = 1;
};
/*
* The hyphen is only a special character when it follows the first
* character of the range (not including the caret).
*/
if(*pptr == '-') {
pptr++;
if(c == '-') {
*endp = pptr;
matched = 1;
};
/*
* Skip other leading '-' characters since they make no sense.
*/
while(*pptr == '-')
pptr++;
};
/*
* The hyphen is only a special character when it follows the first
* character of the range (not including the caret or a hyphen).
*/
if(*pptr == ']') {
pptr++;
if(c == ']') {
*endp = pptr;
matched = 1;
};
};
/*
* Having dealt with the characters that have special meanings at
* the beginning of a character range expression, see if the
* character matches any of the remaining characters of the range,
* up until a terminating ']' character is seen.
*/
while(!matched && *pptr && *pptr != ']') {
/*
* Is this a range of characters signaled by the two end characters
* separated by a hyphen?
*/
if(*pptr == '-') {
if(pptr[1] != ']') {
if(c >= pptr[-1] && c <= pptr[1])
matched = 1;
pptr += 2;
};
/*
* A normal character to be compared directly.
*/
} else if(*pptr++ == c) {
matched = 1;
};
};
/*
* Find the terminating ']'.
*/
while(*pptr && *pptr != ']')
pptr++;
/*
* Did we find a terminating ']'?
*/
if(*pptr == ']') {
*endp = pptr + 1;
return matched ? !invert : invert;
};
/*
* If the pattern didn't end with a ']' then it doesn't match, regardless
* of the value of the required sense of the match.
*/
*endp = pptr;
return 0;
}
/*.......................................................................
* This is a qsort() comparison function used to sort strings.
*
* Input:
* v1, v2 void * Pointers to the two strings to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int ef_cmp_strings(const void *v1, const void *v2)
{
char * const *s1 = (char * const *) v1;
char * const *s2 = (char * const *) v2;
return strcmp(*s1, *s2);
}
/*.......................................................................
* Preprocess a path, expanding ~/, ~user/ and $envvar references, using
* ef->path as a work buffer, then copy the result into a cache entry,
* and return a pointer to this copy.
*
* Input:
* ef ExpandFile * The resource object of the file matcher.
* pathlen int The length of the prefix of path[] to be expanded.
* Output:
* return char * A pointer to a copy of the output path in the
* cache. On error NULL is returned, and a description
* of the error is left in ef->err.
*/
static char *ef_expand_special(ExpandFile *ef, const char *path, int pathlen)
{
int spos; /* The index of the start of the path segment that needs */
/* to be copied from path[] to the output pathname. */
int ppos; /* The index of a character in path[] */
char *pptr; /* A pointer into the output path */
int escaped; /* True if the previous character was a '\' */
int i;
/*
* Clear the pathname buffer.
*/
_pn_clear_path(ef->path);
/*
* We need to perform two passes, one to expand environment variables
* and a second to do tilde expansion. This caters for the case
* where an initial dollar expansion yields a tilde expression.
*/
escaped = 0;
for(spos=ppos=0; ppos < pathlen; ppos++) {
int c = path[ppos];
if(escaped) {
escaped = 0;
} else if(c == '\\') {
escaped = 1;
} else if(c == '$') {
int envlen; /* The length of the environment variable */
char *value; /* The value of the environment variable */
/*
* Record the preceding unrecorded part of the pathname.
*/
if(spos < ppos && _pn_append_to_path(ef->path, path + spos, ppos-spos, 0)
== NULL) {
_err_record_msg(ef->err, "Insufficient memory to expand path",
END_ERR_MSG);
return NULL;
};
/*
* Skip the dollar.
*/
ppos++;
/*
* Copy the environment variable name that follows the dollar into
* ef->envnam[], stopping if a directory separator or end of string
* is seen.
*/
for(envlen=0; envlen<ENV_LEN && ppos < pathlen &&
strncmp(path + ppos, FS_DIR_SEP, FS_DIR_SEP_LEN); envlen++)
ef->envnam[envlen] = path[ppos++];
/*
* If the username overflowed the buffer, treat it as invalid (note that
* on most unix systems only 8 characters are allowed in a username,
* whereas our ENV_LEN is much bigger than that.
*/
if(envlen >= ENV_LEN) {
_err_record_msg(ef->err, "Environment variable name too long",
END_ERR_MSG);
return NULL;
};
/*
* Terminate the environment variable name.
*/
ef->envnam[envlen] = '\0';
/*
* Lookup the value of the environment variable.
*/
value = getenv(ef->envnam);
if(!value) {
_err_record_msg(ef->err, "No expansion found for: $", ef->envnam,
END_ERR_MSG);
return NULL;
};
/*
* Copy the value of the environment variable into the output pathname.
*/
if(_pn_append_to_path(ef->path, value, -1, 0) == NULL) {
_err_record_msg(ef->err, "Insufficient memory to expand path",
END_ERR_MSG);
return NULL;
};
/*
* Record the start of the uncopied tail of the input pathname.
*/
spos = ppos;
};
};
/*
* Record the uncopied tail of the pathname.
*/
if(spos < ppos && _pn_append_to_path(ef->path, path + spos, ppos-spos, 0)
== NULL) {
_err_record_msg(ef->err, "Insufficient memory to expand path", END_ERR_MSG);
return NULL;
};
/*
* If the first character of the resulting pathname is a tilde,
* then attempt to substitute the home directory of the specified user.
*/
pptr = ef->path->name;
if(*pptr == '~' && path[0] != '\\') {
int usrlen; /* The length of the username following the tilde */
const char *homedir; /* The home directory of the user */
int homelen; /* The length of the home directory string */
int plen; /* The current length of the path */
int skip=0; /* The number of characters to skip after the ~user */
/*
* Get the current length of the output path.
*/
plen = strlen(ef->path->name);
/*
* Skip the tilde.
*/
pptr++;
/*
* Copy the optional username that follows the tilde into ef->usrnam[].
*/
for(usrlen=0; usrlen<USR_LEN && *pptr &&
strncmp(pptr, FS_DIR_SEP, FS_DIR_SEP_LEN); usrlen++)
ef->usrnam[usrlen] = *pptr++;
/*
* If the username overflowed the buffer, treat it as invalid (note that
* on most unix systems only 8 characters are allowed in a username,
* whereas our USR_LEN is much bigger than that.
*/
if(usrlen >= USR_LEN) {
_err_record_msg(ef->err, "Username too long", END_ERR_MSG);
return NULL;
};
/*
* Terminate the username string.
*/
ef->usrnam[usrlen] = '\0';
/*
* Lookup the home directory of the user.
*/
homedir = _hd_lookup_home_dir(ef->home, ef->usrnam);
if(!homedir) {
_err_record_msg(ef->err, _hd_last_home_dir_error(ef->home), END_ERR_MSG);
return NULL;
};
homelen = strlen(homedir);
/*
* ~user and ~ are usually followed by a directory separator to
* separate them from the file contained in the home directory.
* If the home directory is the root directory, then we don't want
* to follow the home directory by a directory separator, so we must
* erase it.
*/
if(strcmp(homedir, FS_ROOT_DIR) == 0 &&
strncmp(pptr, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
skip = FS_DIR_SEP_LEN;
};
/*
* If needed, increase the size of the pathname buffer to allow it
* to accomodate the home directory instead of the tilde expression.
* Note that pptr may not be valid after this call.
*/
if(_pn_resize_path(ef->path, plen - usrlen - 1 - skip + homelen)==NULL) {
_err_record_msg(ef->err, "Insufficient memory to expand filename",
END_ERR_MSG);
return NULL;
};
/*
* Move the part of the pathname that follows the tilde expression to
* the end of where the home directory will need to be inserted.
*/
memmove(ef->path->name + homelen,
ef->path->name + 1 + usrlen + skip, plen - usrlen - 1 - skip+1);
/*
* Write the home directory at the beginning of the string.
*/
for(i=0; i<homelen; i++)
ef->path->name[i] = homedir[i];
};
/*
* Copy the result into the cache, and return a pointer to the copy.
*/
return ef_cache_pathname(ef, ef->path->name, 0);
}
/*.......................................................................
* Return a description of the last path-expansion error that occurred.
*
* Input:
* ef ExpandFile * The path-expansion resource object.
* Output:
* return char * The description of the last error.
*/
const char *ef_last_error(ExpandFile *ef)
{
return ef ? _err_get_msg(ef->err) : "NULL ExpandFile argument";
}
/*.......................................................................
* Print out an array of matching files.
*
* Input:
* result FileExpansion * The container of the sorted array of
* expansions.
* fp FILE * The output stream to write to.
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int ef_list_expansions(FileExpansion *result, FILE *fp, int term_width)
{
return _ef_output_expansions(result, _io_write_stdio, fp, term_width);
}
/*.......................................................................
* Print out an array of matching files via a callback.
*
* Input:
* result FileExpansion * The container of the sorted array of
* expansions.
* write_fn GlWriteFn * The function to call to write the
* expansions or 0 to discard the output.
* data void * Anonymous data to pass to write_fn().
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _ef_output_expansions(FileExpansion *result, GlWriteFn *write_fn,
void *data, int term_width)
{
EfListFormat fmt; /* List formatting information */
int lnum; /* The sequential number of the line to print next */
/*
* Not enough space to list anything?
*/
if(term_width < 1)
return 0;
/*
* Do we have a callback to write via, and any expansions to be listed?
*/
if(write_fn && result && result->nfile>0) {
/*
* Work out how to arrange the listing into fixed sized columns.
*/
ef_plan_listing(result, term_width, &fmt);
/*
* Print the listing to the specified stream.
*/
for(lnum=0; lnum < fmt.nline; lnum++) {
if(ef_format_line(result, &fmt, lnum, write_fn, data))
return 1;
};
};
return 0;
}
/*.......................................................................
* Work out how to arrange a given array of completions into a listing
* of one or more fixed size columns.
*
* Input:
* result FileExpansion * The set of completions to be listed.
* term_width int The width of the terminal. A lower limit of
* zero is quietly enforced.
* Input/Output:
* fmt EfListFormat * The formatting information will be assigned
* to the members of *fmt.
*/
static void ef_plan_listing(FileExpansion *result, int term_width,
EfListFormat *fmt)
{
int maxlen; /* The length of the longest matching string */
int i;
/*
* Ensure that term_width >= 0.
*/
if(term_width < 0)
term_width = 0;
/*
* Start by assuming the worst case, that either nothing will fit
* on the screen, or that there are no matches to be listed.
*/
fmt->term_width = term_width;
fmt->column_width = 0;
fmt->nline = fmt->ncol = 0;
/*
* Work out the maximum length of the matching strings.
*/
maxlen = 0;
for(i=0; i<result->nfile; i++) {
int len = strlen(result->files[i]);
if(len > maxlen)
maxlen = len;
};
/*
* Nothing to list?
*/
if(maxlen == 0)
return;
/*
* Split the available terminal width into columns of
* maxlen + EF_COL_SEP characters.
*/
fmt->column_width = maxlen;
fmt->ncol = fmt->term_width / (fmt->column_width + EF_COL_SEP);
/*
* If the column width is greater than the terminal width, zero columns
* will have been selected. Set a lower limit of one column. Leave it
* up to the caller how to deal with completions who's widths exceed
* the available terminal width.
*/
if(fmt->ncol < 1)
fmt->ncol = 1;
/*
* How many lines of output will be needed?
*/
fmt->nline = (result->nfile + fmt->ncol - 1) / fmt->ncol;
return;
}
/*.......................................................................
* Render one line of a multi-column listing of completions, using a
* callback function to pass the output to an arbitrary destination.
*
* Input:
* result FileExpansion * The container of the sorted array of
* completions.
* fmt EfListFormat * Formatting information.
* lnum int The index of the line to print, starting
* from 0, and incrementing until the return
* value indicates that there is nothing more
* to be printed.
* write_fn GlWriteFn * The function to call to write the line, or
* 0 to discard the output.
* data void * Anonymous data to pass to write_fn().
* Output:
* return int 0 - Line printed ok.
* 1 - Nothing to print.
*/
static int ef_format_line(FileExpansion *result, EfListFormat *fmt, int lnum,
GlWriteFn *write_fn, void *data)
{
int col; /* The index of the list column being output */
/*
* If the line index is out of bounds, there is nothing to be written.
*/
if(lnum < 0 || lnum >= fmt->nline)
return 1;
/*
* If no output function has been provided, return as though the line
* had been printed.
*/
if(!write_fn)
return 0;
/*
* Print the matches in 'ncol' columns, sorted in line order within each
* column.
*/
for(col=0; col < fmt->ncol; col++) {
int m = col*fmt->nline + lnum;
/*
* Is there another match to be written? Note that in general
* the last line of a listing will have fewer filled columns
* than the initial lines.
*/
if(m < result->nfile) {
char *file = result->files[m];
/*
* How long are the completion and type-suffix strings?
*/
int flen = strlen(file);
/*
* Write the completion string.
*/
if(write_fn(data, file, flen) != flen)
return 1;
/*
* If another column follows the current one, pad to its start with spaces.
*/
if(col+1 < fmt->ncol) {
/*
* The following constant string of spaces is used to pad the output.
*/
static const char spaces[] = " ";
static const int nspace = sizeof(spaces) - 1;
/*
* Pad to the next column, using as few sub-strings of the spaces[]
* array as possible.
*/
int npad = fmt->column_width + EF_COL_SEP - flen;
while(npad>0) {
int n = npad > nspace ? nspace : npad;
if(write_fn(data, spaces + nspace - n, n) != n)
return 1;
npad -= n;
};
};
};
};
/*
* Start a new line.
*/
{
char s[] = "\r\n";
int n = strlen(s);
if(write_fn(data, s, n) != n)
return 1;
};
return 0;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
#ifndef expand_h
#define expand_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* This header is not for use by external applicatons. It contains
* internal immplementation features of the libtecla library, which
* may change incompatibly between releases.
*/
/*
* Print a list of expansions via a callback function.
*/
int _ef_output_expansions(FileExpansion *result, GlWriteFn *write_fn,
void *data, int term_width);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "freelist.h"
typedef struct FreeListBlock FreeListBlock;
struct FreeListBlock {
FreeListBlock *next; /* The next block in the list */
char *nodes; /* The array of free-list nodes */
};
struct FreeList {
size_t node_size; /* The size of a free-list node */
unsigned blocking_factor; /* The number of nodes per block */
long nbusy; /* The number of nodes that are in use */
long ntotal; /* The total number of nodes in the free list */
FreeListBlock *block; /* The head of the list of free-list blocks */
void *free_list; /* The free-list of nodes */
};
static FreeListBlock *_new_FreeListBlock(FreeList *fl);
static FreeListBlock *_del_FreeListBlock(FreeListBlock *fl);
static void _thread_FreeListBlock(FreeList *fl, FreeListBlock *block);
/*.......................................................................
* Allocate a new free-list from blocks of 'blocking_factor' objects of size
* node_size.
*
* Input:
* node_size size_t The size of the free-list nodes to be returned
* by _new_FreeListNode(). Use sizeof() to
* determine this.
* blocking_factor unsigned The number of objects of size 'object_size'
* to allocate per block.
* Output:
* return FreeList * The new freelist, or NULL on error.
*/
FreeList *_new_FreeList(size_t node_size, unsigned blocking_factor)
{
FreeList *fl; /* The new free-list container */
/*
* When a free-list node is on the free-list, it is used as a (void *)
* link field. Roundup node_size to a mulitple of the size of a void
* pointer. This, plus the fact that the array of nodes is obtained via
* malloc, which returns memory suitably aligned for any object, will
* ensure that the first sizeof(void *) bytes of each node will be
* suitably aligned to use as a (void *) link pointer.
*/
node_size = sizeof(void *) *
((node_size + sizeof(void *) - 1) / sizeof(void *));
/*
* Enfore a minimum block size.
*/
if(blocking_factor < 1)
blocking_factor = 1;
/*
* Allocate the container of the free list.
*/
fl = (FreeList *) malloc(sizeof(FreeList));
if(!fl) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_FreeList().
*/
fl->node_size = node_size;
fl->blocking_factor = blocking_factor;
fl->nbusy = 0;
fl->ntotal = 0;
fl->block = NULL;
fl->free_list = NULL;
/*
* Allocate the first block of memory.
*/
fl->block = _new_FreeListBlock(fl);
if(!fl->block) {
errno = ENOMEM;
return _del_FreeList(fl, 1);
};
/*
* Add the new list of nodes to the free-list.
*/
fl->free_list = fl->block->nodes;
/*
* Return the free-list for use.
*/
return fl;
}
/*.......................................................................
* Re-thread a freelist to reclaim all allocated nodes.
* This function should not be called unless if it is known that none
* of the currently allocated nodes are still being used.
*
* Input:
* fl FreeList * The free-list to be reset, or NULL.
*/
void _rst_FreeList(FreeList *fl)
{
if(fl) {
FreeListBlock *block;
/*
* Re-thread the nodes of each block into individual free-lists.
*/
for(block=fl->block; block; block=block->next)
_thread_FreeListBlock(fl, block);
/*
* Link all of the block freelists into one large freelist.
*/
fl->free_list = NULL;
for(block=fl->block; block; block=block->next) {
/*
* Locate the last node of the current block.
*/
char *last_node = block->nodes + fl->node_size *
(fl->blocking_factor - 1);
/*
* Make the link-field of the last node point to the first
* node of the current freelist, then make the first node of the
* new block the start of the freelist.
*/
*(void **)last_node = fl->free_list;
fl->free_list = block->nodes;
};
/*
* All allocated nodes have now been returned to the freelist.
*/
fl->nbusy = 0;
};
}
/*.......................................................................
* Delete a free-list.
*
* Input:
* fl FreeList * The free-list to be deleted, or NULL.
* force int If force==0 then _del_FreeList() will complain
* and refuse to delete the free-list if any
* of nodes have not been returned to the free-list.
* If force!=0 then _del_FreeList() will not check
* whether any nodes are still in use and will
* always delete the list.
* Output:
* return FreeList * Always NULL (even if the list couldn't be
* deleted).
*/
FreeList *_del_FreeList(FreeList *fl, int force)
{
if(fl) {
/*
* Check whether any nodes are in use.
*/
if(!force && _busy_FreeListNodes(fl) != 0) {
errno = EBUSY;
return NULL;
};
/*
* Delete the list blocks.
*/
{
FreeListBlock *next = fl->block;
while(next) {
FreeListBlock *block = next;
next = block->next;
block = _del_FreeListBlock(block);
};
};
fl->block = NULL;
fl->free_list = NULL;
/*
* Discard the container.
*/
free(fl);
};
return NULL;
}
/*.......................................................................
* Allocate a new object from a free-list.
*
* Input:
* fl FreeList * The free-list to return an object from.
* Output:
* return void * A new object of the size that was specified via
* the node_size argument of _new_FreeList() when
* the free-list was created, or NULL if there
* is insufficient memory, or 'fl' is NULL.
*/
void *_new_FreeListNode(FreeList *fl)
{
void *node; /* The node to be returned */
/*
* Check arguments.
*/
if(!fl)
return NULL;
/*
* If the free-list has been exhausted extend it by allocating
* another block of nodes.
*/
if(!fl->free_list) {
FreeListBlock *block = _new_FreeListBlock(fl);
if(!block)
return NULL;
/*
* Prepend the new block to the list of free-list blocks.
*/
block->next = fl->block;
fl->block = block;
/*
* Add the new list of nodes to the free-list.
*/
fl->free_list = fl->block->nodes;
};
/*
* Remove and return a node from the front of the free list.
*/
node = fl->free_list;
fl->free_list = *(void **)node;
/*
* Record the loss of a node from the free-list.
*/
fl->nbusy++;
/*
* Return the node.
*/
return node;
}
/*.......................................................................
* Return an object to the free-list that it was allocated from.
*
* Input:
* fl FreeList * The free-list from which the object was taken.
* object void * The node to be returned.
* Output:
* return void * Always NULL.
*/
void *_del_FreeListNode(FreeList *fl, void *object)
{
/*
* Check arguments.
*/
if(!fl)
return NULL;
/*
* Return the node to the head of the free list.
*/
if(object) {
*(void **)object = fl->free_list;
fl->free_list = object;
/*
* Record the return of the node to the free-list.
*/
fl->nbusy--;
};
return NULL;
}
/*.......................................................................
* Return a count of the number of nodes that are currently allocated.
*
* Input:
* fl FreeList * The list to count wrt, or NULL.
* Output:
* return long The number of nodes (or 0 if fl==NULL).
*/
long _busy_FreeListNodes(FreeList *fl)
{
return fl ? fl->nbusy : 0;
}
/*.......................................................................
* Query the number of allocated nodes in the freelist which are
* currently unused.
*
* Input:
* fl FreeList * The list to count wrt, or NULL.
* Output:
* return long The number of unused nodes (or 0 if fl==NULL).
*/
long _idle_FreeListNodes(FreeList *fl)
{
return fl ? (fl->ntotal - fl->nbusy) : 0;
}
/*.......................................................................
* Allocate a new list of free-list nodes. On return the nodes will
* be linked together as a list starting with the node at the lowest
* address and ending with a NULL next pointer.
*
* Input:
* fl FreeList * The free-list to allocate the list for.
* Output:
* return FreeListBlock * The new linked block of free-list nodes,
* or NULL on error.
*/
static FreeListBlock *_new_FreeListBlock(FreeList *fl)
{
FreeListBlock *block; /* The new block to be returned */
/*
* Allocate the container.
*/
block = (FreeListBlock *) malloc(sizeof(FreeListBlock));
if(!block)
return NULL;
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_FreeListBlock().
*/
block->next = NULL;
block->nodes = NULL;
/*
* Allocate the block of nodes.
*/
block->nodes = (char *) malloc(fl->node_size * fl->blocking_factor);
if(!block->nodes)
return _del_FreeListBlock(block);
/*
* Initialize the block as a linked list of FreeListNode's.
*/
_thread_FreeListBlock(fl, block);
/*
* Update the record of the number of nodes in the freelist.
*/
fl->ntotal += fl->blocking_factor;
return block;
}
/*.......................................................................
* Link each node of a freelist block to the node that follows it.
*
* Input:
* fl FreeList * The freelist that contains the block.
* block FreeListBlock * The block to be threaded.
*/
static void _thread_FreeListBlock(FreeList *fl, FreeListBlock *block)
{
char *mem = block->nodes;
int i;
for(i=0; i<fl->blocking_factor - 1; i++, mem += fl->node_size)
*(void **)mem = mem + fl->node_size; /* Link to the next node */
*(void **)mem = NULL; /* Terminate the list */
}
/*.......................................................................
* Delete a free-list block.
*
* Input:
* fl FreeListBlock * The block to be deleted, or NULL.
* Output:
* return FreeListBlock * Always NULL.
*/
static FreeListBlock *_del_FreeListBlock(FreeListBlock *fl)
{
if(fl) {
fl->next = NULL;
if(fl->nodes)
free(fl->nodes);
fl->nodes = NULL;
free(fl);
};
return NULL;
}
#ifndef freelist_h
#define freelist_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* This module provides a memory allocation scheme that helps to
* prevent memory fragmentation by allocating large blocks of
* fixed sized objects and forming them into a free-list for
* subsequent allocations. The free-list is expanded as needed.
*/
typedef struct FreeList FreeList;
/*
* Allocate a new free-list from blocks of 'blocking_factor' objects of size
* node_size. The node_size argument should be determined by applying
* the sizeof() operator to the object type that you intend to allocate from
* the freelist.
*/
FreeList *_new_FreeList(size_t node_size, unsigned blocking_factor);
/*
* If it is known that none of the nodes currently allocated from
* a freelist are still in use, the following function can be called
* to return all nodes to the freelist without the overhead of
* having to call del_FreeListNode() for every allocated node. The
* nodes of the freelist can then be reused by future callers to
* new_FreeListNode().
*/
void _rst_FreeList(FreeList *fl);
/*
* Delete a free-list.
*/
FreeList *_del_FreeList(FreeList *fl, int force);
/*
* Determine the number of nodes that are currently in use.
*/
long _busy_FreeListNodes(FreeList *fl);
/*
* Query the number of allocated nodes in the freelist which are
* currently unused.
*/
long _idle_FreeListNodes(FreeList *fl);
/*
* Allocate a new object from a free-list.
*/
void *_new_FreeListNode(FreeList *fl);
/*
* Return an object to the free-list that it was allocated from.
*/
void *_del_FreeListNode(FreeList *fl, void *object);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* Copyright (c) 2016 by Delphix. All rights reserved.
*/
/*
* Standard headers.
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <setjmp.h>
#include <stdarg.h>
/*
* UNIX headers.
*/
#include <sys/ioctl.h>
#ifdef HAVE_SELECT
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#endif
/*
* Handle the different sources of terminal control string and size
* information. Note that if no terminal information database is available,
* ANSI VT100 control sequences are used.
*/
#if defined(USE_TERMINFO) || defined(USE_TERMCAP)
/*
* Include curses.h or ncurses/curses.h depending on which is available.
*/
#ifdef HAVE_CURSES_H
#include <curses.h>
#elif defined(HAVE_NCURSES_CURSES_H)
#include <ncurses/curses.h>
#endif
/*
* Include term.h where available.
*/
#if defined(HAVE_TERM_H)
#include <term.h>
#elif defined(HAVE_NCURSES_TERM_H)
#include <ncurses/term.h>
#endif
/*
* When using termcap, include termcap.h on systems that have it.
* Otherwise assume that all prototypes are provided by curses.h.
*/
#if defined(USE_TERMCAP) && defined(HAVE_TERMCAP_H)
#include <termcap.h>
#endif
/*
* Under Solaris default Curses the output function that tputs takes is
* declared to have a char argument. On all other systems and on Solaris
* X/Open Curses (Issue 4, Version 2) it expects an int argument (using
* c89 or options -I /usr/xpg4/include -L /usr/xpg4/lib -R /usr/xpg4/lib
* selects XPG4v2 Curses on Solaris 2.6 and later).
*
* Similarly, under Mac OS X, the return value of the tputs output
* function is declared as void, whereas it is declared as int on
* other systems.
*/
#if defined __sun && defined __SVR4 && !defined _XOPEN_CURSES
typedef int TputsRetType;
typedef char TputsArgType; /* int tputs(char c, FILE *fp) */
#define TPUTS_RETURNS_VALUE 1
#elif defined(__APPLE__) && defined(__MACH__)
typedef void TputsRetType;
typedef int TputsArgType; /* void tputs(int c, FILE *fp) */
#define TPUTS_RETURNS_VALUE 0
#else
typedef int TputsRetType;
typedef int TputsArgType; /* int tputs(int c, FILE *fp) */
#define TPUTS_RETURNS_VALUE 1
#endif
/*
* Use the above specifications to prototype our tputs callback function.
*/
static TputsRetType gl_tputs_putchar(TputsArgType c);
#endif /* defined(USE_TERMINFO) || defined(USE_TERMCAP) */
/*
* If the library is being compiled without filesystem access facilities,
* ensure that none of the action functions that normally do access the
* filesystem are bound by default, and that it they do get bound, that
* they don't do anything.
*/
#if WITHOUT_FILE_SYSTEM
#define HIDE_FILE_SYSTEM
#endif
/*
* POSIX headers.
*/
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
/*
* Provide typedefs for standard POSIX structures.
*/
typedef struct sigaction SigAction;
typedef struct termios Termios;
/*
* Which flag is used to select non-blocking I/O with fcntl()?
*/
#undef NON_BLOCKING_FLAG
#if defined(O_NONBLOCK)
#define NON_BLOCKING_FLAG (O_NONBLOCK)
#elif defined(O_NDELAY)
#define NON_BLOCKING_FLAG (O_NDELAY)
#endif
/*
* What value should we give errno if I/O blocks when it shouldn't.
*/
#undef BLOCKED_ERRNO
#if defined(EAGAIN)
#define BLOCKED_ERRNO (EAGAIN)
#elif defined(EWOULDBLOCK)
#define BLOCKED_ERRNO (EWOULDBLOCK)
#elif defined(EIO)
#define BLOCKED_ERRNO (EIO)
#else
#define BLOCKED_ERRNO 0
#endif
/*
* Local headers.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include "pathutil.h"
#endif
#include "libtecla.h"
#include "keytab.h"
#include "getline.h"
#include "ioutil.h"
#include "history.h"
#include "freelist.h"
#include "stringrp.h"
#include "chrqueue.h"
#include "cplmatch.h"
#ifndef WITHOUT_FILE_SYSTEM
#include "expand.h"
#endif
#include "errmsg.h"
/*
* Enumerate the available editing styles.
*/
typedef enum {
GL_EMACS_MODE, /* Emacs style editing */
GL_VI_MODE, /* Vi style editing */
GL_NO_EDITOR /* Fall back to the basic OS-provided editing */
} GlEditor;
/*
* Set the largest key-sequence that can be handled.
*/
#define GL_KEY_MAX 64
/*
* In vi mode, the following datatype is used to implement the
* undo command. It records a copy of the input line from before
* the command-mode action which edited the input line.
*/
typedef struct {
char *line; /* A historical copy of the input line */
int buff_curpos; /* The historical location of the cursor in */
/* line[] when the line was modified. */
int ntotal; /* The number of characters in line[] */
int saved; /* True once a line has been saved after the */
/* last call to gl_interpret_char(). */
} ViUndo;
/*
* In vi mode, the following datatype is used to record information
* needed by the vi-repeat-change command.
*/
typedef struct {
KtAction action; /* The last action function that made a */
/* change to the line. */
int count; /* The repeat count that was passed to the */
/* above command. */
int input_curpos; /* Whenever vi command mode is entered, the */
/* the position at which it was first left */
/* is recorded here. */
int command_curpos; /* Whenever vi command mode is entered, the */
/* the location of the cursor is recorded */
/* here. */
char input_char; /* Commands that call gl_read_terminal() */
/* record the character here, so that it can */
/* used on repeating the function. */
int saved; /* True if a function has been saved since the */
/* last call to gl_interpret_char(). */
int active; /* True while a function is being repeated. */
} ViRepeat;
/*
* The following datatype is used to encapsulate information specific
* to vi mode.
*/
typedef struct {
ViUndo undo; /* Information needed to implement the vi */
/* undo command. */
ViRepeat repeat; /* Information needed to implement the vi */
/* repeat command. */
int command; /* True in vi command-mode */
int find_forward; /* True if the last character search was in the */
/* forward direction. */
int find_onto; /* True if the last character search left the */
/* on top of the located character, as opposed */
/* to just before or after it. */
char find_char; /* The last character sought, or '\0' if no */
/* searches have been performed yet. */
} ViMode;
#ifdef HAVE_SELECT
/*
* Define a type for recording a file-descriptor callback and its associated
* data.
*/
typedef struct {
GlFdEventFn *fn; /* The callback function */
void *data; /* Anonymous data to pass to the callback function */
} GlFdHandler;
/*
* A list of nodes of the following type is used to record file-activity
* event handlers, but only on systems that have the select() system call.
*/
typedef struct GlFdNode GlFdNode;
struct GlFdNode {
GlFdNode *next; /* The next in the list of nodes */
int fd; /* The file descriptor being watched */
GlFdHandler rd; /* The callback to call when fd is readable */
GlFdHandler wr; /* The callback to call when fd is writable */
GlFdHandler ur; /* The callback to call when fd has urgent data */
};
/*
* Set the number of the above structures to allocate every time that
* the freelist of GlFdNode's becomes exhausted.
*/
#define GLFD_FREELIST_BLOCKING 10
static int gl_call_fd_handler(GetLine *gl, GlFdHandler *gfh, int fd,
GlFdEvent event);
static int gl_call_timeout_handler(GetLine *gl);
#endif
/*
* Each signal that gl_get_line() traps is described by a list node
* of the following type.
*/
typedef struct GlSignalNode GlSignalNode;
struct GlSignalNode {
GlSignalNode *next; /* The next signal in the list */
int signo; /* The number of the signal */
sigset_t proc_mask; /* A process mask which only includes signo */
SigAction original; /* The signal disposition of the calling program */
/* for this signal. */
unsigned flags; /* A bitwise union of GlSignalFlags enumerators */
GlAfterSignal after; /* What to do after the signal has been handled */
int errno_value; /* What to set errno to */
};
/*
* Set the number of the above structures to allocate every time that
* the freelist of GlSignalNode's becomes exhausted.
*/
#define GLS_FREELIST_BLOCKING 30
/*
* Completion handlers and their callback data are recorded in
* nodes of the following type.
*/
typedef struct GlCplCallback GlCplCallback;
struct GlCplCallback {
CplMatchFn *fn; /* The completion callback function */
void *data; /* Arbitrary callback data */
};
/*
* The following function is used as the default completion handler when
* the filesystem is to be hidden. It simply reports no completions.
*/
#ifdef HIDE_FILE_SYSTEM
static CPL_MATCH_FN(gl_no_completions);
#endif
/*
* Specify how many GlCplCallback nodes are added to the GlCplCallback freelist
* whenever it becomes exhausted.
*/
#define GL_CPL_FREELIST_BLOCKING 10
/*
* External action functions and their callback data are recorded in
* nodes of the following type.
*/
typedef struct GlExternalAction GlExternalAction;
struct GlExternalAction {
GlActionFn *fn; /* The function which implements the action */
void *data; /* Arbitrary callback data */
};
/*
* Specify how many GlExternalAction nodes are added to the
* GlExternalAction freelist whenever it becomes exhausted.
*/
#define GL_EXT_ACT_FREELIST_BLOCKING 10
/*
* Define the contents of the GetLine object.
* Note that the typedef for this object can be found in libtecla.h.
*/
struct GetLine {
ErrMsg *err; /* The error-reporting buffer */
GlHistory *glh; /* The line-history buffer */
WordCompletion *cpl; /* String completion resource object */
GlCplCallback cplfn; /* The completion callback */
#ifndef WITHOUT_FILE_SYSTEM
ExpandFile *ef; /* ~user/, $envvar and wildcard expansion */
/* resource object. */
#endif
StringGroup *capmem; /* Memory for recording terminal capability */
/* strings. */
GlCharQueue *cq; /* The terminal output character queue */
int input_fd; /* The file descriptor to read on */
int output_fd; /* The file descriptor to write to */
FILE *input_fp; /* A stream wrapper around input_fd */
FILE *output_fp; /* A stream wrapper around output_fd */
FILE *file_fp; /* When input is being temporarily taken from */
/* a file, this is its file-pointer. Otherwise */
/* it is NULL. */
char *term; /* The terminal type specified on the last call */
/* to gl_change_terminal(). */
int is_term; /* True if stdin is a terminal */
GlWriteFn *flush_fn; /* The function to call to write to the terminal */
GlIOMode io_mode; /* The I/O mode established by gl_io_mode() */
int raw_mode; /* True while the terminal is in raw mode */
GlPendingIO pending_io; /* The type of I/O that is currently pending */
GlReturnStatus rtn_status; /* The reason why gl_get_line() returned */
int rtn_errno; /* THe value of errno associated with rtn_status */
size_t linelen; /* The max number of characters per line */
char *line; /* A line-input buffer of allocated size */
/* linelen+2. The extra 2 characters are */
/* reserved for "\n\0". */
char *cutbuf; /* A cut-buffer of the same size as line[] */
char *prompt; /* The current prompt string */
int prompt_len; /* The length of the prompt string */
int prompt_changed; /* True after a callback changes the prompt */
int prompt_style; /* How the prompt string is displayed */
FreeList *cpl_mem; /* Memory for GlCplCallback objects */
FreeList *ext_act_mem; /* Memory for GlExternalAction objects */
FreeList *sig_mem; /* Memory for nodes of the signal list */
GlSignalNode *sigs; /* The head of the list of signals */
int signals_masked; /* True between calls to gl_mask_signals() and */
/* gl_unmask_signals() */
int signals_overriden; /* True between calls to gl_override_signals() */
/* and gl_restore_signals() */
sigset_t all_signal_set; /* The set of all signals that we are trapping */
sigset_t old_signal_set; /* The set of blocked signals on entry to */
/* gl_get_line(). */
sigset_t use_signal_set; /* The subset of all_signal_set to unblock */
/* while waiting for key-strokes */
Termios oldattr; /* Saved terminal attributes. */
KeyTab *bindings; /* A table of key-bindings */
int ntotal; /* The number of characters in gl->line[] */
int buff_curpos; /* The cursor position within gl->line[] */
int term_curpos; /* The cursor position on the terminal */
int term_len; /* The number of terminal characters used to */
/* display the current input line. */
int buff_mark; /* A marker location in the buffer */
int insert_curpos; /* The cursor position at start of insert */
int insert; /* True in insert mode */
int number; /* If >= 0, a numeric argument is being read */
int endline; /* True to tell gl_get_input_line() to return */
/* the current contents of gl->line[] */
int displayed; /* True if an input line is currently displayed */
int redisplay; /* If true, the input line will be redrawn */
/* either after the current action function */
/* returns, or when gl_get_input_line() */
/* is next called. */
int postpone; /* _gl_normal_io() sets this flag, to */
/* postpone any redisplays until */
/* is next called, to resume line editing. */
char keybuf[GL_KEY_MAX+1]; /* A buffer of currently unprocessed key presses */
int nbuf; /* The number of characters in keybuf[] */
int nread; /* The number of characters read from keybuf[] */
KtAction current_action; /* The action function that is being invoked */
int current_count; /* The repeat count passed to */
/* current_acction.fn() */
GlhLineID preload_id; /* When not zero, this should be the ID of a */
/* line in the history buffer for potential */
/* recall. */
int preload_history; /* If true, preload the above history line when */
/* gl_get_input_line() is next called. */
long keyseq_count; /* The number of key sequences entered by the */
/* the user since new_GetLine() was called. */
long last_search; /* The value of keyseq_count during the last */
/* history search operation. */
GlEditor editor; /* The style of editing, (eg. vi or emacs) */
int silence_bell; /* True if gl_ring_bell() should do nothing. */
int automatic_history; /* True to automatically archive entered lines */
/* in the history list. */
ViMode vi; /* Parameters used when editing in vi mode */
const char *left; /* The string that moves the cursor 1 character */
/* left. */
const char *right; /* The string that moves the cursor 1 character */
/* right. */
const char *up; /* The string that moves the cursor 1 character */
/* up. */
const char *down; /* The string that moves the cursor 1 character */
/* down. */
const char *home; /* The string that moves the cursor home */
const char *bol; /* Move cursor to beginning of line */
const char *clear_eol; /* The string that clears from the cursor to */
/* the end of the line. */
const char *clear_eod; /* The string that clears from the cursor to */
/* the end of the display. */
const char *u_arrow; /* The string returned by the up-arrow key */
const char *d_arrow; /* The string returned by the down-arrow key */
const char *l_arrow; /* The string returned by the left-arrow key */
const char *r_arrow; /* The string returned by the right-arrow key */
const char *sound_bell; /* The string needed to ring the terminal bell */
const char *bold; /* Switch to the bold font */
const char *underline; /* Underline subsequent characters */
const char *standout; /* Turn on standout mode */
const char *dim; /* Switch to a dim font */
const char *reverse; /* Turn on reverse video */
const char *blink; /* Switch to a blinking font */
const char *text_attr_off; /* Turn off all text attributes */
int nline; /* The height of the terminal in lines */
int ncolumn; /* The width of the terminal in columns */
#ifdef USE_TERMCAP
char *tgetent_buf; /* The buffer that is used by tgetent() to */
/* store a terminal description. */
char *tgetstr_buf; /* The buffer that is used by tgetstr() to */
/* store terminal capabilities. */
#endif
#ifdef USE_TERMINFO
const char *left_n; /* The parameter string that moves the cursor */
/* n characters left. */
const char *right_n; /* The parameter string that moves the cursor */
/* n characters right. */
#endif
char *app_file; /* The pathname of the application-specific */
/* .teclarc configuration file, or NULL. */
char *user_file; /* The pathname of the user-specific */
/* .teclarc configuration file, or NULL. */
int configured; /* True as soon as any teclarc configuration */
/* file has been read. */
int echo; /* True to display the line as it is being */
/* entered. If 0, only the prompt will be */
/* displayed, and the line will not be */
/* archived in the history list. */
int last_signal; /* The last signal that was caught by */
/* the last call to gl_get_line(), or -1 */
/* if no signal has been caught yet. */
#ifdef HAVE_SELECT
FreeList *fd_node_mem; /* A freelist of GlFdNode structures */
GlFdNode *fd_nodes; /* The list of fd event descriptions */
fd_set rfds; /* The set of fds to watch for readability */
fd_set wfds; /* The set of fds to watch for writability */
fd_set ufds; /* The set of fds to watch for urgent data */
int max_fd; /* The maximum file-descriptor being watched */
struct { /* Inactivity timeout related data */
struct timeval dt; /* The inactivity timeout when timer.fn() */
/* isn't 0 */
GlTimeoutFn *fn; /* The application callback to call when */
/* the inactivity timer expires, or 0 if */
/* timeouts are not required. */
void *data; /* Application provided data to be passed to */
/* timer.fn(). */
} timer;
#endif
};
/*
* Define the max amount of space needed to store a termcap terminal
* description. Unfortunately this has to be done by guesswork, so
* there is the potential for buffer overflows if we guess too small.
* Fortunately termcap has been replaced by terminfo on most
* platforms, and with terminfo this isn't an issue. The value that I
* am using here is the conventional value, as recommended by certain
* web references.
*/
#ifdef USE_TERMCAP
#define TERMCAP_BUF_SIZE 2048
#endif
/*
* Set the size of the string segments used to store terminal capability
* strings.
*/
#define CAPMEM_SEGMENT_SIZE 512
/*
* If no terminal size information is available, substitute the
* following vt100 default sizes.
*/
#define GL_DEF_NLINE 24
#define GL_DEF_NCOLUMN 80
/*
* Enumerate the attributes needed to classify different types of
* signals. These attributes reflect the standard default
* characteristics of these signals (according to Richard Steven's
* Advanced Programming in the UNIX Environment). Note that these values
* are all powers of 2, so that they can be combined in a bitwise union.
*/
typedef enum {
GLSA_TERM=1, /* A signal that terminates processes */
GLSA_SUSP=2, /* A signal that suspends processes */
GLSA_CONT=4, /* A signal that is sent when suspended processes resume */
GLSA_IGN=8, /* A signal that is ignored */
GLSA_CORE=16, /* A signal that generates a core dump */
GLSA_HARD=32, /* A signal generated by a hardware exception */
GLSA_SIZE=64 /* A signal indicating terminal size changes */
} GlSigAttr;
/*
* List the signals that we need to catch. In general these are
* those that by default terminate or suspend the process, since
* in such cases we need to restore terminal settings.
*/
static const struct GlDefSignal {
int signo; /* The number of the signal */
unsigned flags; /* A bitwise union of GlSignalFlags enumerators */
GlAfterSignal after; /* What to do after the signal has been delivered */
int attr; /* The default attributes of this signal, expressed */
/* as a bitwise union of GlSigAttr enumerators */
int errno_value; /* What to set errno to */
} gl_signal_list[] = {
{SIGABRT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM|GLSA_CORE, EINTR},
{SIGALRM, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
{SIGCONT, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_CONT|GLSA_IGN, 0},
#if defined(SIGHUP)
#ifdef ENOTTY
{SIGHUP, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, ENOTTY},
#else
{SIGHUP, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
#endif
#endif
{SIGINT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
#if defined(SIGPIPE)
#ifdef EPIPE
{SIGPIPE, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EPIPE},
#else
{SIGPIPE, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
#endif
#endif
#ifdef SIGPOLL
{SIGPOLL, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
#endif
#ifdef SIGPWR
{SIGPWR, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_IGN, 0},
#endif
#ifdef SIGQUIT
{SIGQUIT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM|GLSA_CORE, EINTR},
#endif
{SIGTERM, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
#ifdef SIGTSTP
{SIGTSTP, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
#endif
#ifdef SIGTTIN
{SIGTTIN, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
#endif
#ifdef SIGTTOU
{SIGTTOU, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
#endif
#ifdef SIGUSR1
{SIGUSR1, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
#endif
#ifdef SIGUSR2
{SIGUSR2, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
#endif
#ifdef SIGVTALRM
{SIGVTALRM, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
#endif
#ifdef SIGWINCH
{SIGWINCH, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_SIZE|GLSA_IGN, 0},
#endif
#ifdef SIGXCPU
{SIGXCPU, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM|GLSA_CORE, 0},
#endif
#ifdef SIGXFSZ
{SIGXFSZ, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM|GLSA_CORE, 0},
#endif
};
/*
* Define file-scope variables for use in signal handlers.
*/
static volatile sig_atomic_t gl_pending_signal = -1;
static sigjmp_buf gl_setjmp_buffer;
static void gl_signal_handler(int signo);
static int gl_check_caught_signal(GetLine *gl);
/*
* Respond to an externally caught process suspension or
* termination signal.
*/
static void gl_suspend_process(int signo, GetLine *gl, int ngl);
/* Return the default attributes of a given signal */
static int gl_classify_signal(int signo);
/*
* Unfortunately both terminfo and termcap require one to use the tputs()
* function to output terminal control characters, and this function
* doesn't allow one to specify a file stream. As a result, the following
* file-scope variable is used to pass the current output file stream.
* This is bad, but there doesn't seem to be any alternative.
*/
static GetLine *tputs_gl = NULL;
/*
* Define a tab to be a string of 8 spaces.
*/
#define TAB_WIDTH 8
/*
* Lookup the current size of the terminal.
*/
static void gl_query_size(GetLine *gl, int *ncolumn, int *nline);
/*
* Getline calls this to temporarily override certain signal handlers
* of the calling program.
*/
static int gl_override_signal_handlers(GetLine *gl);
/*
* Getline calls this to restore the signal handlers of the calling
* program.
*/
static int gl_restore_signal_handlers(GetLine *gl);
/*
* Temporarily block the delivery of all signals that gl_get_line()
* is currently configured to trap.
*/
static int gl_mask_signals(GetLine *gl, sigset_t *oldset);
/*
* Restore the process signal mask that was overriden by a previous
* call to gl_mask_signals().
*/
static int gl_unmask_signals(GetLine *gl, sigset_t *oldset);
/*
* Unblock the signals that gl_get_line() has been configured to catch.
*/
static int gl_catch_signals(GetLine *gl);
/*
* Return the set of all trappable signals.
*/
static void gl_list_trappable_signals(sigset_t *signals);
/*
* Put the terminal into raw input mode, after saving the original
* terminal attributes in gl->oldattr.
*/
static int gl_raw_terminal_mode(GetLine *gl);
/*
* Restore the terminal attributes from gl->oldattr.
*/
static int gl_restore_terminal_attributes(GetLine *gl);
/*
* Switch to non-blocking I/O if possible.
*/
static int gl_nonblocking_io(GetLine *gl, int fd);
/*
* Switch to blocking I/O if possible.
*/
static int gl_blocking_io(GetLine *gl, int fd);
/*
* Read a line from the user in raw mode.
*/
static int gl_get_input_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos);
/*
* Query the user for a single character.
*/
static int gl_get_query_char(GetLine *gl, const char *prompt, int defchar);
/*
* Read input from a non-interactive input stream.
*/
static int gl_read_stream_line(GetLine *gl);
/*
* Read a single character from a non-interactive input stream.
*/
static int gl_read_stream_char(GetLine *gl);
/*
* Prepare to edit a new line.
*/
static int gl_present_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos);
/*
* Reset all line input parameters for a new input line.
*/
static void gl_reset_input_line(GetLine *gl);
/*
* Handle the receipt of the potential start of a new key-sequence from
* the user.
*/
static int gl_interpret_char(GetLine *gl, char c);
/*
* Bind a single control or meta character to an action.
*/
static int gl_bind_control_char(GetLine *gl, KtBinder binder,
char c, const char *action);
/*
* Set up terminal-specific key bindings.
*/
static int gl_bind_terminal_keys(GetLine *gl);
/*
* Lookup terminal control string and size information.
*/
static int gl_control_strings(GetLine *gl, const char *term);
/*
* Wrappers around the terminfo and termcap functions that lookup
* strings in the terminal information databases.
*/
#ifdef USE_TERMINFO
static const char *gl_tigetstr(GetLine *gl, const char *name);
#elif defined(USE_TERMCAP)
static const char *gl_tgetstr(GetLine *gl, const char *name, char **bufptr);
#endif
/*
* Output a binary string directly to the terminal.
*/
static int gl_print_raw_string(GetLine *gl, int buffered,
const char *string, int n);
/*
* Print an informational message, starting and finishing on new lines.
* After the list of strings to be printed, the last argument MUST be
* GL_END_INFO.
*/
static int gl_print_info(GetLine *gl, ...);
#define GL_END_INFO ((const char *)0)
/*
* Start a newline and place the cursor at its start.
*/
static int gl_start_newline(GetLine *gl, int buffered);
/*
* Output a terminal control sequence.
*/
static int gl_print_control_sequence(GetLine *gl, int nline,
const char *string);
/*
* Output a character or string to the terminal after converting tabs
* to spaces and control characters to a caret followed by the modified
* character.
*/
static int gl_print_char(GetLine *gl, char c, char pad);
static int gl_print_string(GetLine *gl, const char *string, char pad);
/*
* Delete nc characters starting from the one under the cursor.
* Optionally copy the deleted characters to the cut buffer.
*/
static int gl_delete_chars(GetLine *gl, int nc, int cut);
/*
* Add a character to the line buffer at the current cursor position,
* inserting or overwriting according the current mode.
*/
static int gl_add_char_to_line(GetLine *gl, char c);
/*
* Insert/append a string to the line buffer and terminal at the current
* cursor position.
*/
static int gl_add_string_to_line(GetLine *gl, const char *s);
/*
* Record a new character in the input-line buffer.
*/
static int gl_buffer_char(GetLine *gl, char c, int bufpos);
/*
* Record a string in the input-line buffer.
*/
static int gl_buffer_string(GetLine *gl, const char *s, int n, int bufpos);
/*
* Make way to insert a string in the input-line buffer.
*/
static int gl_make_gap_in_buffer(GetLine *gl, int start, int n);
/*
* Remove characters from the input-line buffer, and move any characters
* that followed them to the start of the vacated space.
*/
static void gl_remove_from_buffer(GetLine *gl, int start, int n);
/*
* Terminate the input-line buffer after a specified number of characters.
*/
static int gl_truncate_buffer(GetLine *gl, int n);
/*
* Delete the displayed part of the input line that follows the current
* terminal cursor position.
*/
static int gl_truncate_display(GetLine *gl);
/*
* Accomodate changes to the contents of the input line buffer
* that weren't made by the above gl_*buffer functions.
*/
static void gl_update_buffer(GetLine *gl);
/*
* Read a single character from the terminal.
*/
static int gl_read_terminal(GetLine *gl, int keep, char *c);
/*
* Discard processed characters from the key-press lookahead buffer.
*/
static void gl_discard_chars(GetLine *gl, int nused);
/*
* Move the terminal cursor n positions to the left or right.
*/
static int gl_terminal_move_cursor(GetLine *gl, int n);
/*
* Move the terminal cursor to a given position.
*/
static int gl_set_term_curpos(GetLine *gl, int term_curpos);
/*
* Set the position of the cursor both in the line input buffer and on the
* terminal.
*/
static int gl_place_cursor(GetLine *gl, int buff_curpos);
/*
* How many characters are needed to write a number as an octal string?
*/
static int gl_octal_width(unsigned num);
/*
* Return the number of spaces needed to display a tab character at
* a given location of the terminal.
*/
static int gl_displayed_tab_width(GetLine *gl, int term_curpos);
/*
* Return the number of terminal characters needed to display a
* given raw character.
*/
static int gl_displayed_char_width(GetLine *gl, char c, int term_curpos);
/*
* Return the number of terminal characters needed to display a
* given substring.
*/
static int gl_displayed_string_width(GetLine *gl, const char *string, int nc,
int term_curpos);
/*
* Return non-zero if 'c' is to be considered part of a word.
*/
static int gl_is_word_char(int c);
/*
* Read a tecla configuration file.
*/
static int _gl_read_config_file(GetLine *gl, const char *filename, KtBinder who);
/*
* Read a tecla configuration string.
*/
static int _gl_read_config_string(GetLine *gl, const char *buffer, KtBinder who);
/*
* Define the callback function used by _gl_parse_config_line() to
* read the next character of a configuration stream.
*/
#define GLC_GETC_FN(fn) int (fn)(void *stream)
typedef GLC_GETC_FN(GlcGetcFn);
static GLC_GETC_FN(glc_file_getc); /* Read from a file */
static GLC_GETC_FN(glc_buff_getc); /* Read from a string */
/*
* Parse a single configuration command line.
*/
static int _gl_parse_config_line(GetLine *gl, void *stream, GlcGetcFn *getc_fn,
const char *origin, KtBinder who, int *lineno);
static int gl_report_config_error(GetLine *gl, const char *origin, int lineno,
const char *errmsg);
/*
* Bind the actual arrow key bindings to match those of the symbolic
* arrow-key bindings.
*/
static int _gl_bind_arrow_keys(GetLine *gl);
/*
* Copy the binding of the specified symbolic arrow-key binding to
* the terminal specific, and default arrow-key key-sequences.
*/
static int _gl_rebind_arrow_key(GetLine *gl, const char *name,
const char *term_seq,
const char *def_seq1,
const char *def_seq2);
/*
* After the gl_read_from_file() action has been used to tell gl_get_line()
* to temporarily read input from a file, gl_revert_input() arranges
* for input to be reverted to the input stream last registered with
* gl_change_terminal().
*/
static void gl_revert_input(GetLine *gl);
/*
* Flush unwritten characters to the terminal.
*/
static int gl_flush_output(GetLine *gl);
/*
* The callback through which all terminal output is routed.
* This simply appends characters to a queue buffer, which is
* subsequently flushed to the output channel by gl_flush_output().
*/
static GL_WRITE_FN(gl_write_fn);
/*
* The callback function which the output character queue object
* calls to transfer characters to the output channel.
*/
static GL_WRITE_FN(gl_flush_terminal);
/*
* Enumerate the possible return statuses of gl_read_input().
*/
typedef enum {
GL_READ_OK, /* A character was read successfully */
GL_READ_ERROR, /* A read-error occurred */
GL_READ_BLOCKED, /* The read would have blocked the caller */
GL_READ_EOF /* The end of the current input file was reached */
} GlReadStatus;
static GlReadStatus gl_read_input(GetLine *gl, char *c);
/*
* Private functions of gl_read_input().
*/
static int gl_event_handler(GetLine *gl, int fd);
static int gl_read_unmasked(GetLine *gl, int fd, char *c);
/*
* A private function of gl_tty_signals().
*/
static int gl_set_tty_signal(int signo, void (*handler)(int));
/*
* Change the editor style being emulated.
*/
static int gl_change_editor(GetLine *gl, GlEditor editor);
/*
* Searching in a given direction, return the index of a given (or
* read) character in the input line, or the character that precedes
* it in the specified search direction. Return -1 if not found.
*/
static int gl_find_char(GetLine *gl, int count, int forward, int onto, char c);
/*
* Return the buffer index of the nth word ending after the cursor.
*/
static int gl_nth_word_end_forward(GetLine *gl, int n);
/*
* Return the buffer index of the nth word start after the cursor.
*/
static int gl_nth_word_start_forward(GetLine *gl, int n);
/*
* Return the buffer index of the nth word start before the cursor.
*/
static int gl_nth_word_start_backward(GetLine *gl, int n);
/*
* When called when vi command mode is enabled, this function saves the
* current line and cursor position for potential restoration later
* by the vi undo command.
*/
static void gl_save_for_undo(GetLine *gl);
/*
* If in vi mode, switch to vi command mode.
*/
static void gl_vi_command_mode(GetLine *gl);
/*
* In vi mode this is used to delete up to or onto a given or read
* character in the input line. Also switch to insert mode if requested
* after the deletion.
*/
static int gl_delete_find(GetLine *gl, int count, char c, int forward,
int onto, int change);
/*
* Copy the characters between the cursor and the count'th instance of
* a specified (or read) character in the input line, into the cut buffer.
*/
static int gl_copy_find(GetLine *gl, int count, char c, int forward, int onto);
/*
* Return the line index of the parenthesis that either matches the one under
* the cursor, or not over a parenthesis character, the index of the next
* close parenthesis. Return -1 if not found.
*/
static int gl_index_of_matching_paren(GetLine *gl);
/*
* Replace a malloc'd string (or NULL), with another malloc'd copy of
* a string (or NULL).
*/
static int gl_record_string(char **sptr, const char *string);
/*
* Enumerate text display attributes as powers of two, suitable for
* use in a bit-mask.
*/
typedef enum {
GL_TXT_STANDOUT=1, /* Display text highlighted */
GL_TXT_UNDERLINE=2, /* Display text underlined */
GL_TXT_REVERSE=4, /* Display text with reverse video */
GL_TXT_BLINK=8, /* Display blinking text */
GL_TXT_DIM=16, /* Display text in a dim font */
GL_TXT_BOLD=32 /* Display text using a bold font */
} GlTextAttr;
/*
* Display the prompt regardless of the current visibility mode.
*/
static int gl_display_prompt(GetLine *gl);
/*
* Return the number of characters used by the prompt on the terminal.
*/
static int gl_displayed_prompt_width(GetLine *gl);
/*
* Prepare to return the current input line to the caller of gl_get_line().
*/
static int gl_line_ended(GetLine *gl, int newline_char);
/*
* Arrange for the input line to be redisplayed when the current contents
* of the output queue have been flushed.
*/
static void gl_queue_redisplay(GetLine *gl);
/*
* Erase the displayed representation of the input line, without
* touching the buffered copy.
*/
static int gl_erase_line(GetLine *gl);
/*
* This function is called whenever the input line has been erased.
*/
static void gl_line_erased(GetLine *gl);
/*
* Arrange for the current input line to be discarded.
*/
void _gl_abandon_line(GetLine *gl);
/*
* The following are private internally callable versions of pertinent
* public functions. Unlike their public wrapper functions, they don't
* block signals while running, and assume that their arguments are valid.
* They are designed to be called from places where signals are already
* blocked, and where simple sanity checks have already been applied to
* their arguments.
*/
static char *_gl_get_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos);
static int _gl_query_char(GetLine *gl, const char *prompt, char defchar);
static int _gl_read_char(GetLine *gl);
static int _gl_update_size(GetLine *gl);
/*
* Redraw the current input line to account for a change in the terminal
* size. Also install the new size in gl.
*/
static int gl_handle_tty_resize(GetLine *gl, int ncolumn, int nline);
static int _gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
const char *term);
static int _gl_configure_getline(GetLine *gl, const char *app_string,
const char *app_file, const char *user_file);
static int _gl_save_history(GetLine *gl, const char *filename,
const char *comment, int max_lines);
static int _gl_load_history(GetLine *gl, const char *filename,
const char *comment);
static int _gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
GlFdEventFn *callback, void *data);
static void _gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline,
GlTerminalSize *size);
static void _gl_replace_prompt(GetLine *gl, const char *prompt);
static int _gl_trap_signal(GetLine *gl, int signo, unsigned flags,
GlAfterSignal after, int errno_value);
static int _gl_raw_io(GetLine *gl, int redisplay);
static int _gl_normal_io(GetLine *gl);
static int _gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
int list_only, const char *name,
const char *keyseq);
static int _gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
const char *name, const char *keyseq);
static int _gl_io_mode(GetLine *gl, GlIOMode mode);
static int _gl_set_term_size(GetLine *gl, int ncolumn, int nline);
static int _gl_append_history(GetLine *gl, const char *line);
/*
* Reset the completion status and associated errno value in
* gl->rtn_status and gl->rtn_errno.
*/
static void gl_clear_status(GetLine *gl);
/*
* Record a completion status, unless a previous abnormal completion
* status has already been recorded for the current call.
*/
static void gl_record_status(GetLine *gl, GlReturnStatus rtn_status,
int rtn_errno);
/*
* Set the maximum length of a line in a user's tecla configuration
* file (not counting comments).
*/
#define GL_CONF_BUFLEN 100
/*
* Set the maximum number of arguments supported by individual commands
* in tecla configuration files.
*/
#define GL_CONF_MAXARG 10
/*
* Prototype the available action functions.
*/
static KT_KEY_FN(gl_user_interrupt);
static KT_KEY_FN(gl_abort);
static KT_KEY_FN(gl_suspend);
static KT_KEY_FN(gl_stop_output);
static KT_KEY_FN(gl_start_output);
static KT_KEY_FN(gl_literal_next);
static KT_KEY_FN(gl_cursor_left);
static KT_KEY_FN(gl_cursor_right);
static KT_KEY_FN(gl_insert_mode);
static KT_KEY_FN(gl_beginning_of_line);
static KT_KEY_FN(gl_end_of_line);
static KT_KEY_FN(gl_delete_line);
static KT_KEY_FN(gl_kill_line);
static KT_KEY_FN(gl_forward_word);
static KT_KEY_FN(gl_backward_word);
static KT_KEY_FN(gl_forward_delete_char);
static KT_KEY_FN(gl_backward_delete_char);
static KT_KEY_FN(gl_forward_delete_word);
static KT_KEY_FN(gl_backward_delete_word);
static KT_KEY_FN(gl_delete_refind);
static KT_KEY_FN(gl_delete_invert_refind);
static KT_KEY_FN(gl_delete_to_column);
static KT_KEY_FN(gl_delete_to_parenthesis);
static KT_KEY_FN(gl_forward_delete_find);
static KT_KEY_FN(gl_backward_delete_find);
static KT_KEY_FN(gl_forward_delete_to);
static KT_KEY_FN(gl_backward_delete_to);
static KT_KEY_FN(gl_upcase_word);
static KT_KEY_FN(gl_downcase_word);
static KT_KEY_FN(gl_capitalize_word);
static KT_KEY_FN(gl_redisplay);
static KT_KEY_FN(gl_clear_screen);
static KT_KEY_FN(gl_transpose_chars);
static KT_KEY_FN(gl_set_mark);
static KT_KEY_FN(gl_exchange_point_and_mark);
static KT_KEY_FN(gl_kill_region);
static KT_KEY_FN(gl_copy_region_as_kill);
static KT_KEY_FN(gl_yank);
static KT_KEY_FN(gl_up_history);
static KT_KEY_FN(gl_down_history);
static KT_KEY_FN(gl_history_search_backward);
static KT_KEY_FN(gl_history_re_search_backward);
static KT_KEY_FN(gl_history_search_forward);
static KT_KEY_FN(gl_history_re_search_forward);
static KT_KEY_FN(gl_complete_word);
#ifndef HIDE_FILE_SYSTEM
static KT_KEY_FN(gl_expand_filename);
static KT_KEY_FN(gl_read_from_file);
static KT_KEY_FN(gl_read_init_files);
static KT_KEY_FN(gl_list_glob);
#endif
static KT_KEY_FN(gl_del_char_or_list_or_eof);
static KT_KEY_FN(gl_list_or_eof);
static KT_KEY_FN(gl_beginning_of_history);
static KT_KEY_FN(gl_end_of_history);
static KT_KEY_FN(gl_digit_argument);
static KT_KEY_FN(gl_newline);
static KT_KEY_FN(gl_repeat_history);
static KT_KEY_FN(gl_vi_insert);
static KT_KEY_FN(gl_vi_overwrite);
static KT_KEY_FN(gl_change_case);
static KT_KEY_FN(gl_vi_insert_at_bol);
static KT_KEY_FN(gl_vi_append_at_eol);
static KT_KEY_FN(gl_vi_append);
static KT_KEY_FN(gl_backward_kill_line);
static KT_KEY_FN(gl_goto_column);
static KT_KEY_FN(gl_forward_to_word);
static KT_KEY_FN(gl_vi_replace_char);
static KT_KEY_FN(gl_vi_change_rest_of_line);
static KT_KEY_FN(gl_vi_change_line);
static KT_KEY_FN(gl_vi_change_to_bol);
static KT_KEY_FN(gl_vi_change_refind);
static KT_KEY_FN(gl_vi_change_invert_refind);
static KT_KEY_FN(gl_vi_change_to_column);
static KT_KEY_FN(gl_vi_change_to_parenthesis);
static KT_KEY_FN(gl_vi_forward_change_word);
static KT_KEY_FN(gl_vi_backward_change_word);
static KT_KEY_FN(gl_vi_forward_change_find);
static KT_KEY_FN(gl_vi_backward_change_find);
static KT_KEY_FN(gl_vi_forward_change_to);
static KT_KEY_FN(gl_vi_backward_change_to);
static KT_KEY_FN(gl_vi_forward_change_char);
static KT_KEY_FN(gl_vi_backward_change_char);
static KT_KEY_FN(gl_forward_copy_char);
static KT_KEY_FN(gl_backward_copy_char);
static KT_KEY_FN(gl_forward_find_char);
static KT_KEY_FN(gl_backward_find_char);
static KT_KEY_FN(gl_forward_to_char);
static KT_KEY_FN(gl_backward_to_char);
static KT_KEY_FN(gl_repeat_find_char);
static KT_KEY_FN(gl_invert_refind_char);
static KT_KEY_FN(gl_append_yank);
static KT_KEY_FN(gl_backward_copy_word);
static KT_KEY_FN(gl_forward_copy_word);
static KT_KEY_FN(gl_copy_to_bol);
static KT_KEY_FN(gl_copy_refind);
static KT_KEY_FN(gl_copy_invert_refind);
static KT_KEY_FN(gl_copy_to_column);
static KT_KEY_FN(gl_copy_to_parenthesis);
static KT_KEY_FN(gl_copy_rest_of_line);
static KT_KEY_FN(gl_copy_line);
static KT_KEY_FN(gl_backward_copy_find);
static KT_KEY_FN(gl_forward_copy_find);
static KT_KEY_FN(gl_backward_copy_to);
static KT_KEY_FN(gl_forward_copy_to);
static KT_KEY_FN(gl_vi_undo);
static KT_KEY_FN(gl_emacs_editing_mode);
static KT_KEY_FN(gl_vi_editing_mode);
static KT_KEY_FN(gl_ring_bell);
static KT_KEY_FN(gl_vi_repeat_change);
static KT_KEY_FN(gl_find_parenthesis);
static KT_KEY_FN(gl_list_history);
static KT_KEY_FN(gl_list_completions);
static KT_KEY_FN(gl_run_external_action);
/*
* Name the available action functions.
*/
static const struct {const char *name; KT_KEY_FN(*fn);} gl_actions[] = {
{"user-interrupt", gl_user_interrupt},
{"abort", gl_abort},
{"suspend", gl_suspend},
{"stop-output", gl_stop_output},
{"start-output", gl_start_output},
{"literal-next", gl_literal_next},
{"cursor-right", gl_cursor_right},
{"cursor-left", gl_cursor_left},
{"insert-mode", gl_insert_mode},
{"beginning-of-line", gl_beginning_of_line},
{"end-of-line", gl_end_of_line},
{"delete-line", gl_delete_line},
{"kill-line", gl_kill_line},
{"forward-word", gl_forward_word},
{"backward-word", gl_backward_word},
{"forward-delete-char", gl_forward_delete_char},
{"backward-delete-char", gl_backward_delete_char},
{"forward-delete-word", gl_forward_delete_word},
{"backward-delete-word", gl_backward_delete_word},
{"delete-refind", gl_delete_refind},
{"delete-invert-refind", gl_delete_invert_refind},
{"delete-to-column", gl_delete_to_column},
{"delete-to-parenthesis", gl_delete_to_parenthesis},
{"forward-delete-find", gl_forward_delete_find},
{"backward-delete-find", gl_backward_delete_find},
{"forward-delete-to", gl_forward_delete_to},
{"backward-delete-to", gl_backward_delete_to},
{"upcase-word", gl_upcase_word},
{"downcase-word", gl_downcase_word},
{"capitalize-word", gl_capitalize_word},
{"redisplay", gl_redisplay},
{"clear-screen", gl_clear_screen},
{"transpose-chars", gl_transpose_chars},
{"set-mark", gl_set_mark},
{"exchange-point-and-mark", gl_exchange_point_and_mark},
{"kill-region", gl_kill_region},
{"copy-region-as-kill", gl_copy_region_as_kill},
{"yank", gl_yank},
{"up-history", gl_up_history},
{"down-history", gl_down_history},
{"history-search-backward", gl_history_search_backward},
{"history-re-search-backward", gl_history_re_search_backward},
{"history-search-forward", gl_history_search_forward},
{"history-re-search-forward", gl_history_re_search_forward},
{"complete-word", gl_complete_word},
#ifndef HIDE_FILE_SYSTEM
{"expand-filename", gl_expand_filename},
{"read-from-file", gl_read_from_file},
{"read-init-files", gl_read_init_files},
{"list-glob", gl_list_glob},
#endif
{"del-char-or-list-or-eof", gl_del_char_or_list_or_eof},
{"beginning-of-history", gl_beginning_of_history},
{"end-of-history", gl_end_of_history},
{"digit-argument", gl_digit_argument},
{"newline", gl_newline},
{"repeat-history", gl_repeat_history},
{"vi-insert", gl_vi_insert},
{"vi-overwrite", gl_vi_overwrite},
{"vi-insert-at-bol", gl_vi_insert_at_bol},
{"vi-append-at-eol", gl_vi_append_at_eol},
{"vi-append", gl_vi_append},
{"change-case", gl_change_case},
{"backward-kill-line", gl_backward_kill_line},
{"goto-column", gl_goto_column},
{"forward-to-word", gl_forward_to_word},
{"vi-replace-char", gl_vi_replace_char},
{"vi-change-rest-of-line", gl_vi_change_rest_of_line},
{"vi-change-line", gl_vi_change_line},
{"vi-change-to-bol", gl_vi_change_to_bol},
{"vi-change-refind", gl_vi_change_refind},
{"vi-change-invert-refind", gl_vi_change_invert_refind},
{"vi-change-to-column", gl_vi_change_to_column},
{"vi-change-to-parenthesis", gl_vi_change_to_parenthesis},
{"forward-copy-char", gl_forward_copy_char},
{"backward-copy-char", gl_backward_copy_char},
{"forward-find-char", gl_forward_find_char},
{"backward-find-char", gl_backward_find_char},
{"forward-to-char", gl_forward_to_char},
{"backward-to-char", gl_backward_to_char},
{"repeat-find-char", gl_repeat_find_char},
{"invert-refind-char", gl_invert_refind_char},
{"append-yank", gl_append_yank},
{"backward-copy-word", gl_backward_copy_word},
{"forward-copy-word", gl_forward_copy_word},
{"copy-to-bol", gl_copy_to_bol},
{"copy-refind", gl_copy_refind},
{"copy-invert-refind", gl_copy_invert_refind},
{"copy-to-column", gl_copy_to_column},
{"copy-to-parenthesis", gl_copy_to_parenthesis},
{"copy-rest-of-line", gl_copy_rest_of_line},
{"copy-line", gl_copy_line},
{"backward-copy-find", gl_backward_copy_find},
{"forward-copy-find", gl_forward_copy_find},
{"backward-copy-to", gl_backward_copy_to},
{"forward-copy-to", gl_forward_copy_to},
{"list-or-eof", gl_list_or_eof},
{"vi-undo", gl_vi_undo},
{"vi-backward-change-word", gl_vi_backward_change_word},
{"vi-forward-change-word", gl_vi_forward_change_word},
{"vi-backward-change-find", gl_vi_backward_change_find},
{"vi-forward-change-find", gl_vi_forward_change_find},
{"vi-backward-change-to", gl_vi_backward_change_to},
{"vi-forward-change-to", gl_vi_forward_change_to},
{"vi-backward-change-char", gl_vi_backward_change_char},
{"vi-forward-change-char", gl_vi_forward_change_char},
{"emacs-mode", gl_emacs_editing_mode},
{"vi-mode", gl_vi_editing_mode},
{"ring-bell", gl_ring_bell},
{"vi-repeat-change", gl_vi_repeat_change},
{"find-parenthesis", gl_find_parenthesis},
{"list-history", gl_list_history},
};
/*
* Define the default key-bindings in emacs mode.
*/
static const KtKeyBinding gl_emacs_bindings[] = {
{"right", "cursor-right"},
{"^F", "cursor-right"},
{"left", "cursor-left"},
{"^B", "cursor-left"},
{"M-i", "insert-mode"},
{"M-I", "insert-mode"},
{"^A", "beginning-of-line"},
{"^E", "end-of-line"},
{"^U", "delete-line"},
{"^K", "kill-line"},
{"M-f", "forward-word"},
{"M-F", "forward-word"},
{"M-b", "backward-word"},
{"M-B", "backward-word"},
{"^D", "del-char-or-list-or-eof"},
{"^H", "backward-delete-char"},
{"^?", "backward-delete-char"},
{"M-d", "forward-delete-word"},
{"M-D", "forward-delete-word"},
{"M-^H", "backward-delete-word"},
{"M-^?", "backward-delete-word"},
{"M-u", "upcase-word"},
{"M-U", "upcase-word"},
{"M-l", "downcase-word"},
{"M-L", "downcase-word"},
{"M-c", "capitalize-word"},
{"M-C", "capitalize-word"},
{"^R", "redisplay"},
{"^L", "clear-screen"},
{"^T", "transpose-chars"},
{"^@", "set-mark"},
{"^X^X", "exchange-point-and-mark"},
{"^W", "kill-region"},
{"M-w", "copy-region-as-kill"},
{"M-W", "copy-region-as-kill"},
{"^Y", "yank"},
{"^P", "up-history"},
{"up", "up-history"},
{"^N", "down-history"},
{"down", "down-history"},
{"M-p", "history-search-backward"},
{"M-P", "history-search-backward"},
{"M-n", "history-search-forward"},
{"M-N", "history-search-forward"},
{"\t", "complete-word"},
#ifndef HIDE_FILE_SYSTEM
{"^X*", "expand-filename"},
{"^X^F", "read-from-file"},
{"^X^R", "read-init-files"},
{"^Xg", "list-glob"},
{"^XG", "list-glob"},
#endif
{"^Xh", "list-history"},
{"^XH", "list-history"},
{"M-<", "beginning-of-history"},
{"M->", "end-of-history"},
{"M-0", "digit-argument"},
{"M-1", "digit-argument"},
{"M-2", "digit-argument"},
{"M-3", "digit-argument"},
{"M-4", "digit-argument"},
{"M-5", "digit-argument"},
{"M-6", "digit-argument"},
{"M-7", "digit-argument"},
{"M-8", "digit-argument"},
{"M-9", "digit-argument"},
{"\r", "newline"},
{"\n", "newline"},
{"M-o", "repeat-history"},
{"M-C-v", "vi-mode"},
};
/*
* Define the default key-bindings in vi mode. Note that in vi-mode
* meta-key bindings are command-mode bindings. For example M-i first
* switches to command mode if not already in that mode, then moves
* the cursor one position right, as in vi.
*/
static const KtKeyBinding gl_vi_bindings[] = {
{"^D", "list-or-eof"},
#ifndef HIDE_FILE_SYSTEM
{"^G", "list-glob"},
#endif
{"^H", "backward-delete-char"},
{"\t", "complete-word"},
{"\r", "newline"},
{"\n", "newline"},
{"^L", "clear-screen"},
{"^N", "down-history"},
{"^P", "up-history"},
{"^R", "redisplay"},
{"^U", "backward-kill-line"},
{"^W", "backward-delete-word"},
#ifndef HIDE_FILE_SYSTEM
{"^X^F", "read-from-file"},
{"^X^R", "read-init-files"},
{"^X*", "expand-filename"},
#endif
{"^?", "backward-delete-char"},
{"M- ", "cursor-right"},
{"M-$", "end-of-line"},
#ifndef HIDE_FILE_SYSTEM
{"M-*", "expand-filename"},
#endif
{"M-+", "down-history"},
{"M--", "up-history"},
{"M-<", "beginning-of-history"},
{"M->", "end-of-history"},
{"M-^", "beginning-of-line"},
{"M-;", "repeat-find-char"},
{"M-,", "invert-refind-char"},
{"M-|", "goto-column"},
{"M-~", "change-case"},
{"M-.", "vi-repeat-change"},
{"M-%", "find-parenthesis"},
{"M-0", "digit-argument"},
{"M-1", "digit-argument"},
{"M-2", "digit-argument"},
{"M-3", "digit-argument"},
{"M-4", "digit-argument"},
{"M-5", "digit-argument"},
{"M-6", "digit-argument"},
{"M-7", "digit-argument"},
{"M-8", "digit-argument"},
{"M-9", "digit-argument"},
{"M-a", "vi-append"},
{"M-A", "vi-append-at-eol"},
{"M-b", "backward-word"},
{"M-B", "backward-word"},
{"M-C", "vi-change-rest-of-line"},
{"M-cb", "vi-backward-change-word"},
{"M-cB", "vi-backward-change-word"},
{"M-cc", "vi-change-line"},
{"M-ce", "vi-forward-change-word"},
{"M-cE", "vi-forward-change-word"},
{"M-cw", "vi-forward-change-word"},
{"M-cW", "vi-forward-change-word"},
{"M-cF", "vi-backward-change-find"},
{"M-cf", "vi-forward-change-find"},
{"M-cT", "vi-backward-change-to"},
{"M-ct", "vi-forward-change-to"},
{"M-c;", "vi-change-refind"},
{"M-c,", "vi-change-invert-refind"},
{"M-ch", "vi-backward-change-char"},
{"M-c^H", "vi-backward-change-char"},
{"M-c^?", "vi-backward-change-char"},
{"M-cl", "vi-forward-change-char"},
{"M-c ", "vi-forward-change-char"},
{"M-c^", "vi-change-to-bol"},
{"M-c0", "vi-change-to-bol"},
{"M-c$", "vi-change-rest-of-line"},
{"M-c|", "vi-change-to-column"},
{"M-c%", "vi-change-to-parenthesis"},
{"M-dh", "backward-delete-char"},
{"M-d^H", "backward-delete-char"},
{"M-d^?", "backward-delete-char"},
{"M-dl", "forward-delete-char"},
{"M-d ", "forward-delete-char"},
{"M-dd", "delete-line"},
{"M-db", "backward-delete-word"},
{"M-dB", "backward-delete-word"},
{"M-de", "forward-delete-word"},
{"M-dE", "forward-delete-word"},
{"M-dw", "forward-delete-word"},
{"M-dW", "forward-delete-word"},
{"M-dF", "backward-delete-find"},
{"M-df", "forward-delete-find"},
{"M-dT", "backward-delete-to"},
{"M-dt", "forward-delete-to"},
{"M-d;", "delete-refind"},
{"M-d,", "delete-invert-refind"},
{"M-d^", "backward-kill-line"},
{"M-d0", "backward-kill-line"},
{"M-d$", "kill-line"},
{"M-D", "kill-line"},
{"M-d|", "delete-to-column"},
{"M-d%", "delete-to-parenthesis"},
{"M-e", "forward-word"},
{"M-E", "forward-word"},
{"M-f", "forward-find-char"},
{"M-F", "backward-find-char"},
{"M--", "up-history"},
{"M-h", "cursor-left"},
{"M-H", "beginning-of-history"},
{"M-i", "vi-insert"},
{"M-I", "vi-insert-at-bol"},
{"M-j", "down-history"},
{"M-J", "history-search-forward"},
{"M-k", "up-history"},
{"M-K", "history-search-backward"},
{"M-l", "cursor-right"},
{"M-L", "end-of-history"},
{"M-n", "history-re-search-forward"},
{"M-N", "history-re-search-backward"},
{"M-p", "append-yank"},
{"M-P", "yank"},
{"M-r", "vi-replace-char"},
{"M-R", "vi-overwrite"},
{"M-s", "vi-forward-change-char"},
{"M-S", "vi-change-line"},
{"M-t", "forward-to-char"},
{"M-T", "backward-to-char"},
{"M-u", "vi-undo"},
{"M-w", "forward-to-word"},
{"M-W", "forward-to-word"},
{"M-x", "forward-delete-char"},
{"M-X", "backward-delete-char"},
{"M-yh", "backward-copy-char"},
{"M-y^H", "backward-copy-char"},
{"M-y^?", "backward-copy-char"},
{"M-yl", "forward-copy-char"},
{"M-y ", "forward-copy-char"},
{"M-ye", "forward-copy-word"},
{"M-yE", "forward-copy-word"},
{"M-yw", "forward-copy-word"},
{"M-yW", "forward-copy-word"},
{"M-yb", "backward-copy-word"},
{"M-yB", "backward-copy-word"},
{"M-yf", "forward-copy-find"},
{"M-yF", "backward-copy-find"},
{"M-yt", "forward-copy-to"},
{"M-yT", "backward-copy-to"},
{"M-y;", "copy-refind"},
{"M-y,", "copy-invert-refind"},
{"M-y^", "copy-to-bol"},
{"M-y0", "copy-to-bol"},
{"M-y$", "copy-rest-of-line"},
{"M-yy", "copy-line"},
{"M-Y", "copy-line"},
{"M-y|", "copy-to-column"},
{"M-y%", "copy-to-parenthesis"},
{"M-^E", "emacs-mode"},
{"M-^H", "cursor-left"},
{"M-^?", "cursor-left"},
{"M-^L", "clear-screen"},
{"M-^N", "down-history"},
{"M-^P", "up-history"},
{"M-^R", "redisplay"},
{"M-^D", "list-or-eof"},
{"M-\r", "newline"},
{"M-\t", "complete-word"},
{"M-\n", "newline"},
#ifndef HIDE_FILE_SYSTEM
{"M-^X^R", "read-init-files"},
#endif
{"M-^Xh", "list-history"},
{"M-^XH", "list-history"},
{"down", "down-history"},
{"up", "up-history"},
{"left", "cursor-left"},
{"right", "cursor-right"},
};
/*.......................................................................
* Create a new GetLine object.
*
* Input:
* linelen size_t The maximum line length to allow for.
* histlen size_t The number of bytes to allocate for recording
* a circular buffer of history lines.
* Output:
* return GetLine * The new object, or NULL on error.
*/
GetLine *new_GetLine(size_t linelen, size_t histlen)
{
GetLine *gl; /* The object to be returned */
int i;
/*
* Check the arguments.
*/
if(linelen < 10) {
errno = ENOMEM;
return NULL;
};
/*
* Allocate the container.
*/
gl = (GetLine *) malloc(sizeof(GetLine));
if(!gl) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_GetLine().
*/
gl->err = NULL;
gl->glh = NULL;
gl->cpl = NULL;
#ifndef HIDE_FILE_SYSTEM
gl->cplfn.fn = cpl_file_completions;
#else
gl->cplfn.fn = gl_no_completions;
#endif
gl->cplfn.data = NULL;
#ifndef WITHOUT_FILE_SYSTEM
gl->ef = NULL;
#endif
gl->capmem = NULL;
gl->cq = NULL;
gl->input_fd = -1;
gl->output_fd = -1;
gl->input_fp = NULL;
gl->output_fp = NULL;
gl->file_fp = NULL;
gl->term = NULL;
gl->is_term = 0;
gl->flush_fn = gl_flush_terminal;
gl->io_mode = GL_NORMAL_MODE;
gl->raw_mode = 0;
gl->pending_io = GLP_WRITE; /* We will start by writing the prompt */
gl_clear_status(gl);
gl->linelen = linelen;
gl->line = NULL;
gl->cutbuf = NULL;
gl->prompt = NULL;
gl->prompt_len = 0;
gl->prompt_changed = 0;
gl->prompt_style = GL_LITERAL_PROMPT;
gl->cpl_mem = NULL;
gl->ext_act_mem = NULL;
gl->sig_mem = NULL;
gl->sigs = NULL;
gl->signals_masked = 0;
gl->signals_overriden = 0;
sigemptyset(&gl->all_signal_set);
sigemptyset(&gl->old_signal_set);
sigemptyset(&gl->use_signal_set);
gl->bindings = NULL;
gl->ntotal = 0;
gl->buff_curpos = 0;
gl->term_curpos = 0;
gl->term_len = 0;
gl->buff_mark = 0;
gl->insert_curpos = 0;
gl->insert = 1;
gl->number = -1;
gl->endline = 1;
gl->displayed = 0;
gl->redisplay = 0;
gl->postpone = 0;
gl->keybuf[0]='\0';
gl->nbuf = 0;
gl->nread = 0;
gl->current_action.fn = 0;
gl->current_action.data = NULL;
gl->current_count = 0;
gl->preload_id = 0;
gl->preload_history = 0;
gl->keyseq_count = 0;
gl->last_search = -1;
gl->editor = GL_EMACS_MODE;
gl->silence_bell = 0;
gl->automatic_history = 1;
gl->vi.undo.line = NULL;
gl->vi.undo.buff_curpos = 0;
gl->vi.undo.ntotal = 0;
gl->vi.undo.saved = 0;
gl->vi.repeat.action.fn = 0;
gl->vi.repeat.action.data = 0;
gl->vi.repeat.count = 0;
gl->vi.repeat.input_curpos = 0;
gl->vi.repeat.command_curpos = 0;
gl->vi.repeat.input_char = '\0';
gl->vi.repeat.saved = 0;
gl->vi.repeat.active = 0;
gl->vi.command = 0;
gl->vi.find_forward = 0;
gl->vi.find_onto = 0;
gl->vi.find_char = '\0';
gl->left = NULL;
gl->right = NULL;
gl->up = NULL;
gl->down = NULL;
gl->home = NULL;
gl->bol = 0;
gl->clear_eol = NULL;
gl->clear_eod = NULL;
gl->u_arrow = NULL;
gl->d_arrow = NULL;
gl->l_arrow = NULL;
gl->r_arrow = NULL;
gl->sound_bell = NULL;
gl->bold = NULL;
gl->underline = NULL;
gl->standout = NULL;
gl->dim = NULL;
gl->reverse = NULL;
gl->blink = NULL;
gl->text_attr_off = NULL;
gl->nline = 0;
gl->ncolumn = 0;
#ifdef USE_TERMINFO
gl->left_n = NULL;
gl->right_n = NULL;
#elif defined(USE_TERMCAP)
gl->tgetent_buf = NULL;
gl->tgetstr_buf = NULL;
#endif
gl->app_file = NULL;
gl->user_file = NULL;
gl->configured = 0;
gl->echo = 1;
gl->last_signal = -1;
#ifdef HAVE_SELECT
gl->fd_node_mem = NULL;
gl->fd_nodes = NULL;
FD_ZERO(&gl->rfds);
FD_ZERO(&gl->wfds);
FD_ZERO(&gl->ufds);
gl->max_fd = 0;
gl->timer.dt.tv_sec = 0;
gl->timer.dt.tv_usec = 0;
gl->timer.fn = 0;
gl->timer.data = NULL;
#endif
/*
* Allocate an error reporting buffer.
*/
gl->err = _new_ErrMsg();
if(!gl->err)
return del_GetLine(gl);
/*
* Allocate the history buffer.
*/
gl->glh = _new_GlHistory(histlen);
if(!gl->glh)
return del_GetLine(gl);
/*
* Allocate the resource object for file-completion.
*/
gl->cpl = new_WordCompletion();
if(!gl->cpl)
return del_GetLine(gl);
/*
* Allocate the resource object for file-completion.
*/
#ifndef WITHOUT_FILE_SYSTEM
gl->ef = new_ExpandFile();
if(!gl->ef)
return del_GetLine(gl);
#endif
/*
* Allocate a string-segment memory allocator for use in storing terminal
* capablity strings.
*/
gl->capmem = _new_StringGroup(CAPMEM_SEGMENT_SIZE);
if(!gl->capmem)
return del_GetLine(gl);
/*
* Allocate the character queue that is used to buffer terminal output.
*/
gl->cq = _new_GlCharQueue();
if(!gl->cq)
return del_GetLine(gl);
/*
* Allocate a line buffer, leaving 2 extra characters for the terminating
* '\n' and '\0' characters
*/
gl->line = (char *) malloc(linelen + 2);
if(!gl->line) {
errno = ENOMEM;
return del_GetLine(gl);
};
/*
* Start with an empty input line.
*/
gl_truncate_buffer(gl, 0);
/*
* Allocate a cut buffer.
*/
gl->cutbuf = (char *) malloc(linelen + 2);
if(!gl->cutbuf) {
errno = ENOMEM;
return del_GetLine(gl);
};
gl->cutbuf[0] = '\0';
/*
* Allocate an initial empty prompt.
*/
_gl_replace_prompt(gl, NULL);
if(!gl->prompt) {
errno = ENOMEM;
return del_GetLine(gl);
};
/*
* Allocate a vi undo buffer.
*/
gl->vi.undo.line = (char *) malloc(linelen + 2);
if(!gl->vi.undo.line) {
errno = ENOMEM;
return del_GetLine(gl);
};
gl->vi.undo.line[0] = '\0';
/*
* Allocate a freelist from which to allocate nodes for the list
* of completion functions.
*/
gl->cpl_mem = _new_FreeList(sizeof(GlCplCallback), GL_CPL_FREELIST_BLOCKING);
if(!gl->cpl_mem)
return del_GetLine(gl);
/*
* Allocate a freelist from which to allocate nodes for the list
* of external action functions.
*/
gl->ext_act_mem = _new_FreeList(sizeof(GlExternalAction),
GL_EXT_ACT_FREELIST_BLOCKING);
if(!gl->ext_act_mem)
return del_GetLine(gl);
/*
* Allocate a freelist from which to allocate nodes for the list
* of signals.
*/
gl->sig_mem = _new_FreeList(sizeof(GlSignalNode), GLS_FREELIST_BLOCKING);
if(!gl->sig_mem)
return del_GetLine(gl);
/*
* Install initial dispositions for the default list of signals that
* gl_get_line() traps.
*/
for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
const struct GlDefSignal *sig = gl_signal_list + i;
if(_gl_trap_signal(gl, sig->signo, sig->flags, sig->after,
sig->errno_value))
return del_GetLine(gl);
};
/*
* Allocate an empty table of key bindings.
*/
gl->bindings = _new_KeyTab();
if(!gl->bindings)
return del_GetLine(gl);
/*
* Define the available actions that can be bound to key sequences.
*/
for(i=0; i<sizeof(gl_actions)/sizeof(gl_actions[0]); i++) {
if(_kt_set_action(gl->bindings, gl_actions[i].name, gl_actions[i].fn, NULL))
return del_GetLine(gl);
};
/*
* Set up the default bindings.
*/
if(gl_change_editor(gl, gl->editor))
return del_GetLine(gl);
/*
* Allocate termcap buffers.
*/
#ifdef USE_TERMCAP
gl->tgetent_buf = (char *) malloc(TERMCAP_BUF_SIZE);
gl->tgetstr_buf = (char *) malloc(TERMCAP_BUF_SIZE);
if(!gl->tgetent_buf || !gl->tgetstr_buf) {
errno = ENOMEM;
return del_GetLine(gl);
};
#endif
/*
* Set up for I/O assuming stdin and stdout.
*/
if(_gl_change_terminal(gl, stdin, stdout, getenv("TERM")))
return del_GetLine(gl);
/*
* Create a freelist for use in allocating GlFdNode list nodes.
*/
#ifdef HAVE_SELECT
gl->fd_node_mem = _new_FreeList(sizeof(GlFdNode), GLFD_FREELIST_BLOCKING);
if(!gl->fd_node_mem)
return del_GetLine(gl);
#endif
/*
* We are done for now.
*/
return gl;
}
/*.......................................................................
* Delete a GetLine object.
*
* Input:
* gl GetLine * The object to be deleted.
* Output:
* return GetLine * The deleted object (always NULL).
*/
GetLine *del_GetLine(GetLine *gl)
{
if(gl) {
/*
* If the terminal is in raw server mode, reset it.
*/
_gl_normal_io(gl);
/*
* Deallocate all objects contained by gl.
*/
gl->err = _del_ErrMsg(gl->err);
gl->glh = _del_GlHistory(gl->glh);
gl->cpl = del_WordCompletion(gl->cpl);
#ifndef WITHOUT_FILE_SYSTEM
gl->ef = del_ExpandFile(gl->ef);
#endif
gl->capmem = _del_StringGroup(gl->capmem);
gl->cq = _del_GlCharQueue(gl->cq);
if(gl->file_fp)
fclose(gl->file_fp);
if(gl->term)
free(gl->term);
if(gl->line)
free(gl->line);
if(gl->cutbuf)
free(gl->cutbuf);
if(gl->prompt)
free(gl->prompt);
gl->cpl_mem = _del_FreeList(gl->cpl_mem, 1);
gl->ext_act_mem = _del_FreeList(gl->ext_act_mem, 1);
gl->sig_mem = _del_FreeList(gl->sig_mem, 1);
gl->sigs = NULL; /* Already freed by freeing sig_mem */
gl->bindings = _del_KeyTab(gl->bindings);
if(gl->vi.undo.line)
free(gl->vi.undo.line);
#ifdef USE_TERMCAP
if(gl->tgetent_buf)
free(gl->tgetent_buf);
if(gl->tgetstr_buf)
free(gl->tgetstr_buf);
#endif
if(gl->app_file)
free(gl->app_file);
if(gl->user_file)
free(gl->user_file);
#ifdef HAVE_SELECT
gl->fd_node_mem = _del_FreeList(gl->fd_node_mem, 1);
gl->fd_nodes = NULL; /* Already freed by freeing gl->fd_node_mem */
#endif
/*
* Delete the now empty container.
*/
free(gl);
};
return NULL;
}
/*.......................................................................
* Bind a control or meta character to an action.
*
* Input:
* gl GetLine * The resource object of this program.
* binder KtBinder The source of the binding.
* c char The control or meta character.
* If this is '\0', the call is ignored.
* action const char * The action name to bind the key to.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_bind_control_char(GetLine *gl, KtBinder binder, char c,
const char *action)
{
char keyseq[2];
/*
* Quietly reject binding to the NUL control character, since this
* is an ambiguous prefix of all bindings.
*/
if(c == '\0')
return 0;
/*
* Making sure not to bind characters which aren't either control or
* meta characters.
*/
if(IS_CTRL_CHAR(c) || IS_META_CHAR(c)) {
keyseq[0] = c;
keyseq[1] = '\0';
} else {
return 0;
};
/*
* Install the binding.
*/
if(_kt_set_keybinding(gl->bindings, binder, keyseq, action)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Read a line from the user.
*
* Input:
* gl GetLine * A resource object returned by new_GetLine().
* prompt char * The prompt to prefix the line with.
* start_line char * The initial contents of the input line, or NULL
* if it should start out empty.
* start_pos int If start_line isn't NULL, this specifies the
* index of the character over which the cursor
* should initially be positioned within the line.
* If you just want it to follow the last character
* of the line, send -1.
* Output:
* return char * An internal buffer containing the input line, or
* NULL at the end of input. If the line fitted in
* the buffer there will be a '\n' newline character
* before the terminating '\0'. If it was truncated
* there will be no newline character, and the remains
* of the line should be retrieved via further calls
* to this function.
*/
char *gl_get_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos)
{
char *retval; /* The return value of _gl_get_line() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return NULL;
};
/*
* Temporarily block all of the signals that we have been asked to trap.
*/
if(gl_mask_signals(gl, &gl->old_signal_set))
return NULL;
/*
* Perform the command-line editing task.
*/
retval = _gl_get_line(gl, prompt, start_line, start_pos);
/*
* Restore the process signal mask to how it was when this function was
* first called.
*/
gl_unmask_signals(gl, &gl->old_signal_set);
return retval;
}
/*.......................................................................
* This is the main body of the public function gl_get_line().
*/
static char *_gl_get_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos)
{
int waserr = 0; /* True if an error occurs */
/*
* Assume that this call will successfully complete the input
* line until proven otherwise.
*/
gl_clear_status(gl);
/*
* If this is the first call to this function since new_GetLine(),
* complete any postponed configuration.
*/
if(!gl->configured) {
(void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
gl->configured = 1;
};
/*
* Before installing our signal handler functions, record the fact
* that there are no pending signals.
*/
gl_pending_signal = -1;
/*
* Temporarily override the signal handlers of the calling program,
* so that we can intercept signals that would leave the terminal
* in a bad state.
*/
waserr = gl_override_signal_handlers(gl);
/*
* After recording the current terminal settings, switch the terminal
* into raw input mode.
*/
waserr = waserr || _gl_raw_io(gl, 1);
/*
* Attempt to read the line. This will require more than one attempt if
* either a current temporary input file is opened by gl_get_input_line()
* or the end of a temporary input file is reached by gl_read_stream_line().
*/
while(!waserr) {
/*
* Read a line from a non-interactive stream?
*/
if(gl->file_fp || !gl->is_term) {
if(gl_read_stream_line(gl)==0) {
break;
} else if(gl->file_fp) {
gl_revert_input(gl);
gl_record_status(gl, GLR_NEWLINE, 0);
} else {
waserr = 1;
break;
};
};
/*
* Read from the terminal? Note that the above if() block may have
* changed gl->file_fp, so it is necessary to retest it here, rather
* than using an else statement.
*/
if(!gl->file_fp && gl->is_term) {
if(gl_get_input_line(gl, prompt, start_line, start_pos))
waserr = 1;
else
break;
};
};
/*
* If an error occurred, but gl->rtn_status is still set to
* GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
* leave it at whatever specific value was assigned by the function
* that aborted input. This means that only functions that trap
* non-generic errors have to remember to update gl->rtn_status
* themselves.
*/
if(waserr && gl->rtn_status == GLR_NEWLINE)
gl_record_status(gl, GLR_ERROR, errno);
/*
* Restore terminal settings.
*/
if(gl->io_mode != GL_SERVER_MODE)
_gl_normal_io(gl);
/*
* Restore the signal handlers.
*/
gl_restore_signal_handlers(gl);
/*
* If gl_get_line() gets aborted early, the errno value associated
* with the event that caused this to happen is recorded in
* gl->rtn_errno. Since errno may have been overwritten by cleanup
* functions after this, restore its value to the value that it had
* when the error condition occured, so that the caller can examine it
* to find out what happened.
*/
errno = gl->rtn_errno;
/*
* Check the completion status to see how to return.
*/
switch(gl->rtn_status) {
case GLR_NEWLINE: /* Success */
return gl->line;
case GLR_BLOCKED: /* These events abort the current input line, */
case GLR_SIGNAL: /* when in normal blocking I/O mode, but only */
case GLR_TIMEOUT: /* temporarily pause line editing when in */
case GLR_FDABORT: /* non-blocking server I/O mode. */
if(gl->io_mode != GL_SERVER_MODE)
_gl_abandon_line(gl);
return NULL;
case GLR_ERROR: /* Unrecoverable errors abort the input line, */
case GLR_EOF: /* regardless of the I/O mode. */
default:
_gl_abandon_line(gl);
return NULL;
};
}
/*.......................................................................
* Read a single character from the user.
*
* Input:
* gl GetLine * A resource object returned by new_GetLine().
* prompt char * The prompt to prefix the line with, or NULL if
* no prompt is required.
* defchar char The character to substitute if the
* user simply hits return, or '\n' if you don't
* need to substitute anything.
* Output:
* return int The character that was read, or EOF if the read
* had to be aborted (in which case you can call
* gl_return_status() to find out why).
*/
int gl_query_char(GetLine *gl, const char *prompt, char defchar)
{
int retval; /* The return value of _gl_query_char() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return EOF;
};
/*
* Temporarily block all of the signals that we have been asked to trap.
*/
if(gl_mask_signals(gl, &gl->old_signal_set))
return EOF;
/*
* Perform the character reading task.
*/
retval = _gl_query_char(gl, prompt, defchar);
/*
* Restore the process signal mask to how it was when this function was
* first called.
*/
gl_unmask_signals(gl, &gl->old_signal_set);
return retval;
}
/*.......................................................................
* This is the main body of the public function gl_query_char().
*/
static int _gl_query_char(GetLine *gl, const char *prompt, char defchar)
{
int c = EOF; /* The character to be returned */
int waserr = 0; /* True if an error occurs */
/*
* Assume that this call will successfully complete the input operation
* until proven otherwise.
*/
gl_clear_status(gl);
/*
* If this is the first call to this function or gl_get_line(),
* since new_GetLine(), complete any postponed configuration.
*/
if(!gl->configured) {
(void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
gl->configured = 1;
};
/*
* Before installing our signal handler functions, record the fact
* that there are no pending signals.
*/
gl_pending_signal = -1;
/*
* Temporarily override the signal handlers of the calling program,
* so that we can intercept signals that would leave the terminal
* in a bad state.
*/
waserr = gl_override_signal_handlers(gl);
/*
* After recording the current terminal settings, switch the terminal
* into raw input mode without redisplaying any partially entered
* input line.
*/
waserr = waserr || _gl_raw_io(gl, 0);
/*
* Attempt to read the line. This will require more than one attempt if
* either a current temporary input file is opened by gl_get_input_line()
* or the end of a temporary input file is reached by gl_read_stream_line().
*/
while(!waserr) {
/*
* Read a line from a non-interactive stream?
*/
if(gl->file_fp || !gl->is_term) {
c = gl_read_stream_char(gl);
if(c != EOF) { /* Success? */
if(c=='\n') c = defchar;
break;
} else if(gl->file_fp) { /* End of temporary input file? */
gl_revert_input(gl);
gl_record_status(gl, GLR_NEWLINE, 0);
} else { /* An error? */
waserr = 1;
break;
};
};
/*
* Read from the terminal? Note that the above if() block may have
* changed gl->file_fp, so it is necessary to retest it here, rather
* than using an else statement.
*/
if(!gl->file_fp && gl->is_term) {
c = gl_get_query_char(gl, prompt, defchar);
if(c==EOF)
waserr = 1;
else
break;
};
};
/*
* If an error occurred, but gl->rtn_status is still set to
* GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
* leave it at whatever specific value was assigned by the function
* that aborted input. This means that only functions that trap
* non-generic errors have to remember to update gl->rtn_status
* themselves.
*/
if(waserr && gl->rtn_status == GLR_NEWLINE)
gl_record_status(gl, GLR_ERROR, errno);
/*
* Restore terminal settings.
*/
if(gl->io_mode != GL_SERVER_MODE)
_gl_normal_io(gl);
/*
* Restore the signal handlers.
*/
gl_restore_signal_handlers(gl);
/*
* If this function gets aborted early, the errno value associated
* with the event that caused this to happen is recorded in
* gl->rtn_errno. Since errno may have been overwritten by cleanup
* functions after this, restore its value to the value that it had
* when the error condition occured, so that the caller can examine it
* to find out what happened.
*/
errno = gl->rtn_errno;
/*
* Error conditions are signalled to the caller, by setting the returned
* character to EOF.
*/
if(gl->rtn_status != GLR_NEWLINE)
c = EOF;
/*
* In this mode, every character that is read is a completed
* transaction, just like reading a completed input line, so prepare
* for the next input line or character.
*/
_gl_abandon_line(gl);
/*
* Return the acquired character.
*/
return c;
}
/*.......................................................................
* Record of the signal handlers of the calling program, so that they
* can be restored later.
*
* Input:
* gl GetLine * The resource object of this library.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_override_signal_handlers(GetLine *gl)
{
GlSignalNode *sig; /* A node in the list of signals to be caught */
/*
* Set up our signal handler.
*/
SigAction act;
act.sa_handler = gl_signal_handler;
memcpy(&act.sa_mask, &gl->all_signal_set, sizeof(sigset_t));
act.sa_flags = 0;
/*
* Get the subset of the signals that we are supposed to trap that
* should actually be trapped.
*/
sigemptyset(&gl->use_signal_set);
for(sig=gl->sigs; sig; sig=sig->next) {
/*
* Trap this signal? If it is blocked by the calling program and we
* haven't been told to unblock it, don't arrange to trap this signal.
*/
if(sig->flags & GLS_UNBLOCK_SIG ||
!sigismember(&gl->old_signal_set, sig->signo)) {
if(sigaddset(&gl->use_signal_set, sig->signo) == -1) {
_err_record_msg(gl->err, "sigaddset error", END_ERR_MSG);
return 1;
};
};
};
/*
* Override the actions of the signals that we are trapping.
*/
for(sig=gl->sigs; sig; sig=sig->next) {
if(sigismember(&gl->use_signal_set, sig->signo)) {
sigdelset(&act.sa_mask, sig->signo);
if(sigaction(sig->signo, &act, &sig->original)) {
_err_record_msg(gl->err, "sigaction error", END_ERR_MSG);
return 1;
};
sigaddset(&act.sa_mask, sig->signo);
};
};
/*
* Record the fact that the application's signal handlers have now
* been overriden.
*/
gl->signals_overriden = 1;
/*
* Just in case a SIGWINCH signal was sent to the process while our
* SIGWINCH signal handler wasn't in place, check to see if the terminal
* size needs updating.
*/
if(_gl_update_size(gl))
return 1;
return 0;
}
/*.......................................................................
* Restore the signal handlers of the calling program.
*
* Input:
* gl GetLine * The resource object of this library.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_restore_signal_handlers(GetLine *gl)
{
GlSignalNode *sig; /* A node in the list of signals to be caught */
/*
* Restore application signal handlers that were overriden
* by gl_override_signal_handlers().
*/
for(sig=gl->sigs; sig; sig=sig->next) {
if(sigismember(&gl->use_signal_set, sig->signo) &&
sigaction(sig->signo, &sig->original, NULL)) {
_err_record_msg(gl->err, "sigaction error", END_ERR_MSG);
return 1;
};
};
/*
* Record the fact that the application's signal handlers have now
* been restored.
*/
gl->signals_overriden = 0;
return 0;
}
/*.......................................................................
* This signal handler simply records the fact that a given signal was
* caught in the file-scope gl_pending_signal variable.
*/
static void gl_signal_handler(int signo)
{
gl_pending_signal = signo;
siglongjmp(gl_setjmp_buffer, 1);
}
/*.......................................................................
* Switch the terminal into raw mode after storing the previous terminal
* settings in gl->attributes.
*
* Input:
* gl GetLine * The resource object of this program.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_raw_terminal_mode(GetLine *gl)
{
Termios newattr; /* The new terminal attributes */
/*
* If the terminal is already in raw mode, do nothing.
*/
if(gl->raw_mode)
return 0;
/*
* Record the current terminal attributes.
*/
if(tcgetattr(gl->input_fd, &gl->oldattr)) {
_err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
return 1;
};
/*
* This function shouldn't do anything but record the current terminal
* attritubes if editing has been disabled.
*/
if(gl->editor == GL_NO_EDITOR)
return 0;
/*
* Modify the existing attributes.
*/
newattr = gl->oldattr;
/*
* Turn off local echo, canonical input mode and extended input processing.
*/
newattr.c_lflag &= ~(ECHO | ICANON | IEXTEN);
/*
* Don't translate carriage return to newline, turn off input parity
* checking, don't strip off 8th bit, turn off output flow control.
*/
newattr.c_iflag &= ~(ICRNL | INPCK | ISTRIP);
/*
* Clear size bits, turn off parity checking, and allow 8-bit characters.
*/
newattr.c_cflag &= ~(CSIZE | PARENB);
newattr.c_cflag |= CS8;
/*
* Turn off output processing.
*/
newattr.c_oflag &= ~(OPOST);
/*
* Request one byte at a time, without waiting.
*/
newattr.c_cc[VMIN] = gl->io_mode==GL_SERVER_MODE ? 0:1;
newattr.c_cc[VTIME] = 0;
/*
* Install the new terminal modes.
*/
while(tcsetattr(gl->input_fd, TCSADRAIN, &newattr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
return 1;
};
};
/*
* Record the new terminal mode.
*/
gl->raw_mode = 1;
return 0;
}
/*.......................................................................
* Restore the terminal attributes recorded in gl->oldattr.
*
* Input:
* gl GetLine * The resource object of this library.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_restore_terminal_attributes(GetLine *gl)
{
int waserr = 0;
/*
* If not in raw mode, do nothing.
*/
if(!gl->raw_mode)
return 0;
/*
* Before changing the terminal attributes, make sure that all output
* has been passed to the terminal.
*/
if(gl_flush_output(gl))
waserr = 1;
/*
* Reset the terminal attributes to the values that they had on
* entry to gl_get_line().
*/
while(tcsetattr(gl->input_fd, TCSADRAIN, &gl->oldattr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
waserr = 1;
break;
};
};
/*
* Record the new terminal mode.
*/
gl->raw_mode = 0;
return waserr;
}
/*.......................................................................
* Switch the terminal file descriptor to use non-blocking I/O.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* fd int The file descriptor to make non-blocking.
*/
static int gl_nonblocking_io(GetLine *gl, int fd)
{
int fcntl_flags; /* The new file-descriptor control flags */
/*
* Is non-blocking I/O supported on this system? Note that even
* without non-blocking I/O, the terminal will probably still act as
* though it was non-blocking, because we also set the terminal
* attributes to return immediately if no input is available and we
* use select() to wait to be able to write. If select() also isn't
* available, then input will probably remain fine, but output could
* block, depending on the behaviour of the terminal driver.
*/
#if defined(NON_BLOCKING_FLAG)
/*
* Query the current file-control flags, and add the
* non-blocking I/O flag.
*/
fcntl_flags = fcntl(fd, F_GETFL) | NON_BLOCKING_FLAG;
/*
* Install the new control flags.
*/
if(fcntl(fd, F_SETFL, fcntl_flags) == -1) {
_err_record_msg(gl->err, "fcntl error", END_ERR_MSG);
return 1;
};
#endif
return 0;
}
/*.......................................................................
* Switch to blocking terminal I/O.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* fd int The file descriptor to make blocking.
*/
static int gl_blocking_io(GetLine *gl, int fd)
{
int fcntl_flags; /* The new file-descriptor control flags */
/*
* Is non-blocking I/O implemented on this system?
*/
#if defined(NON_BLOCKING_FLAG)
/*
* Query the current file control flags and remove the non-blocking
* I/O flag.
*/
fcntl_flags = fcntl(fd, F_GETFL) & ~NON_BLOCKING_FLAG;
/*
* Install the modified control flags.
*/
if(fcntl(fd, F_SETFL, fcntl_flags) == -1) {
_err_record_msg(gl->err, "fcntl error", END_ERR_MSG);
return 1;
};
#endif
return 0;
}
/*.......................................................................
* Read a new input line from the user.
*
* Input:
* gl GetLine * The resource object of this library.
* prompt char * The prompt to prefix the line with, or NULL to
* use the same prompt that was used by the previous
* line.
* start_line char * The initial contents of the input line, or NULL
* if it should start out empty.
* start_pos int If start_line isn't NULL, this specifies the
* index of the character over which the cursor
* should initially be positioned within the line.
* If you just want it to follow the last character
* of the line, send -1.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_get_input_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos)
{
char c; /* The character being read */
/*
* Flush any pending output to the terminal.
*/
if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl))
return 1;
/*
* Are we starting a new line?
*/
if(gl->endline) {
/*
* Delete any incompletely enterred line.
*/
if(gl_erase_line(gl))
return 1;
/*
* Display the new line to be edited.
*/
if(gl_present_line(gl, prompt, start_line, start_pos))
return 1;
};
/*
* Read one character at a time.
*/
while(gl_read_terminal(gl, 1, &c) == 0) {
/*
* Increment the count of the number of key sequences entered.
*/
gl->keyseq_count++;
/*
* Interpret the character either as the start of a new key-sequence,
* as a continuation of a repeat count, or as a printable character
* to be added to the line.
*/
if(gl_interpret_char(gl, c))
break;
/*
* If we just ran an action function which temporarily asked for
* input to be taken from a file, abort this call.
*/
if(gl->file_fp)
return 0;
/*
* Has the line been completed?
*/
if(gl->endline)
return gl_line_ended(gl, c);
};
/*
* To get here, gl_read_terminal() must have returned non-zero. See
* whether a signal was caught that requested that the current line
* be returned.
*/
if(gl->endline)
return gl_line_ended(gl, '\n');
/*
* If I/O blocked while attempting to get the latest character
* of the key sequence, rewind the key buffer to allow interpretation of
* the current key sequence to be restarted on the next call to this
* function.
*/
if(gl->rtn_status == GLR_BLOCKED && gl->pending_io == GLP_READ)
gl->nread = 0;
return 1;
}
/*.......................................................................
* This is the private function of gl_query_char() that handles
* prompting the user, reading a character from the terminal, and
* displaying what the user entered.
*
* Input:
* gl GetLine * The resource object of this library.
* prompt char * The prompt to prefix the line with.
* defchar char The character to substitute if the
* user simply hits return, or '\n' if you don't
* need to substitute anything.
* Output:
* return int The character that was read, or EOF if something
* prevented a character from being read.
*/
static int gl_get_query_char(GetLine *gl, const char *prompt, int defchar)
{
char c; /* The character being read */
int retval; /* The return value of this function */
/*
* Flush any pending output to the terminal.
*/
if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl))
return EOF;
/*
* Delete any incompletely entered line.
*/
if(gl_erase_line(gl))
return EOF;
/*
* Reset the line input parameters and display the prompt, if any.
*/
if(gl_present_line(gl, prompt, NULL, 0))
return EOF;
/*
* Read one character.
*/
if(gl_read_terminal(gl, 1, &c) == 0) {
/*
* In this mode, count each character as being a new key-sequence.
*/
gl->keyseq_count++;
/*
* Delete the character that was read, from the key-press buffer.
*/
gl_discard_chars(gl, gl->nread);
/*
* Convert carriage returns to newlines.
*/
if(c == '\r')
c = '\n';
/*
* If the user just hit return, subsitute the default character.
*/
if(c == '\n')
c = defchar;
/*
* Display the entered character to the right of the prompt.
*/
if(c!='\n') {
if(gl_end_of_line(gl, 1, NULL)==0)
gl_print_char(gl, c, ' ');
};
/*
* Record the return character, and mark the call as successful.
*/
retval = c;
gl_record_status(gl, GLR_NEWLINE, 0);
/*
* Was a signal caught whose disposition is to cause the current input
* line to be returned? If so return a newline character.
*/
} else if(gl->endline) {
retval = '\n';
gl_record_status(gl, GLR_NEWLINE, 0);
} else {
retval = EOF;
};
/*
* Start a new line.
*/
if(gl_start_newline(gl, 1))
return EOF;
/*
* Attempt to flush any pending output.
*/
(void) gl_flush_output(gl);
/*
* Return either the character that was read, or EOF if an error occurred.
*/
return retval;
}
/*.......................................................................
* Add a character to the line buffer at the current cursor position,
* inserting or overwriting according the current mode.
*
* Input:
* gl GetLine * The resource object of this library.
* c char The character to be added.
* Output:
* return int 0 - OK.
* 1 - Insufficient room.
*/
static int gl_add_char_to_line(GetLine *gl, char c)
{
/*
* Keep a record of the current cursor position.
*/
int buff_curpos = gl->buff_curpos;
int term_curpos = gl->term_curpos;
/*
* Work out the displayed width of the new character.
*/
int width = gl_displayed_char_width(gl, c, term_curpos);
/*
* If we are in insert mode, or at the end of the line,
* check that we can accomodate a new character in the buffer.
* If not, simply return, leaving it up to the calling program
* to check for the absence of a newline character.
*/
if((gl->insert || buff_curpos >= gl->ntotal) && gl->ntotal >= gl->linelen)
return 0;
/*
* Are we adding characters to the line (ie. inserting or appending)?
*/
if(gl->insert || buff_curpos >= gl->ntotal) {
/*
* If inserting, make room for the new character.
*/
if(buff_curpos < gl->ntotal)
gl_make_gap_in_buffer(gl, buff_curpos, 1);
/*
* Copy the character into the buffer.
*/
gl_buffer_char(gl, c, buff_curpos);
gl->buff_curpos++;
/*
* Redraw the line from the cursor position to the end of the line,
* and move the cursor to just after the added character.
*/
if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
gl_set_term_curpos(gl, term_curpos + width))
return 1;
/*
* Are we overwriting an existing character?
*/
} else {
/*
* Get the width of the character being overwritten.
*/
int old_width = gl_displayed_char_width(gl, gl->line[buff_curpos],
term_curpos);
/*
* Overwrite the character in the buffer.
*/
gl_buffer_char(gl, c, buff_curpos);
/*
* If we are replacing with a narrower character, we need to
* redraw the terminal string to the end of the line, then
* overwrite the trailing old_width - width characters
* with spaces.
*/
if(old_width > width) {
if(gl_print_string(gl, gl->line + buff_curpos, '\0'))
return 1;
/*
* Clear to the end of the terminal.
*/
if(gl_truncate_display(gl))
return 1;
/*
* Move the cursor to the end of the new character.
*/
if(gl_set_term_curpos(gl, term_curpos + width))
return 1;
gl->buff_curpos++;
/*
* If we are replacing with a wider character, then we will be
* inserting new characters, and thus extending the line.
*/
} else if(width > old_width) {
/*
* Redraw the line from the cursor position to the end of the line,
* and move the cursor to just after the added character.
*/
if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
gl_set_term_curpos(gl, term_curpos + width))
return 1;
gl->buff_curpos++;
/*
* The original and replacement characters have the same width,
* so simply overwrite.
*/
} else {
/*
* Copy the character into the buffer.
*/
gl_buffer_char(gl, c, buff_curpos);
gl->buff_curpos++;
/*
* Overwrite the original character.
*/
if(gl_print_char(gl, c, gl->line[gl->buff_curpos]))
return 1;
};
};
return 0;
}
/*.......................................................................
* Insert/append a string to the line buffer and terminal at the current
* cursor position.
*
* Input:
* gl GetLine * The resource object of this library.
* s char * The string to be added.
* Output:
* return int 0 - OK.
* 1 - Insufficient room.
*/
static int gl_add_string_to_line(GetLine *gl, const char *s)
{
int buff_slen; /* The length of the string being added to line[] */
int term_slen; /* The length of the string being written to the terminal */
int buff_curpos; /* The original value of gl->buff_curpos */
int term_curpos; /* The original value of gl->term_curpos */
/*
* Keep a record of the current cursor position.
*/
buff_curpos = gl->buff_curpos;
term_curpos = gl->term_curpos;
/*
* How long is the string to be added?
*/
buff_slen = strlen(s);
term_slen = gl_displayed_string_width(gl, s, buff_slen, term_curpos);
/*
* Check that we can accomodate the string in the buffer.
* If not, simply return, leaving it up to the calling program
* to check for the absence of a newline character.
*/
if(gl->ntotal + buff_slen > gl->linelen)
return 0;
/*
* Move the characters that follow the cursor in the buffer by
* buff_slen characters to the right.
*/
if(gl->ntotal > gl->buff_curpos)
gl_make_gap_in_buffer(gl, gl->buff_curpos, buff_slen);
/*
* Copy the string into the buffer.
*/
gl_buffer_string(gl, s, buff_slen, gl->buff_curpos);
gl->buff_curpos += buff_slen;
/*
* Write the modified part of the line to the terminal, then move
* the terminal cursor to the end of the displayed input string.
*/
if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
gl_set_term_curpos(gl, term_curpos + term_slen))
return 1;
return 0;
}
/*.......................................................................
* Read a single character from the terminal.
*
* Input:
* gl GetLine * The resource object of this library.
* keep int If true, the returned character will be kept in
* the input buffer, for potential replays. It should
* subsequently be removed from the buffer when the
* key sequence that it belongs to has been fully
* processed, by calling gl_discard_chars().
* Input/Output:
* c char * The character that is read, is assigned to *c.
* Output:
* return int 0 - OK.
* 1 - Either an I/O error occurred, or a signal was
* caught who's disposition is to abort gl_get_line()
* or to have gl_get_line() return the current line
* as though the user had pressed return. In the
* latter case gl->endline will be non-zero.
*/
static int gl_read_terminal(GetLine *gl, int keep, char *c)
{
/*
* Before waiting for a new character to be input, flush unwritten
* characters to the terminal.
*/
if(gl_flush_output(gl))
return 1;
/*
* Record the fact that we are about to read from the terminal.
*/
gl->pending_io = GLP_READ;
/*
* If there is already an unread character in the buffer,
* return it.
*/
if(gl->nread < gl->nbuf) {
*c = gl->keybuf[gl->nread];
/*
* Retain the character in the key buffer, but mark it as having been read?
*/
if(keep) {
gl->nread++;
/*
* Completely remove the character from the key buffer?
*/
} else {
memmove(gl->keybuf + gl->nread, gl->keybuf + gl->nread + 1,
gl->nbuf - gl->nread - 1);
};
return 0;
};
/*
* Make sure that there is space in the key buffer for one more character.
* This should always be true if gl_interpret_char() is called for each
* new character added, since it will clear the buffer once it has recognized
* or rejected a key sequence.
*/
if(gl->nbuf + 1 > GL_KEY_MAX) {
gl_print_info(gl, "gl_read_terminal: Buffer overflow avoided.",
GL_END_INFO);
errno = EIO;
return 1;
};
/*
* Read one character from the terminal.
*/
switch(gl_read_input(gl, c)) {
case GL_READ_OK:
break;
case GL_READ_BLOCKED:
gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
return 1;
break;
default:
return 1;
break;
};
/*
* Append the character to the key buffer?
*/
if(keep) {
gl->keybuf[gl->nbuf] = *c;
gl->nread = ++gl->nbuf;
};
return 0;
}
/*.......................................................................
* Read one or more keypresses from the terminal of an input stream.
*
* Input:
* gl GetLine * The resource object of this module.
* c char * The character that was read is assigned to *c.
* Output:
* return GlReadStatus The completion status of the read operation.
*/
static GlReadStatus gl_read_input(GetLine *gl, char *c)
{
/*
* We may have to repeat the read if window change signals are received.
*/
for(;;) {
/*
* Which file descriptor should we read from? Mark this volatile, so
* that siglongjmp() can't clobber it.
*/
volatile int fd = gl->file_fp ? fileno(gl->file_fp) : gl->input_fd;
/*
* If the endline flag becomes set, don't wait for another character.
*/
if(gl->endline)
return GL_READ_ERROR;
/*
* Since the code in this function can block, trap signals.
*/
if(sigsetjmp(gl_setjmp_buffer, 1)==0) {
/*
* Handle the different I/O modes.
*/
switch(gl->io_mode) {
/*
* In normal I/O mode, we call the event handler before attempting
* to read, since read() blocks.
*/
case GL_NORMAL_MODE:
if(gl_event_handler(gl, fd))
return GL_READ_ERROR;
return gl_read_unmasked(gl, fd, c); /* Read one character */
break;
/*
* In non-blocking server I/O mode, we attempt to read a character,
* and only if this fails, call the event handler to wait for a any
* user-configured timeout and any other user-configured events. In
* addition, we turn off the fcntl() non-blocking flag when reading
* from the terminal, to work around a bug in Solaris. We can do this
* without causing the read() to block, because when in non-blocking
* server-I/O mode, gl_raw_io() sets the VMIN terminal attribute to 0,
* which tells the terminal driver to return immediately if no
* characters are available to be read.
*/
case GL_SERVER_MODE:
{
GlReadStatus status; /* The return status */
if(isatty(fd)) /* If we reading from a terminal, */
gl_blocking_io(gl, fd); /* switch to blocking I/O */
status = gl_read_unmasked(gl, fd, c); /* Try reading */
if(status == GL_READ_BLOCKED) { /* Nothing readable yet */
if(gl_event_handler(gl, fd)) /* Wait for input */
status = GL_READ_ERROR;
else
status = gl_read_unmasked(gl, fd, c); /* Try reading again */
};
gl_nonblocking_io(gl, fd); /* Restore non-blocking I/O */
return status;
};
break;
};
};
/*
* To get here, one of the signals that we are trapping must have
* been received. Note that by using sigsetjmp() instead of setjmp()
* the signal mask that was blocking these signals will have been
* reinstated, so we can be sure that no more of these signals will
* be received until we explicitly unblock them again.
*
* First, if non-blocking I/O was temporarily disabled, reinstate it.
*/
if(gl->io_mode == GL_SERVER_MODE)
gl_nonblocking_io(gl, fd);
/*
* Now respond to the signal that was caught.
*/
if(gl_check_caught_signal(gl))
return GL_READ_ERROR;
};
}
/*.......................................................................
* This is a private function of gl_read_input(), which unblocks signals
* temporarily while it reads a single character from the specified file
* descriptor.
*
* Input:
* gl GetLine * The resource object of this module.
* fd int The file descriptor to read from.
* c char * The character that was read is assigned to *c.
* Output:
* return GlReadStatus The completion status of the read.
*/
static int gl_read_unmasked(GetLine *gl, int fd, char *c)
{
int nread; /* The return value of read() */
/*
* Unblock the signals that we are trapping, while waiting for I/O.
*/
gl_catch_signals(gl);
/*
* Attempt to read one character from the terminal, restarting the read
* if any signals that we aren't trapping, are received.
*/
do {
errno = 0;
nread = read(fd, c, 1);
} while(nread < 0 && errno==EINTR);
/*
* Block all of the signals that we are trapping.
*/
gl_mask_signals(gl, NULL);
/*
* Check the completion status of the read.
*/
switch(nread) {
case 1:
return GL_READ_OK;
case 0:
return (errno != 0 || isatty(fd)) ? GL_READ_BLOCKED : GL_READ_EOF;
default:
return GL_READ_ERROR;
};
}
/*.......................................................................
* Remove a specified number of characters from the start of the
* key-press lookahead buffer, gl->keybuf[], and arrange for the next
* read to start from the character at the start of the shifted buffer.
*
* Input:
* gl GetLine * The resource object of this module.
* nused int The number of characters to discard from the start
* of the buffer.
*/
static void gl_discard_chars(GetLine *gl, int nused)
{
int nkeep = gl->nbuf - nused;
if(nkeep > 0) {
memmove(gl->keybuf, gl->keybuf + nused, nkeep);
gl->nbuf = nkeep;
gl->nread = 0;
} else {
gl->nbuf = gl->nread = 0;
};
}
/*.......................................................................
* This function is called to handle signals caught between calls to
* sigsetjmp() and siglongjmp().
*
* Input:
* gl GetLine * The resource object of this library.
* Output:
* return int 0 - Signal handled internally.
* 1 - Signal requires gl_get_line() to abort.
*/
static int gl_check_caught_signal(GetLine *gl)
{
GlSignalNode *sig; /* The signal disposition */
SigAction keep_action; /* The signal disposition of tecla signal handlers */
unsigned flags; /* The signal processing flags to use */
int signo; /* The signal to be handled */
/*
* Was no signal caught?
*/
if(gl_pending_signal == -1)
return 0;
/*
* Get the signal to be handled.
*/
signo = gl_pending_signal;
/*
* Mark the signal as handled. Note that at this point, all of
* the signals that we are trapping are blocked from delivery.
*/
gl_pending_signal = -1;
/*
* Record the signal that was caught, so that the user can query it later.
*/
gl->last_signal = signo;
/*
* In non-blocking server mode, the application is responsible for
* responding to terminal signals, and we don't want gl_get_line()s
* normal signal handling to clash with this, so whenever a signal
* is caught, we arrange for gl_get_line() to abort and requeue the
* signal while signals are still blocked. If the application
* had the signal unblocked when gl_get_line() was called, the signal
* will be delivered again as soon as gl_get_line() restores the
* process signal mask, just before returning to the application.
* Note that the caller of this function should set gl->pending_io
* to the appropriate choice of GLP_READ and GLP_WRITE, before returning.
*/
if(gl->io_mode==GL_SERVER_MODE) {
gl_record_status(gl, GLR_SIGNAL, EINTR);
raise(signo);
return 1;
};
/*
* Lookup the requested disposition of this signal.
*/
for(sig=gl->sigs; sig && sig->signo != signo; sig=sig->next)
;
if(!sig)
return 0;
/*
* Get the signal response flags for this signal.
*/
flags = sig->flags;
/*
* Did we receive a terminal size signal?
*/
#ifdef SIGWINCH
if(signo == SIGWINCH && _gl_update_size(gl))
return 1;
#endif
/*
* Start a fresh line?
*/
if(flags & GLS_RESTORE_LINE) {
if(gl_start_newline(gl, 0))
return 1;
};
/*
* Restore terminal settings to how they were before gl_get_line() was
* called?
*/
if(flags & GLS_RESTORE_TTY)
gl_restore_terminal_attributes(gl);
/*
* Restore signal handlers to how they were before gl_get_line() was
* called? If this hasn't been requested, only reinstate the signal
* handler of the signal that we are handling.
*/
if(flags & GLS_RESTORE_SIG) {
gl_restore_signal_handlers(gl);
gl_unmask_signals(gl, &gl->old_signal_set);
} else {
(void) sigaction(sig->signo, &sig->original, &keep_action);
(void) sigprocmask(SIG_UNBLOCK, &sig->proc_mask, NULL);
};
/*
* Forward the signal to the application's signal handler.
*/
if(!(flags & GLS_DONT_FORWARD))
raise(signo);
/*
* Reinstate our signal handlers.
*/
if(flags & GLS_RESTORE_SIG) {
gl_mask_signals(gl, NULL);
gl_override_signal_handlers(gl);
} else {
(void) sigaction(sig->signo, &keep_action, NULL);
(void) sigprocmask(SIG_BLOCK, &sig->proc_mask, NULL);
};
/*
* Do we need to reinstate our terminal settings?
*/
if(flags & GLS_RESTORE_TTY)
gl_raw_terminal_mode(gl);
/*
* Redraw the line?
*/
if(flags & GLS_REDRAW_LINE)
gl_queue_redisplay(gl);
/*
* What next?
*/
switch(sig->after) {
case GLS_RETURN:
gl_newline(gl, 1, NULL);
return gl_flush_output(gl);
break;
case GLS_ABORT:
gl_record_status(gl, GLR_SIGNAL, sig->errno_value);
return 1;
break;
case GLS_CONTINUE:
return gl_flush_output(gl);
break;
};
return 0;
}
/*.......................................................................
* Get pertinent terminal control strings and the initial terminal size.
*
* Input:
* gl GetLine * The resource object of this library.
* term char * The type of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_control_strings(GetLine *gl, const char *term)
{
int bad_term = 0; /* True if term is unusable */
/*
* Discard any existing control strings from a previous terminal.
*/
gl->left = NULL;
gl->right = NULL;
gl->up = NULL;
gl->down = NULL;
gl->home = NULL;
gl->bol = 0;
gl->clear_eol = NULL;
gl->clear_eod = NULL;
gl->u_arrow = NULL;
gl->d_arrow = NULL;
gl->l_arrow = NULL;
gl->r_arrow = NULL;
gl->sound_bell = NULL;
gl->bold = NULL;
gl->underline = NULL;
gl->standout = NULL;
gl->dim = NULL;
gl->reverse = NULL;
gl->blink = NULL;
gl->text_attr_off = NULL;
gl->nline = 0;
gl->ncolumn = 0;
#ifdef USE_TERMINFO
gl->left_n = NULL;
gl->right_n = NULL;
#endif
/*
* If possible lookup the information in a terminal information
* database.
*/
#ifdef USE_TERMINFO
{
int errret;
if(!term || setupterm((char *)term, gl->input_fd, &errret) == ERR) {
bad_term = 1;
} else {
_clr_StringGroup(gl->capmem);
gl->left = gl_tigetstr(gl, "cub1");
gl->right = gl_tigetstr(gl, "cuf1");
gl->up = gl_tigetstr(gl, "cuu1");
gl->down = gl_tigetstr(gl, "cud1");
gl->home = gl_tigetstr(gl, "home");
gl->clear_eol = gl_tigetstr(gl, "el");
gl->clear_eod = gl_tigetstr(gl, "ed");
gl->u_arrow = gl_tigetstr(gl, "kcuu1");
gl->d_arrow = gl_tigetstr(gl, "kcud1");
gl->l_arrow = gl_tigetstr(gl, "kcub1");
gl->r_arrow = gl_tigetstr(gl, "kcuf1");
gl->left_n = gl_tigetstr(gl, "cub");
gl->right_n = gl_tigetstr(gl, "cuf");
gl->sound_bell = gl_tigetstr(gl, "bel");
gl->bold = gl_tigetstr(gl, "bold");
gl->underline = gl_tigetstr(gl, "smul");
gl->standout = gl_tigetstr(gl, "smso");
gl->dim = gl_tigetstr(gl, "dim");
gl->reverse = gl_tigetstr(gl, "rev");
gl->blink = gl_tigetstr(gl, "blink");
gl->text_attr_off = gl_tigetstr(gl, "sgr0");
};
};
#elif defined(USE_TERMCAP)
if(!term || tgetent(gl->tgetent_buf, (char *)term) < 0) {
bad_term = 1;
} else {
char *tgetstr_buf_ptr = gl->tgetstr_buf;
_clr_StringGroup(gl->capmem);
gl->left = gl_tgetstr(gl, "le", &tgetstr_buf_ptr);
gl->right = gl_tgetstr(gl, "nd", &tgetstr_buf_ptr);
gl->up = gl_tgetstr(gl, "up", &tgetstr_buf_ptr);
gl->down = gl_tgetstr(gl, "do", &tgetstr_buf_ptr);
gl->home = gl_tgetstr(gl, "ho", &tgetstr_buf_ptr);
gl->clear_eol = gl_tgetstr(gl, "ce", &tgetstr_buf_ptr);
gl->clear_eod = gl_tgetstr(gl, "cd", &tgetstr_buf_ptr);
gl->u_arrow = gl_tgetstr(gl, "ku", &tgetstr_buf_ptr);
gl->d_arrow = gl_tgetstr(gl, "kd", &tgetstr_buf_ptr);
gl->l_arrow = gl_tgetstr(gl, "kl", &tgetstr_buf_ptr);
gl->r_arrow = gl_tgetstr(gl, "kr", &tgetstr_buf_ptr);
gl->sound_bell = gl_tgetstr(gl, "bl", &tgetstr_buf_ptr);
gl->bold = gl_tgetstr(gl, "md", &tgetstr_buf_ptr);
gl->underline = gl_tgetstr(gl, "us", &tgetstr_buf_ptr);
gl->standout = gl_tgetstr(gl, "so", &tgetstr_buf_ptr);
gl->dim = gl_tgetstr(gl, "mh", &tgetstr_buf_ptr);
gl->reverse = gl_tgetstr(gl, "mr", &tgetstr_buf_ptr);
gl->blink = gl_tgetstr(gl, "mb", &tgetstr_buf_ptr);
gl->text_attr_off = gl_tgetstr(gl, "me", &tgetstr_buf_ptr);
};
#endif
/*
* Report term being unusable.
*/
if(bad_term) {
gl_print_info(gl, "Bad terminal type: \"", term ? term : "(null)",
"\". Will assume vt100.", GL_END_INFO);
};
/*
* Fill in missing information with ANSI VT100 strings.
*/
if(!gl->left)
gl->left = "\b"; /* ^H */
if(!gl->right)
gl->right = GL_ESC_STR "[C";
if(!gl->up)
gl->up = GL_ESC_STR "[A";
if(!gl->down)
gl->down = "\n";
if(!gl->home)
gl->home = GL_ESC_STR "[H";
if(!gl->bol)
gl->bol = "\r";
if(!gl->clear_eol)
gl->clear_eol = GL_ESC_STR "[K";
if(!gl->clear_eod)
gl->clear_eod = GL_ESC_STR "[J";
if(!gl->u_arrow)
gl->u_arrow = GL_ESC_STR "[A";
if(!gl->d_arrow)
gl->d_arrow = GL_ESC_STR "[B";
if(!gl->l_arrow)
gl->l_arrow = GL_ESC_STR "[D";
if(!gl->r_arrow)
gl->r_arrow = GL_ESC_STR "[C";
if(!gl->sound_bell)
gl->sound_bell = "\a";
if(!gl->bold)
gl->bold = GL_ESC_STR "[1m";
if(!gl->underline)
gl->underline = GL_ESC_STR "[4m";
if(!gl->standout)
gl->standout = GL_ESC_STR "[1;7m";
if(!gl->dim)
gl->dim = ""; /* Not available */
if(!gl->reverse)
gl->reverse = GL_ESC_STR "[7m";
if(!gl->blink)
gl->blink = GL_ESC_STR "[5m";
if(!gl->text_attr_off)
gl->text_attr_off = GL_ESC_STR "[m";
/*
* Find out the current terminal size.
*/
(void) _gl_terminal_size(gl, GL_DEF_NCOLUMN, GL_DEF_NLINE, NULL);
return 0;
}
#ifdef USE_TERMINFO
/*.......................................................................
* This is a private function of gl_control_strings() used to look up
* a termninal capability string from the terminfo database and make
* a private copy of it.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* name const char * The name of the terminfo string to look up.
* Output:
* return const char * The local copy of the capability, or NULL
* if not available.
*/
static const char *gl_tigetstr(GetLine *gl, const char *name)
{
const char *value = tigetstr((char *)name);
if(!value || value == (char *) -1)
return NULL;
return _sg_store_string(gl->capmem, value, 0);
}
#elif defined(USE_TERMCAP)
/*.......................................................................
* This is a private function of gl_control_strings() used to look up
* a termninal capability string from the termcap database and make
* a private copy of it. Note that some emulations of tgetstr(), such
* as that used by Solaris, ignores the buffer pointer that is past to
* it, so we can't assume that a private copy has been made that won't
* be trashed by another call to gl_control_strings() by another
* GetLine object. So we make what may be a redundant private copy
* of the string in gl->capmem.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* name const char * The name of the terminfo string to look up.
* Input/Output:
* bufptr char ** On input *bufptr points to the location in
* gl->tgetstr_buf at which to record the
* capability string. On output *bufptr is
* incremented over the stored string.
* Output:
* return const char * The local copy of the capability, or NULL
* on error.
*/
static const char *gl_tgetstr(GetLine *gl, const char *name, char **bufptr)
{
const char *value = tgetstr((char *)name, bufptr);
if(!value || value == (char *) -1)
return NULL;
return _sg_store_string(gl->capmem, value, 0);
}
#endif
/*.......................................................................
* This is an action function that implements a user interrupt (eg. ^C).
*/
static KT_KEY_FN(gl_user_interrupt)
{
raise(SIGINT);
return 1;
}
/*.......................................................................
* This is an action function that implements the abort signal.
*/
static KT_KEY_FN(gl_abort)
{
raise(SIGABRT);
return 1;
}
/*.......................................................................
* This is an action function that sends a suspend signal (eg. ^Z) to the
* the parent process.
*/
static KT_KEY_FN(gl_suspend)
{
raise(SIGTSTP);
return 0;
}
/*.......................................................................
* This is an action function that halts output to the terminal.
*/
static KT_KEY_FN(gl_stop_output)
{
tcflow(gl->output_fd, TCOOFF);
return 0;
}
/*.......................................................................
* This is an action function that resumes halted terminal output.
*/
static KT_KEY_FN(gl_start_output)
{
tcflow(gl->output_fd, TCOON);
return 0;
}
/*.......................................................................
* This is an action function that allows the next character to be accepted
* without any interpretation as a special character.
*/
static KT_KEY_FN(gl_literal_next)
{
char c; /* The character to be added to the line */
int i;
/*
* Get the character to be inserted literally.
*/
if(gl_read_terminal(gl, 1, &c))
return 1;
/*
* Add the character to the line 'count' times.
*/
for(i=0; i<count; i++)
gl_add_char_to_line(gl, c);
return 0;
}
/*.......................................................................
* Return the width of a tab character at a given position when
* displayed at a given position on the terminal. This is needed
* because the width of tab characters depends on where they are,
* relative to the preceding tab stops.
*
* Input:
* gl GetLine * The resource object of this library.
* term_curpos int The destination terminal location of the character.
* Output:
* return int The number of terminal charaters needed.
*/
static int gl_displayed_tab_width(GetLine *gl, int term_curpos)
{
return TAB_WIDTH - ((term_curpos % gl->ncolumn) % TAB_WIDTH);
}
/*.......................................................................
* Return the number of characters needed to display a given character
* on the screen. Tab characters require eight spaces, and control
* characters are represented by a caret followed by the modified
* character.
*
* Input:
* gl GetLine * The resource object of this library.
* c char The character to be displayed.
* term_curpos int The destination terminal location of the character.
* This is needed because the width of tab characters
* depends on where they are, relative to the
* preceding tab stops.
* Output:
* return int The number of terminal charaters needed.
*/
static int gl_displayed_char_width(GetLine *gl, char c, int term_curpos)
{
if(c=='\t')
return gl_displayed_tab_width(gl, term_curpos);
if(IS_CTRL_CHAR(c))
return 2;
if(!isprint((int)(unsigned char) c))
return gl_octal_width((int)(unsigned char)c) + 1;
return 1;
}
/*.......................................................................
* Work out the length of given string of characters on the terminal.
*
* Input:
* gl GetLine * The resource object of this library.
* string char * The string to be measured.
* nc int The number of characters to be measured, or -1
* to measure the whole string.
* term_curpos int The destination terminal location of the character.
* This is needed because the width of tab characters
* depends on where they are, relative to the
* preceding tab stops.
* Output:
* return int The number of displayed characters.
*/
static int gl_displayed_string_width(GetLine *gl, const char *string, int nc,
int term_curpos)
{
int slen = 0; /* The displayed number of characters */
int i;
/*
* How many characters are to be measured?
*/
if(nc < 0)
nc = strlen(string);
/*
* Add up the length of the displayed string.
*/
for(i=0; i<nc; i++)
slen += gl_displayed_char_width(gl, string[i], term_curpos + slen);
return slen;
}
/*.......................................................................
* Write a string verbatim to the current terminal or output stream.
*
* Note that when async-signal safety is required, the 'buffered'
* argument must be 0, and n must not be -1.
*
* Input:
* gl GetLine * The resource object of the gl_get_line().
* buffered int If true, used buffered I/O when writing to
* the terminal. Otherwise use async-signal-safe
* unbuffered I/O.
* string const char * The string to be written (this need not be
* '\0' terminated unless n<0).
* n int The number of characters to write from the
* prefix of string[], or -1 to request that
* gl_print_raw_string() use strlen() to figure
* out the length.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_print_raw_string(GetLine *gl, int buffered,
const char *string, int n)
{
GlWriteFn *write_fn = buffered ? gl_write_fn : gl->flush_fn;
/*
* Only display output when echoing is turned on.
*/
if(gl->echo) {
int ndone = 0; /* The number of characters written so far */
/*
* When using un-buffered I/O, flush pending output first.
*/
if(!buffered) {
if(gl_flush_output(gl))
return 1;
};
/*
* If no length has been provided, measure the length of the string.
*/
if(n < 0)
n = strlen(string);
/*
* Write the string.
*/
if(write_fn(gl, string + ndone, n-ndone) != n)
return 1;
};
return 0;
}
/*.......................................................................
* Output a terminal control sequence. When using terminfo,
* this must be a sequence returned by tgetstr() or tigetstr()
* respectively.
*
* Input:
* gl GetLine * The resource object of this library.
* nline int The number of lines affected by the operation,
* or 1 if not relevant.
* string char * The control sequence to be sent.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_print_control_sequence(GetLine *gl, int nline, const char *string)
{
int waserr = 0; /* True if an error occurs */
/*
* Only write characters to the terminal when echoing is enabled.
*/
if(gl->echo) {
#if defined(USE_TERMINFO) || defined(USE_TERMCAP)
tputs_gl = gl;
errno = 0;
tputs((char *)string, nline, gl_tputs_putchar);
waserr = errno != 0;
#else
waserr = gl_print_raw_string(gl, 1, string, -1);
#endif
};
return waserr;
}
#if defined(USE_TERMINFO) || defined(USE_TERMCAP)
/*.......................................................................
* The following callback function is called by tputs() to output a raw
* control character to the terminal.
*/
static TputsRetType gl_tputs_putchar(TputsArgType c)
{
char ch = c;
#if TPUTS_RETURNS_VALUE
return gl_print_raw_string(tputs_gl, 1, &ch, 1);
#else
(void) gl_print_raw_string(tputs_gl, 1, &ch, 1);
#endif
}
#endif
/*.......................................................................
* Move the terminal cursor n characters to the left or right.
*
* Input:
* gl GetLine * The resource object of this program.
* n int number of positions to the right (> 0) or left (< 0).
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_terminal_move_cursor(GetLine *gl, int n)
{
int cur_row, cur_col; /* The current terminal row and column index of */
/* the cursor wrt the start of the input line. */
int new_row, new_col; /* The target terminal row and column index of */
/* the cursor wrt the start of the input line. */
/*
* Do nothing if the input line isn't currently displayed. In this
* case, the cursor will be moved to the right place when the line
* is next redisplayed.
*/
if(!gl->displayed)
return 0;
/*
* How far can we move left?
*/
if(gl->term_curpos + n < 0)
n = gl->term_curpos;
/*
* Break down the current and target cursor locations into rows and columns.
*/
cur_row = gl->term_curpos / gl->ncolumn;
cur_col = gl->term_curpos % gl->ncolumn;
new_row = (gl->term_curpos + n) / gl->ncolumn;
new_col = (gl->term_curpos + n) % gl->ncolumn;
/*
* Move down to the next line.
*/
for(; cur_row < new_row; cur_row++) {
if(gl_print_control_sequence(gl, 1, gl->down))
return 1;
};
/*
* Move up to the previous line.
*/
for(; cur_row > new_row; cur_row--) {
if(gl_print_control_sequence(gl, 1, gl->up))
return 1;
};
/*
* Move to the right within the target line?
*/
if(cur_col < new_col) {
#ifdef USE_TERMINFO
/*
* Use a parameterized control sequence if it generates less control
* characters (guess based on ANSI terminal termcap entry).
*/
if(gl->right_n != NULL && new_col - cur_col > 1) {
if(gl_print_control_sequence(gl, 1, tparm((char *)gl->right_n,
(long)(new_col - cur_col), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
return 1;
} else
#endif
{
for(; cur_col < new_col; cur_col++) {
if(gl_print_control_sequence(gl, 1, gl->right))
return 1;
};
};
/*
* Move to the left within the target line?
*/
} else if(cur_col > new_col) {
#ifdef USE_TERMINFO
/*
* Use a parameterized control sequence if it generates less control
* characters (guess based on ANSI terminal termcap entry).
*/
if(gl->left_n != NULL && cur_col - new_col > 3) {
if(gl_print_control_sequence(gl, 1, tparm((char *)gl->left_n,
(long)(cur_col - new_col), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
return 1;
} else
#endif
{
for(; cur_col > new_col; cur_col--) {
if(gl_print_control_sequence(gl, 1, gl->left))
return 1;
};
};
}
/*
* Update the recorded position of the terminal cursor.
*/
gl->term_curpos += n;
return 0;
}
/*.......................................................................
* Write a character to the terminal after expanding tabs and control
* characters to their multi-character representations.
*
* Input:
* gl GetLine * The resource object of this program.
* c char The character to be output.
* pad char Many terminals have the irritating feature that
* when one writes a character in the last column of
* of the terminal, the cursor isn't wrapped to the
* start of the next line until one more character
* is written. Some terminals don't do this, so
* after such a write, we don't know where the
* terminal is unless we output an extra character.
* This argument specifies the character to write.
* If at the end of the input line send '\0' or a
* space, and a space will be written. Otherwise,
* pass the next character in the input line
* following the one being written.
* Output:
* return int 0 - OK.
*/
static int gl_print_char(GetLine *gl, char c, char pad)
{
char string[TAB_WIDTH + 4]; /* A work area for composing compound strings */
int nchar; /* The number of terminal characters */
int i;
/*
* Check for special characters.
*/
if(c == '\t') {
/*
* How many spaces do we need to represent a tab at the current terminal
* column?
*/
nchar = gl_displayed_tab_width(gl, gl->term_curpos);
/*
* Compose the tab string.
*/
for(i=0; i<nchar; i++)
string[i] = ' ';
} else if(IS_CTRL_CHAR(c)) {
string[0] = '^';
string[1] = CTRL_TO_CHAR(c);
nchar = 2;
} else if(!isprint((int)(unsigned char) c)) {
snprintf(string, sizeof(string), "\\%o", (int)(unsigned char)c);
nchar = strlen(string);
} else {
string[0] = c;
nchar = 1;
};
/*
* Terminate the string.
*/
string[nchar] = '\0';
/*
* Write the string to the terminal.
*/
if(gl_print_raw_string(gl, 1, string, -1))
return 1;
/*
* Except for one exception to be described in a moment, the cursor should
* now have been positioned after the character that was just output.
*/
gl->term_curpos += nchar;
/*
* Keep a record of the number of characters in the terminal version
* of the input line.
*/
if(gl->term_curpos > gl->term_len)
gl->term_len = gl->term_curpos;
/*
* If the new character ended exactly at the end of a line,
* most terminals won't move the cursor onto the next line until we
* have written a character on the next line, so append an extra
* space then move the cursor back.
*/
if(gl->term_curpos % gl->ncolumn == 0) {
int term_curpos = gl->term_curpos;
if(gl_print_char(gl, pad ? pad : ' ', ' ') ||
gl_set_term_curpos(gl, term_curpos))
return 1;
};
return 0;
}
/*.......................................................................
* Write a string to the terminal after expanding tabs and control
* characters to their multi-character representations.
*
* Input:
* gl GetLine * The resource object of this program.
* string char * The string to be output.
* pad char Many terminals have the irritating feature that
* when one writes a character in the last column of
* of the terminal, the cursor isn't wrapped to the
* start of the next line until one more character
* is written. Some terminals don't do this, so
* after such a write, we don't know where the
* terminal is unless we output an extra character.
* This argument specifies the character to write.
* If at the end of the input line send '\0' or a
* space, and a space will be written. Otherwise,
* pass the next character in the input line
* following the one being written.
* Output:
* return int 0 - OK.
*/
static int gl_print_string(GetLine *gl, const char *string, char pad)
{
const char *cptr; /* A pointer into string[] */
for(cptr=string; *cptr; cptr++) {
char nextc = cptr[1];
if(gl_print_char(gl, *cptr, nextc ? nextc : pad))
return 1;
};
return 0;
}
/*.......................................................................
* Move the terminal cursor position.
*
* Input:
* gl GetLine * The resource object of this library.
* term_curpos int The destination terminal cursor position.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_set_term_curpos(GetLine *gl, int term_curpos)
{
return gl_terminal_move_cursor(gl, term_curpos - gl->term_curpos);
}
/*.......................................................................
* This is an action function that moves the buffer cursor one character
* left, and updates the terminal cursor to match.
*/
static KT_KEY_FN(gl_cursor_left)
{
return gl_place_cursor(gl, gl->buff_curpos - count);
}
/*.......................................................................
* This is an action function that moves the buffer cursor one character
* right, and updates the terminal cursor to match.
*/
static KT_KEY_FN(gl_cursor_right)
{
return gl_place_cursor(gl, gl->buff_curpos + count);
}
/*.......................................................................
* This is an action function that toggles between overwrite and insert
* mode.
*/
static KT_KEY_FN(gl_insert_mode)
{
gl->insert = !gl->insert;
return 0;
}
/*.......................................................................
* This is an action function which moves the cursor to the beginning of
* the line.
*/
static KT_KEY_FN(gl_beginning_of_line)
{
return gl_place_cursor(gl, 0);
}
/*.......................................................................
* This is an action function which moves the cursor to the end of
* the line.
*/
static KT_KEY_FN(gl_end_of_line)
{
return gl_place_cursor(gl, gl->ntotal);
}
/*.......................................................................
* This is an action function which deletes the entire contents of the
* current line.
*/
static KT_KEY_FN(gl_delete_line)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Copy the contents of the line to the cut buffer.
*/
strlcpy(gl->cutbuf, gl->line, gl->linelen);
/*
* Clear the buffer.
*/
gl_truncate_buffer(gl, 0);
/*
* Move the terminal cursor to just after the prompt.
*/
if(gl_place_cursor(gl, 0))
return 1;
/*
* Clear from the end of the prompt to the end of the terminal.
*/
if(gl_truncate_display(gl))
return 1;
return 0;
}
/*.......................................................................
* This is an action function which deletes all characters between the
* current cursor position and the end of the line.
*/
static KT_KEY_FN(gl_kill_line)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Copy the part of the line that is about to be deleted to the cut buffer.
*/
strlcpy(gl->cutbuf, gl->line + gl->buff_curpos, gl->linelen);
/*
* Terminate the buffered line at the current cursor position.
*/
gl_truncate_buffer(gl, gl->buff_curpos);
/*
* Clear the part of the line that follows the cursor.
*/
if(gl_truncate_display(gl))
return 1;
/*
* Explicitly reset the cursor position to allow vi command mode
* constraints on its position to be set.
*/
return gl_place_cursor(gl, gl->buff_curpos);
}
/*.......................................................................
* This is an action function which deletes all characters between the
* start of the line and the current cursor position.
*/
static KT_KEY_FN(gl_backward_kill_line)
{
/*
* How many characters are to be deleted from before the cursor?
*/
int nc = gl->buff_curpos - gl->insert_curpos;
if (!nc)
return 0;
/*
* Move the cursor to the start of the line, or in vi input mode,
* the start of the sub-line at which insertion started, and delete
* up to the old cursor position.
*/
return gl_place_cursor(gl, gl->insert_curpos) ||
gl_delete_chars(gl, nc, gl->editor == GL_EMACS_MODE || gl->vi.command);
}
/*.......................................................................
* This is an action function which moves the cursor forward by a word.
*/
static KT_KEY_FN(gl_forward_word)
{
return gl_place_cursor(gl, gl_nth_word_end_forward(gl, count) +
(gl->editor==GL_EMACS_MODE));
}
/*.......................................................................
* This is an action function which moves the cursor forward to the start
* of the next word.
*/
static KT_KEY_FN(gl_forward_to_word)
{
return gl_place_cursor(gl, gl_nth_word_start_forward(gl, count));
}
/*.......................................................................
* This is an action function which moves the cursor backward by a word.
*/
static KT_KEY_FN(gl_backward_word)
{
return gl_place_cursor(gl, gl_nth_word_start_backward(gl, count));
}
/*.......................................................................
* Delete one or more characters, starting with the one under the cursor.
*
* Input:
* gl GetLine * The resource object of this library.
* nc int The number of characters to delete.
* cut int If true, copy the characters to the cut buffer.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_delete_chars(GetLine *gl, int nc, int cut)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* If there are fewer than nc characters following the cursor, limit
* nc to the number available.
*/
if(gl->buff_curpos + nc > gl->ntotal)
nc = gl->ntotal - gl->buff_curpos;
/*
* Copy the about to be deleted region to the cut buffer.
*/
if(cut) {
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, nc);
gl->cutbuf[nc] = '\0';
}
/*
* Nothing to delete?
*/
if(nc <= 0)
return 0;
/*
* In vi overwrite mode, restore any previously overwritten characters
* from the undo buffer.
*/
if(gl->editor == GL_VI_MODE && !gl->vi.command && !gl->insert) {
/*
* How many of the characters being deleted can be restored from the
* undo buffer?
*/
int nrestore = gl->buff_curpos + nc <= gl->vi.undo.ntotal ?
nc : gl->vi.undo.ntotal - gl->buff_curpos;
/*
* Restore any available characters.
*/
if(nrestore > 0) {
gl_buffer_string(gl, gl->vi.undo.line + gl->buff_curpos, nrestore,
gl->buff_curpos);
};
/*
* If their were insufficient characters in the undo buffer, then this
* implies that we are deleting from the end of the line, so we need
* to terminate the line either where the undo buffer ran out, or if
* we are deleting from beyond the end of the undo buffer, at the current
* cursor position.
*/
if(nc != nrestore) {
gl_truncate_buffer(gl, (gl->vi.undo.ntotal > gl->buff_curpos) ?
gl->vi.undo.ntotal : gl->buff_curpos);
};
} else {
/*
* Copy the remaining part of the line back over the deleted characters.
*/
gl_remove_from_buffer(gl, gl->buff_curpos, nc);
};
/*
* Redraw the remaining characters following the cursor.
*/
if(gl_print_string(gl, gl->line + gl->buff_curpos, '\0'))
return 1;
/*
* Clear to the end of the terminal.
*/
if(gl_truncate_display(gl))
return 1;
/*
* Place the cursor at the start of where the deletion was performed.
*/
return gl_place_cursor(gl, gl->buff_curpos);
}
/*.......................................................................
* This is an action function which deletes character(s) under the
* cursor without moving the cursor.
*/
static KT_KEY_FN(gl_forward_delete_char)
{
/*
* Delete 'count' characters.
*/
return gl_delete_chars(gl, count, gl->vi.command);
}
/*.......................................................................
* This is an action function which deletes character(s) under the
* cursor and moves the cursor back one character.
*/
static KT_KEY_FN(gl_backward_delete_char)
{
/*
* Restrict the deletion count to the number of characters that
* precede the insertion point.
*/
if(count > gl->buff_curpos - gl->insert_curpos)
count = gl->buff_curpos - gl->insert_curpos;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
return gl_cursor_left(gl, count, NULL) ||
gl_delete_chars(gl, count, gl->vi.command);
}
/*.......................................................................
* Starting from the cursor position delete to the specified column.
*/
static KT_KEY_FN(gl_delete_to_column)
{
if (--count >= gl->buff_curpos)
return gl_forward_delete_char(gl, count - gl->buff_curpos, NULL);
else
return gl_backward_delete_char(gl, gl->buff_curpos - count, NULL);
}
/*.......................................................................
* Starting from the cursor position delete characters to a matching
* parenthesis.
*/
static KT_KEY_FN(gl_delete_to_parenthesis)
{
int curpos = gl_index_of_matching_paren(gl);
if(curpos >= 0) {
gl_save_for_undo(gl);
if(curpos >= gl->buff_curpos)
return gl_forward_delete_char(gl, curpos - gl->buff_curpos + 1, NULL);
else
return gl_backward_delete_char(gl, ++gl->buff_curpos - curpos + 1, NULL);
};
return 0;
}
/*.......................................................................
* This is an action function which deletes from the cursor to the end
* of the word that the cursor is either in or precedes.
*/
static KT_KEY_FN(gl_forward_delete_word)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* In emacs mode delete to the end of the word. In vi mode delete to the
* start of the net word.
*/
if(gl->editor == GL_EMACS_MODE) {
return gl_delete_chars(gl,
gl_nth_word_end_forward(gl,count) - gl->buff_curpos + 1, 1);
} else {
return gl_delete_chars(gl,
gl_nth_word_start_forward(gl,count) - gl->buff_curpos,
gl->vi.command);
};
}
/*.......................................................................
* This is an action function which deletes the word that precedes the
* cursor.
*/
static KT_KEY_FN(gl_backward_delete_word)
{
/*
* Keep a record of the current cursor position.
*/
int buff_curpos = gl->buff_curpos;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Move back 'count' words.
*/
if(gl_backward_word(gl, count, NULL))
return 1;
/*
* Delete from the new cursor position to the original one.
*/
return gl_delete_chars(gl, buff_curpos - gl->buff_curpos,
gl->editor == GL_EMACS_MODE || gl->vi.command);
}
/*.......................................................................
* Searching in a given direction, delete to the count'th
* instance of a specified or queried character, in the input line.
*
* Input:
* gl GetLine * The getline resource object.
* count int The number of times to search.
* c char The character to be searched for, or '\0' if
* the character should be read from the user.
* forward int True if searching forward.
* onto int True if the search should end on top of the
* character, false if the search should stop
* one character before the character in the
* specified search direction.
* change int If true, this function is being called upon
* to do a vi change command, in which case the
* user will be left in insert mode after the
* deletion.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_delete_find(GetLine *gl, int count, char c, int forward,
int onto, int change)
{
/*
* Search for the character, and abort the deletion if not found.
*/
int pos = gl_find_char(gl, count, forward, onto, c);
if(pos < 0)
return 0;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Allow the cursor to be at the end of the line if this is a change
* command.
*/
if(change)
gl->vi.command = 0;
/*
* Delete the appropriate span of characters.
*/
if(forward) {
if(gl_delete_chars(gl, pos - gl->buff_curpos + 1, 1))
return 1;
} else {
int buff_curpos = gl->buff_curpos;
if(gl_place_cursor(gl, pos) ||
gl_delete_chars(gl, buff_curpos - gl->buff_curpos, 1))
return 1;
};
/*
* If this is a change operation, switch the insert mode.
*/
if(change && gl_vi_insert(gl, 0, NULL))
return 1;
return 0;
}
/*.......................................................................
* This is an action function which deletes forward from the cursor up to and
* including a specified character.
*/
static KT_KEY_FN(gl_forward_delete_find)
{
return gl_delete_find(gl, count, '\0', 1, 1, 0);
}
/*.......................................................................
* This is an action function which deletes backward from the cursor back to
* and including a specified character.
*/
static KT_KEY_FN(gl_backward_delete_find)
{
return gl_delete_find(gl, count, '\0', 0, 1, 0);
}
/*.......................................................................
* This is an action function which deletes forward from the cursor up to but
* not including a specified character.
*/
static KT_KEY_FN(gl_forward_delete_to)
{
return gl_delete_find(gl, count, '\0', 1, 0, 0);
}
/*.......................................................................
* This is an action function which deletes backward from the cursor back to
* but not including a specified character.
*/
static KT_KEY_FN(gl_backward_delete_to)
{
return gl_delete_find(gl, count, '\0', 0, 0, 0);
}
/*.......................................................................
* This is an action function which deletes to a character specified by a
* previous search.
*/
static KT_KEY_FN(gl_delete_refind)
{
return gl_delete_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
gl->vi.find_onto, 0);
}
/*.......................................................................
* This is an action function which deletes to a character specified by a
* previous search, but in the opposite direction.
*/
static KT_KEY_FN(gl_delete_invert_refind)
{
return gl_delete_find(gl, count, gl->vi.find_char,
!gl->vi.find_forward, gl->vi.find_onto, 0);
}
/*.......................................................................
* This is an action function which converts the characters in the word
* following the cursor to upper case.
*/
static KT_KEY_FN(gl_upcase_word)
{
/*
* Locate the count'th word ending after the cursor.
*/
int last = gl_nth_word_end_forward(gl, count);
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Upcase characters from the current cursor position to 'last'.
*/
while(gl->buff_curpos <= last) {
char *cptr = gl->line + gl->buff_curpos;
/*
* Convert the character to upper case?
*/
if(islower((int)(unsigned char) *cptr))
gl_buffer_char(gl, toupper((int) *cptr), gl->buff_curpos);
gl->buff_curpos++;
/*
* Write the possibly modified character back. Note that for non-modified
* characters we want to do this as well, so as to advance the cursor.
*/
if(gl_print_char(gl, *cptr, cptr[1]))
return 1;
};
return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
}
/*.......................................................................
* This is an action function which converts the characters in the word
* following the cursor to lower case.
*/
static KT_KEY_FN(gl_downcase_word)
{
/*
* Locate the count'th word ending after the cursor.
*/
int last = gl_nth_word_end_forward(gl, count);
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Upcase characters from the current cursor position to 'last'.
*/
while(gl->buff_curpos <= last) {
char *cptr = gl->line + gl->buff_curpos;
/*
* Convert the character to upper case?
*/
if(isupper((int)(unsigned char) *cptr))
gl_buffer_char(gl, tolower((int) *cptr), gl->buff_curpos);
gl->buff_curpos++;
/*
* Write the possibly modified character back. Note that for non-modified
* characters we want to do this as well, so as to advance the cursor.
*/
if(gl_print_char(gl, *cptr, cptr[1]))
return 1;
};
return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
}
/*.......................................................................
* This is an action function which converts the first character of the
* following word to upper case, in order to capitalize the word, and
* leaves the cursor at the end of the word.
*/
static KT_KEY_FN(gl_capitalize_word)
{
char *cptr; /* &gl->line[gl->buff_curpos] */
int first; /* True for the first letter of the word */
int i;
/*
* Keep a record of the current insert mode and the cursor position.
*/
int insert = gl->insert;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* We want to overwrite the modified word.
*/
gl->insert = 0;
/*
* Capitalize 'count' words.
*/
for(i=0; i<count && gl->buff_curpos < gl->ntotal; i++) {
int pos = gl->buff_curpos;
/*
* If we are not already within a word, skip to the start of the word.
*/
for(cptr = gl->line + pos ; pos<gl->ntotal && !gl_is_word_char((int) *cptr);
pos++, cptr++)
;
/*
* Move the cursor to the new position.
*/
if(gl_place_cursor(gl, pos))
return 1;
/*
* While searching for the end of the word, change lower case letters
* to upper case.
*/
for(first=1; gl->buff_curpos<gl->ntotal && gl_is_word_char((int) *cptr);
gl->buff_curpos++, cptr++) {
/*
* Convert the character to upper case?
*/
if(first) {
if(islower((int)(unsigned char) *cptr))
gl_buffer_char(gl, toupper((int) *cptr), cptr - gl->line);
} else {
if(isupper((int)(unsigned char) *cptr))
gl_buffer_char(gl, tolower((int) *cptr), cptr - gl->line);
};
first = 0;
/*
* Write the possibly modified character back. Note that for non-modified
* characters we want to do this as well, so as to advance the cursor.
*/
if(gl_print_char(gl, *cptr, cptr[1]))
return 1;
};
};
/*
* Restore the insertion mode.
*/
gl->insert = insert;
return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
}
/*.......................................................................
* This is an action function which redraws the current line.
*/
static KT_KEY_FN(gl_redisplay)
{
/*
* Keep a record of the current cursor position.
*/
int buff_curpos = gl->buff_curpos;
/*
* Do nothing if there is no line to be redisplayed.
*/
if(gl->endline)
return 0;
/*
* Erase the current input line.
*/
if(gl_erase_line(gl))
return 1;
/*
* Display the current prompt.
*/
if(gl_display_prompt(gl))
return 1;
/*
* Render the part of the line that the user has typed in so far.
*/
if(gl_print_string(gl, gl->line, '\0'))
return 1;
/*
* Restore the cursor position.
*/
if(gl_place_cursor(gl, buff_curpos))
return 1;
/*
* Mark the redisplay operation as having been completed.
*/
gl->redisplay = 0;
/*
* Flush the redisplayed line to the terminal.
*/
return gl_flush_output(gl);
}
/*.......................................................................
* This is an action function which clears the display and redraws the
* input line from the home position.
*/
static KT_KEY_FN(gl_clear_screen)
{
/*
* Home the cursor and clear from there to the end of the display.
*/
if(gl_print_control_sequence(gl, gl->nline, gl->home) ||
gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
return 1;
/*
* The input line is no longer displayed.
*/
gl_line_erased(gl);
/*
* Arrange for the input line to be redisplayed.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This is an action function which swaps the character under the cursor
* with the character to the left of the cursor.
*/
static KT_KEY_FN(gl_transpose_chars)
{
char from[3]; /* The original string of 2 characters */
char swap[3]; /* The swapped string of two characters */
/*
* If we are at the beginning or end of the line, there aren't two
* characters to swap.
*/
if(gl->buff_curpos < 1 || gl->buff_curpos >= gl->ntotal)
return 0;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Get the original and swapped strings of the two characters.
*/
from[0] = gl->line[gl->buff_curpos - 1];
from[1] = gl->line[gl->buff_curpos];
from[2] = '\0';
swap[0] = gl->line[gl->buff_curpos];
swap[1] = gl->line[gl->buff_curpos - 1];
swap[2] = '\0';
/*
* Move the cursor to the start of the two characters.
*/
if(gl_place_cursor(gl, gl->buff_curpos-1))
return 1;
/*
* Swap the two characters in the buffer.
*/
gl_buffer_char(gl, swap[0], gl->buff_curpos);
gl_buffer_char(gl, swap[1], gl->buff_curpos+1);
/*
* If the sum of the displayed width of the two characters
* in their current and final positions is the same, swapping can
* be done by just overwriting with the two swapped characters.
*/
if(gl_displayed_string_width(gl, from, -1, gl->term_curpos) ==
gl_displayed_string_width(gl, swap, -1, gl->term_curpos)) {
int insert = gl->insert;
gl->insert = 0;
if(gl_print_char(gl, swap[0], swap[1]) ||
gl_print_char(gl, swap[1], gl->line[gl->buff_curpos+2]))
return 1;
gl->insert = insert;
/*
* If the swapped substring has a different displayed size, we need to
* redraw everything after the first of the characters.
*/
} else {
if(gl_print_string(gl, gl->line + gl->buff_curpos, '\0') ||
gl_truncate_display(gl))
return 1;
};
/*
* Advance the cursor to the character after the swapped pair.
*/
return gl_place_cursor(gl, gl->buff_curpos + 2);
}
/*.......................................................................
* This is an action function which sets a mark at the current cursor
* location.
*/
static KT_KEY_FN(gl_set_mark)
{
gl->buff_mark = gl->buff_curpos;
return 0;
}
/*.......................................................................
* This is an action function which swaps the mark location for the
* cursor location.
*/
static KT_KEY_FN(gl_exchange_point_and_mark)
{
/*
* Get the old mark position, and limit to the extent of the input
* line.
*/
int old_mark = gl->buff_mark <= gl->ntotal ? gl->buff_mark : gl->ntotal;
/*
* Make the current cursor position the new mark.
*/
gl->buff_mark = gl->buff_curpos;
/*
* Move the cursor to the old mark position.
*/
return gl_place_cursor(gl, old_mark);
}
/*.......................................................................
* This is an action function which deletes the characters between the
* mark and the cursor, recording them in gl->cutbuf for later pasting.
*/
static KT_KEY_FN(gl_kill_region)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Limit the mark to be within the line.
*/
if(gl->buff_mark > gl->ntotal)
gl->buff_mark = gl->ntotal;
/*
* If there are no characters between the cursor and the mark, simply clear
* the cut buffer.
*/
if(gl->buff_mark == gl->buff_curpos) {
gl->cutbuf[0] = '\0';
return 0;
};
/*
* If the mark is before the cursor, swap the cursor and the mark.
*/
if(gl->buff_mark < gl->buff_curpos && gl_exchange_point_and_mark(gl,1,NULL))
return 1;
/*
* Delete the characters.
*/
if(gl_delete_chars(gl, gl->buff_mark - gl->buff_curpos, 1))
return 1;
/*
* Make the mark the same as the cursor position.
*/
gl->buff_mark = gl->buff_curpos;
return 0;
}
/*.......................................................................
* This is an action function which records the characters between the
* mark and the cursor, in gl->cutbuf for later pasting.
*/
static KT_KEY_FN(gl_copy_region_as_kill)
{
int ca, cb; /* The indexes of the first and last characters in the region */
int mark; /* The position of the mark */
/*
* Get the position of the mark, limiting it to lie within the line.
*/
mark = gl->buff_mark > gl->ntotal ? gl->ntotal : gl->buff_mark;
/*
* If there are no characters between the cursor and the mark, clear
* the cut buffer.
*/
if(mark == gl->buff_curpos) {
gl->cutbuf[0] = '\0';
return 0;
};
/*
* Get the line indexes of the first and last characters in the region.
*/
if(mark < gl->buff_curpos) {
ca = mark;
cb = gl->buff_curpos - 1;
} else {
ca = gl->buff_curpos;
cb = mark - 1;
};
/*
* Copy the region to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line + ca, cb + 1 - ca);
gl->cutbuf[cb + 1 - ca] = '\0';
return 0;
}
/*.......................................................................
* This is an action function which inserts the contents of the cut
* buffer at the current cursor location.
*/
static KT_KEY_FN(gl_yank)
{
int i;
/*
* Set the mark at the current location.
*/
gl->buff_mark = gl->buff_curpos;
/*
* Do nothing else if the cut buffer is empty.
*/
if(gl->cutbuf[0] == '\0')
return gl_ring_bell(gl, 1, NULL);
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Insert the string count times.
*/
for(i=0; i<count; i++) {
if(gl_add_string_to_line(gl, gl->cutbuf))
return 1;
};
/*
* gl_add_string_to_line() leaves the cursor after the last character that
* was pasted, whereas vi leaves the cursor over the last character pasted.
*/
if(gl->editor == GL_VI_MODE && gl_cursor_left(gl, 1, NULL))
return 1;
return 0;
}
/*.......................................................................
* This is an action function which inserts the contents of the cut
* buffer one character beyond the current cursor location.
*/
static KT_KEY_FN(gl_append_yank)
{
int was_command = gl->vi.command;
int i;
/*
* If the cut buffer is empty, ring the terminal bell.
*/
if(gl->cutbuf[0] == '\0')
return gl_ring_bell(gl, 1, NULL);
/*
* Set the mark at the current location + 1.
*/
gl->buff_mark = gl->buff_curpos + 1;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Arrange to paste the text in insert mode after the current character.
*/
if(gl_vi_append(gl, 0, NULL))
return 1;
/*
* Insert the string count times.
*/
for(i=0; i<count; i++) {
if(gl_add_string_to_line(gl, gl->cutbuf))
return 1;
};
/*
* Switch back to command mode if necessary.
*/
if(was_command)
gl_vi_command_mode(gl);
return 0;
}
/*.......................................................................
* Attempt to ask the terminal for its current size. On systems that
* don't support the TIOCWINSZ ioctl() for querying the terminal size,
* the current values of gl->ncolumn and gl->nrow are returned.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* ncolumn int * The number of columns will be assigned to *ncolumn.
* nline int * The number of lines will be assigned to *nline.
*/
static void gl_query_size(GetLine *gl, int *ncolumn, int *nline)
{
#ifdef TIOCGWINSZ
/*
* Query the new terminal window size. Ignore invalid responses.
*/
struct winsize size;
if(ioctl(gl->output_fd, TIOCGWINSZ, &size) == 0 &&
size.ws_row > 0 && size.ws_col > 0) {
*ncolumn = size.ws_col;
*nline = size.ws_row;
return;
};
#endif
/*
* Return the existing values.
*/
*ncolumn = gl->ncolumn;
*nline = gl->nline;
return;
}
/*.......................................................................
* Query the size of the terminal, and if it has changed, redraw the
* current input line accordingly.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _gl_update_size(GetLine *gl)
{
int ncolumn, nline; /* The new size of the terminal */
/*
* Query the new terminal window size.
*/
gl_query_size(gl, &ncolumn, &nline);
/*
* Update gl and the displayed line to fit the new dimensions.
*/
return gl_handle_tty_resize(gl, ncolumn, nline);
}
/*.......................................................................
* Redraw the current input line to account for a change in the terminal
* size. Also install the new size in gl.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* ncolumn int The new number of columns.
* nline int The new number of lines.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_handle_tty_resize(GetLine *gl, int ncolumn, int nline)
{
/*
* If the input device isn't a terminal, just record the new size.
*/
if(!gl->is_term) {
gl->nline = nline;
gl->ncolumn = ncolumn;
/*
* Has the size actually changed?
*/
} else if(ncolumn != gl->ncolumn || nline != gl->nline) {
/*
* If we are currently editing a line, erase it.
*/
if(gl_erase_line(gl))
return 1;
/*
* Update the recorded window size.
*/
gl->nline = nline;
gl->ncolumn = ncolumn;
/*
* Arrange for the input line to be redrawn before the next character
* is read from the terminal.
*/
gl_queue_redisplay(gl);
};
return 0;
}
/*.......................................................................
* This is the action function that recalls the previous line in the
* history buffer.
*/
static KT_KEY_FN(gl_up_history)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Forget any previous recall session.
*/
gl->preload_id = 0;
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* We don't want a search prefix for this function.
*/
if(_glh_search_prefix(gl->glh, gl->line, 0)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
/*
* Recall the count'th next older line in the history list. If the first one
* fails we can return since nothing has changed, otherwise we must continue
* and update the line state.
*/
if(_glh_find_backwards(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
while(--count && _glh_find_backwards(gl->glh, gl->line, gl->linelen+1))
;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange to have the cursor placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This is the action function that recalls the next line in the
* history buffer.
*/
static KT_KEY_FN(gl_down_history)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* If no search is currently in progress continue a previous recall
* session from a previous entered line if possible.
*/
if(_glh_line_id(gl->glh, 0) == 0 && gl->preload_id) {
_glh_recall_line(gl->glh, gl->preload_id, gl->line, gl->linelen+1);
gl->preload_id = 0;
} else {
/*
* We don't want a search prefix for this function.
*/
if(_glh_search_prefix(gl->glh, gl->line, 0)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
/*
* Recall the count'th next newer line in the history list. If the first one
* fails we can return since nothing has changed otherwise we must continue
* and update the line state.
*/
if(_glh_find_forwards(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
while(--count && _glh_find_forwards(gl->glh, gl->line, gl->linelen+1))
;
};
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange to have the cursor placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This is the action function that recalls the previous line in the
* history buffer whos prefix matches the characters that currently
* precede the cursor. By setting count=-1, this can be used internally
* to force searching for the prefix used in the last search.
*/
static KT_KEY_FN(gl_history_search_backward)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Forget any previous recall session.
*/
gl->preload_id = 0;
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* If a prefix search isn't already in progress, replace the search
* prefix to the string that precedes the cursor. In vi command mode
* include the character that is under the cursor in the string. If
* count<0 keep the previous search prefix regardless, so as to force
* a repeat search even if the last command wasn't a history command.
*/
if(count >= 0 && !_glh_search_active(gl->glh) &&
_glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
(gl->editor==GL_VI_MODE && gl->ntotal>0))) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
/*
* Search backwards for a match to the part of the line which precedes the
* cursor.
*/
if(_glh_find_backwards(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange to have the cursor placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This is the action function that recalls the previous line in the
* history buffer who's prefix matches that specified in an earlier call
* to gl_history_search_backward() or gl_history_search_forward().
*/
static KT_KEY_FN(gl_history_re_search_backward)
{
return gl_history_search_backward(gl, -1, NULL);
}
/*.......................................................................
* This is the action function that recalls the next line in the
* history buffer who's prefix matches that specified in the earlier call
* to gl_history_search_backward) which started the history search.
* By setting count=-1, this can be used internally to force searching
* for the prefix used in the last search.
*/
static KT_KEY_FN(gl_history_search_forward)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* If a prefix search isn't already in progress, replace the search
* prefix to the string that precedes the cursor. In vi command mode
* include the character that is under the cursor in the string. If
* count<0 keep the previous search prefix regardless, so as to force
* a repeat search even if the last command wasn't a history command.
*/
if(count >= 0 && !_glh_search_active(gl->glh) &&
_glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
(gl->editor==GL_VI_MODE && gl->ntotal>0))) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
/*
* Search forwards for the next matching line.
*/
if(_glh_find_forwards(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange for the cursor to be placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This is the action function that recalls the next line in the
* history buffer who's prefix matches that specified in an earlier call
* to gl_history_search_backward() or gl_history_search_forward().
*/
static KT_KEY_FN(gl_history_re_search_forward)
{
return gl_history_search_forward(gl, -1, NULL);
}
#ifdef HIDE_FILE_SYSTEM
/*.......................................................................
* The following function is used as the default completion handler when
* the filesystem is to be hidden. It simply reports no completions.
*/
static CPL_MATCH_FN(gl_no_completions)
{
return 0;
}
#endif
/*.......................................................................
* This is the tab completion function that completes the filename that
* precedes the cursor position. Its callback data argument must be a
* pointer to a GlCplCallback containing the completion callback function
* and its callback data, or NULL to use the builtin filename completer.
*/
static KT_KEY_FN(gl_complete_word)
{
CplMatches *matches; /* The possible completions */
int suffix_len; /* The length of the completion extension */
int cont_len; /* The length of any continuation suffix */
int nextra; /* The number of characters being added to the */
/* total length of the line. */
int buff_pos; /* The buffer index at which the completion is */
/* to be inserted. */
int waserr = 0; /* True after errors */
/*
* Get the container of the completion callback and its callback data.
*/
GlCplCallback *cb = data ? (GlCplCallback *) data : &gl->cplfn;
/*
* In vi command mode, switch to append mode so that the character under
* the cursor is included in the completion (otherwise people can't
* complete at the end of the line).
*/
if(gl->vi.command && gl_vi_append(gl, 0, NULL))
return 1;
/*
* Get the cursor position at which the completion is to be inserted.
*/
buff_pos = gl->buff_curpos;
/*
* Perform the completion.
*/
matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos, cb->data,
cb->fn);
/*
* No matching completions?
*/
if(!matches) {
waserr = gl_print_info(gl, cpl_last_error(gl->cpl), GL_END_INFO);
/*
* Are there any completions?
*/
} else if(matches->nmatch >= 1) {
/*
* If there any ambiguous matches, report them, starting on a new line.
*/
if(matches->nmatch > 1 && gl->echo) {
if(_gl_normal_io(gl) ||
_cpl_output_completions(matches, gl_write_fn, gl, gl->ncolumn))
waserr = 1;
};
/*
* Get the length of the suffix and any continuation suffix to add to it.
*/
suffix_len = strlen(matches->suffix);
cont_len = strlen(matches->cont_suffix);
/*
* If there is an unambiguous match, and the continuation suffix ends in
* a newline, strip that newline and arrange to have getline return
* after this action function returns.
*/
if(matches->nmatch==1 && cont_len > 0 &&
matches->cont_suffix[cont_len - 1] == '\n') {
cont_len--;
if(gl_newline(gl, 1, NULL))
waserr = 1;
};
/*
* Work out the number of characters that are to be added.
*/
nextra = suffix_len + cont_len;
/*
* Is there anything to be added?
*/
if(!waserr && nextra) {
/*
* Will there be space for the expansion in the line buffer?
*/
if(gl->ntotal + nextra < gl->linelen) {
/*
* Make room to insert the filename extension.
*/
gl_make_gap_in_buffer(gl, gl->buff_curpos, nextra);
/*
* Insert the filename extension.
*/
gl_buffer_string(gl, matches->suffix, suffix_len, gl->buff_curpos);
/*
* Add the terminating characters.
*/
gl_buffer_string(gl, matches->cont_suffix, cont_len,
gl->buff_curpos + suffix_len);
/*
* Place the cursor position at the end of the completion.
*/
gl->buff_curpos += nextra;
/*
* If we don't have to redisplay the whole line, redisplay the part
* of the line which follows the original cursor position, and place
* the cursor at the end of the completion.
*/
if(gl->displayed) {
if(gl_truncate_display(gl) ||
gl_print_string(gl, gl->line + buff_pos, '\0') ||
gl_place_cursor(gl, gl->buff_curpos))
waserr = 1;
};
} else {
(void) gl_print_info(gl,
"Insufficient room in line for file completion.",
GL_END_INFO);
waserr = 1;
};
};
};
/*
* If any output had to be written to the terminal, then editing will
* have been suspended, make sure that we are back in raw line editing
* mode before returning.
*/
if(_gl_raw_io(gl, 1))
waserr = 1;
return 0;
}
#ifndef HIDE_FILE_SYSTEM
/*.......................................................................
* This is the function that expands the filename that precedes the
* cursor position. It expands ~user/ expressions, $envvar expressions,
* and wildcards.
*/
static KT_KEY_FN(gl_expand_filename)
{
char *start_path; /* The pointer to the start of the pathname in */
/* gl->line[]. */
FileExpansion *result; /* The results of the filename expansion */
int pathlen; /* The length of the pathname being expanded */
int length; /* The number of characters needed to display the */
/* expanded files. */
int nextra; /* The number of characters to be added */
int i,j;
/*
* In vi command mode, switch to append mode so that the character under
* the cursor is included in the completion (otherwise people can't
* complete at the end of the line).
*/
if(gl->vi.command && gl_vi_append(gl, 0, NULL))
return 1;
/*
* Locate the start of the filename that precedes the cursor position.
*/
start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
if(!start_path)
return 1;
/*
* Get the length of the string that is to be expanded.
*/
pathlen = gl->buff_curpos - (start_path - gl->line);
/*
* Attempt to expand it.
*/
result = ef_expand_file(gl->ef, start_path, pathlen);
/*
* If there was an error, report the error on a new line.
*/
if(!result)
return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
/*
* If no files matched, report this as well.
*/
if(result->nfile == 0 || !result->exists)
return gl_print_info(gl, "No files match.", GL_END_INFO);
/*
* If in vi command mode, preserve the current line for potential use by
* vi-undo.
*/
gl_save_for_undo(gl);
/*
* Work out how much space we will need to display all of the matching
* filenames, taking account of the space that we need to place between
* them, and the number of additional '\' characters needed to escape
* spaces, tabs and backslash characters in the individual filenames.
*/
length = 0;
for(i=0; i<result->nfile; i++) {
char *file = result->files[i];
while(*file) {
int c = *file++;
switch(c) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
length++; /* Count extra backslash characters */
};
length++; /* Count the character itself */
};
length++; /* Count the space that follows each filename */
};
/*
* Work out the number of characters that are to be added.
*/
nextra = length - pathlen;
/*
* Will there be space for the expansion in the line buffer?
*/
if(gl->ntotal + nextra >= gl->linelen) {
return gl_print_info(gl, "Insufficient room in line for file expansion.",
GL_END_INFO);
} else {
/*
* Do we need to move the part of the line that followed the unexpanded
* filename?
*/
if(nextra > 0) {
gl_make_gap_in_buffer(gl, gl->buff_curpos, nextra);
} else if(nextra < 0) {
gl->buff_curpos += nextra;
gl_remove_from_buffer(gl, gl->buff_curpos, -nextra);
};
/*
* Insert the filenames, separated by spaces, and with internal spaces,
* tabs and backslashes escaped with backslashes.
*/
for(i=0,j=start_path - gl->line; i<result->nfile; i++) {
char *file = result->files[i];
while(*file) {
int c = *file++;
switch(c) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
gl_buffer_char(gl, '\\', j++);
};
gl_buffer_char(gl, c, j++);
};
gl_buffer_char(gl, ' ', j++);
};
};
/*
* Redisplay the part of the line which follows the start of
* the original filename.
*/
if(gl_place_cursor(gl, start_path - gl->line) ||
gl_truncate_display(gl) ||
gl_print_string(gl, start_path, start_path[length]))
return 1;
/*
* Move the cursor to the end of the expansion.
*/
return gl_place_cursor(gl, (start_path - gl->line) + length);
}
#endif
#ifndef HIDE_FILE_SYSTEM
/*.......................................................................
* This is the action function that lists glob expansions of the
* filename that precedes the cursor position. It expands ~user/
* expressions, $envvar expressions, and wildcards.
*/
static KT_KEY_FN(gl_list_glob)
{
char *start_path; /* The pointer to the start of the pathname in */
/* gl->line[]. */
FileExpansion *result; /* The results of the filename expansion */
int pathlen; /* The length of the pathname being expanded */
/*
* Locate the start of the filename that precedes the cursor position.
*/
start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
if(!start_path)
return 1;
/*
* Get the length of the string that is to be expanded.
*/
pathlen = gl->buff_curpos - (start_path - gl->line);
/*
* Attempt to expand it.
*/
result = ef_expand_file(gl->ef, start_path, pathlen);
/*
* If there was an error, report it.
*/
if(!result) {
return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
/*
* If no files matched, report this as well.
*/
} else if(result->nfile == 0 || !result->exists) {
return gl_print_info(gl, "No files match.", GL_END_INFO);
/*
* List the matching expansions.
*/
} else if(gl->echo) {
if(gl_start_newline(gl, 1) ||
_ef_output_expansions(result, gl_write_fn, gl, gl->ncolumn))
return 1;
gl_queue_redisplay(gl);
};
return 0;
}
#endif
/*.......................................................................
* Return non-zero if a character should be considered a part of a word.
*
* Input:
* c int The character to be tested.
* Output:
* return int True if the character should be considered part of a word.
*/
static int gl_is_word_char(int c)
{
return isalnum((int)(unsigned char)c) || strchr(GL_WORD_CHARS, c) != NULL;
}
/*.......................................................................
* Override the builtin file-completion callback that is bound to the
* "complete_word" action function.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * This is passed to match_fn() whenever it is
* called. It could, for example, point to a
* symbol table where match_fn() could look
* for possible completions.
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* report matching symbols.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_customize_completion(GetLine *gl, void *data, CplMatchFn *match_fn)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
/*
* Check the arguments.
*/
if(!gl || !match_fn) {
if(gl)
_err_record_msg(gl->err, "NULL argument", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Record the new completion function and its callback data.
*/
gl->cplfn.fn = match_fn;
gl->cplfn.data = data;
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return 0;
}
/*.......................................................................
* Change the terminal (or stream) that getline interacts with.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* input_fp FILE * The stdio stream to read from.
* output_fp FILE * The stdio stream to write to.
* term char * The terminal type. This can be NULL if
* either or both of input_fp and output_fp don't
* refer to a terminal. Otherwise it should refer
* to an entry in the terminal information database.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
const char *term)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_change_terminal() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_change_terminal(gl, input_fp, output_fp, term);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_change_terminal() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
const char *term)
{
int is_term = 0; /* True if both input_fd and output_fd are associated */
/* with a terminal. */
/*
* Require that input_fp and output_fp both be valid.
*/
if(!input_fp || !output_fp) {
gl_print_info(gl, "Can't change terminal. Bad input/output stream(s).",
GL_END_INFO);
return 1;
};
/*
* Are we displacing an existing terminal (as opposed to setting the
* initial terminal)?
*/
if(gl->input_fd >= 0) {
/*
* Make sure to leave the previous terminal in a usable state.
*/
if(_gl_normal_io(gl))
return 1;
/*
* Remove the displaced terminal from the list of fds to watch.
*/
#ifdef HAVE_SELECT
FD_CLR(gl->input_fd, &gl->rfds);
#endif
};
/*
* Record the file descriptors and streams.
*/
gl->input_fp = input_fp;
gl->input_fd = fileno(input_fp);
gl->output_fp = output_fp;
gl->output_fd = fileno(output_fp);
/*
* If needed, expand the record of the maximum file-descriptor that might
* need to be monitored with select().
*/
#ifdef HAVE_SELECT
if(gl->input_fd > gl->max_fd)
gl->max_fd = gl->input_fd;
#endif
/*
* Disable terminal interaction until we have enough info to interact
* with the terminal.
*/
gl->is_term = 0;
/*
* For terminal editing, we need both output_fd and input_fd to refer to
* a terminal. While we can't verify that they both point to the same
* terminal, we can verify that they point to terminals.
*/
is_term = isatty(gl->input_fd) && isatty(gl->output_fd);
/*
* If we are interacting with a terminal and no terminal type has been
* specified, treat it as a generic ANSI terminal.
*/
if(is_term && !term)
term = "ansi";
/*
* Make a copy of the terminal type string.
*/
if(term != gl->term) {
/*
* Delete any old terminal type string.
*/
if(gl->term) {
free(gl->term);
gl->term = NULL;
};
/*
* Make a copy of the new terminal-type string, if any.
*/
if(term) {
size_t termsz = strlen(term)+1;
gl->term = (char *) malloc(termsz);
if(gl->term)
strlcpy(gl->term, term, termsz);
};
};
/*
* Clear any terminal-specific key bindings that were taken from the
* settings of the last terminal.
*/
_kt_clear_bindings(gl->bindings, KTB_TERM);
/*
* If we have a terminal install new bindings for it.
*/
if(is_term) {
/*
* Get the current settings of the terminal.
*/
if(tcgetattr(gl->input_fd, &gl->oldattr)) {
_err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
return 1;
};
/*
* If we don't set this now, gl_control_strings() won't know
* that it is talking to a terminal.
*/
gl->is_term = 1;
/*
* Lookup the terminal control string and size information.
*/
if(gl_control_strings(gl, term)) {
gl->is_term = 0;
return 1;
};
/*
* Bind terminal-specific keys.
*/
if(gl_bind_terminal_keys(gl))
return 1;
};
/*
* Assume that the caller has given us a terminal in a sane state.
*/
gl->io_mode = GL_NORMAL_MODE;
/*
* Switch into the currently configured I/O mode.
*/
if(_gl_io_mode(gl, gl->io_mode))
return 1;
return 0;
}
/*.......................................................................
* Set up terminal-specific key bindings.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_bind_terminal_keys(GetLine *gl)
{
/*
* Install key-bindings for the special terminal characters.
*/
if(gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VINTR],
"user-interrupt") ||
gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VQUIT], "abort") ||
gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VSUSP], "suspend"))
return 1;
/*
* In vi-mode, arrange for the above characters to be seen in command
* mode.
*/
if(gl->editor == GL_VI_MODE) {
if(gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VINTR]),
"user-interrupt") ||
gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VQUIT]),
"abort") ||
gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VSUSP]),
"suspend"))
return 1;
};
/*
* Non-universal special keys.
*/
#ifdef VLNEXT
if(gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VLNEXT],
"literal-next"))
return 1;
#else
if(_kt_set_keybinding(gl->bindings, KTB_TERM, "^V", "literal-next")) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
#endif
/*
* Bind action functions to the terminal-specific arrow keys
* looked up by gl_control_strings().
*/
if(_gl_bind_arrow_keys(gl))
return 1;
return 0;
}
/*.......................................................................
* This function is normally bound to control-D. When it is invoked within
* a line it deletes the character which follows the cursor. When invoked
* at the end of the line it lists possible file completions, and when
* invoked on an empty line it causes gl_get_line() to return EOF. This
* function emulates the one that is normally bound to control-D by tcsh.
*/
static KT_KEY_FN(gl_del_char_or_list_or_eof)
{
/*
* If we have an empty line arrange to return EOF.
*/
if(gl->ntotal < 1) {
gl_record_status(gl, GLR_EOF, 0);
return 1;
/*
* If we are at the end of the line list possible completions.
*/
} else if(gl->buff_curpos >= gl->ntotal) {
return gl_list_completions(gl, 1, NULL);
/*
* Within the line delete the character that follows the cursor.
*/
} else {
/*
* If in vi command mode, first preserve the current line for potential use
* by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Delete 'count' characters.
*/
return gl_forward_delete_char(gl, count, NULL);
};
}
/*.......................................................................
* This function is normally bound to control-D in vi mode. When it is
* invoked within a line it lists possible file completions, and when
* invoked on an empty line it causes gl_get_line() to return EOF. This
* function emulates the one that is normally bound to control-D by tcsh.
*/
static KT_KEY_FN(gl_list_or_eof)
{
/*
* If we have an empty line arrange to return EOF.
*/
if(gl->ntotal < 1) {
gl_record_status(gl, GLR_EOF, 0);
return 1;
/*
* Otherwise list possible completions.
*/
} else {
return gl_list_completions(gl, 1, NULL);
};
}
/*.......................................................................
* List possible completions of the word that precedes the cursor. The
* callback data argument must either be NULL to select the default
* file completion callback, or be a GlCplCallback object containing the
* completion callback function to call.
*/
static KT_KEY_FN(gl_list_completions)
{
int waserr = 0; /* True after errors */
/*
* Get the container of the completion callback and its callback data.
*/
GlCplCallback *cb = data ? (GlCplCallback *) data : &gl->cplfn;
/*
* Get the list of possible completions.
*/
CplMatches *matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos,
cb->data, cb->fn);
/*
* No matching completions?
*/
if(!matches) {
waserr = gl_print_info(gl, cpl_last_error(gl->cpl), GL_END_INFO);
/*
* List the matches.
*/
} else if(matches->nmatch > 0 && gl->echo) {
if(_gl_normal_io(gl) ||
_cpl_output_completions(matches, gl_write_fn, gl, gl->ncolumn))
waserr = 1;
};
/*
* If any output had to be written to the terminal, then editing will
* have been suspended, make sure that we are back in raw line editing
* mode before returning.
*/
if(_gl_raw_io(gl, 1))
waserr = 1;
return waserr;
}
/*.......................................................................
* Where the user has used the symbolic arrow-key names to specify
* arrow key bindings, bind the specified action functions to the default
* and terminal specific arrow key sequences.
*
* Input:
* gl GetLine * The getline resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _gl_bind_arrow_keys(GetLine *gl)
{
/*
* Process each of the arrow keys.
*/
if(_gl_rebind_arrow_key(gl, "up", gl->u_arrow, "^[[A", "^[OA") ||
_gl_rebind_arrow_key(gl, "down", gl->d_arrow, "^[[B", "^[OB") ||
_gl_rebind_arrow_key(gl, "left", gl->l_arrow, "^[[D", "^[OD") ||
_gl_rebind_arrow_key(gl, "right", gl->r_arrow, "^[[C", "^[OC"))
return 1;
return 0;
}
/*.......................................................................
* Lookup the action function of a symbolic arrow-key binding, and bind
* it to the terminal-specific and default arrow-key sequences. Note that
* we don't trust the terminal-specified key sequences to be correct.
* The main reason for this is that on some machines the xterm terminfo
* entry is for hardware X-terminals, rather than xterm terminal emulators
* and the two terminal types emit different character sequences when the
* their cursor keys are pressed. As a result we also supply a couple
* of default key sequences.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* name char * The symbolic name of the arrow key.
* term_seq char * The terminal-specific arrow-key sequence.
* def_seq1 char * The first default arrow-key sequence.
* def_seq2 char * The second arrow-key sequence.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _gl_rebind_arrow_key(GetLine *gl, const char *name,
const char *term_seq, const char *def_seq1,
const char *def_seq2)
{
KeySym *keysym; /* The binding-table entry matching the arrow-key name */
int nsym; /* The number of ambiguous matches */
/*
* Lookup the key binding for the symbolic name of the arrow key. This
* will either be the default action, or a user provided one.
*/
if(_kt_lookup_keybinding(gl->bindings, name, strlen(name), &keysym, &nsym)
== KT_EXACT_MATCH) {
/*
* Get the action function.
*/
KtAction *action = keysym->actions + keysym->binder;
KtKeyFn *fn = action->fn;
void *data = action->data;
/*
* Bind this to each of the specified key sequences.
*/
if((term_seq &&
_kt_set_keyfn(gl->bindings, KTB_TERM, term_seq, fn, data)) ||
(def_seq1 &&
_kt_set_keyfn(gl->bindings, KTB_NORM, def_seq1, fn, data)) ||
(def_seq2 &&
_kt_set_keyfn(gl->bindings, KTB_NORM, def_seq2, fn, data))) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
};
return 0;
}
/*.......................................................................
* Read getline configuration information from a given file.
*
* Input:
* gl GetLine * The getline resource object.
* filename const char * The name of the file to read configuration
* information from. The contents of this file
* are as described in the gl_get_line(3) man
* page for the default ~/.teclarc configuration
* file.
* who KtBinder Who bindings are to be installed for.
* Output:
* return int 0 - OK.
* 1 - Irrecoverable error.
*/
static int _gl_read_config_file(GetLine *gl, const char *filename, KtBinder who)
{
/*
* If filesystem access is to be excluded, configuration files can't
* be read.
*/
#ifdef WITHOUT_FILE_SYSTEM
_err_record_msg(gl->err,
"Can't read configuration files without filesystem access",
END_ERR_MSG);
errno = EINVAL;
return 1;
#else
FileExpansion *expansion; /* The expansion of the filename */
FILE *fp; /* The opened file */
int waserr = 0; /* True if an error occurred while reading */
int lineno = 1; /* The line number being processed */
/*
* Check the arguments.
*/
if(!gl || !filename) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Expand the filename.
*/
expansion = ef_expand_file(gl->ef, filename, -1);
if(!expansion) {
gl_print_info(gl, "Unable to expand ", filename, " (",
ef_last_error(gl->ef), ").", GL_END_INFO);
return 1;
};
/*
* Attempt to open the file.
*/
fp = fopen(expansion->files[0], "r");
/*
* It isn't an error for there to be no configuration file.
*/
if(!fp)
return 0;
/*
* Parse the contents of the file.
*/
while(!waserr && !feof(fp))
waserr = _gl_parse_config_line(gl, fp, glc_file_getc, filename, who,
&lineno);
/*
* Bind action functions to the terminal-specific arrow keys.
*/
if(_gl_bind_arrow_keys(gl))
return 1;
/*
* Clean up.
*/
(void) fclose(fp);
return waserr;
#endif
}
/*.......................................................................
* Read GetLine configuration information from a string. The contents of
* the string are the same as those described in the gl_get_line(3)
* man page for the contents of the ~/.teclarc configuration file.
*/
static int _gl_read_config_string(GetLine *gl, const char *buffer, KtBinder who)
{
const char *bptr; /* A pointer into buffer[] */
int waserr = 0; /* True if an error occurred while reading */
int lineno = 1; /* The line number being processed */
/*
* Check the arguments.
*/
if(!gl || !buffer) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Get a pointer to the start of the buffer.
*/
bptr = buffer;
/*
* Parse the contents of the buffer.
*/
while(!waserr && *bptr)
waserr = _gl_parse_config_line(gl, &bptr, glc_buff_getc, "", who, &lineno);
/*
* Bind action functions to the terminal-specific arrow keys.
*/
if(_gl_bind_arrow_keys(gl))
return 1;
return waserr;
}
/*.......................................................................
* Parse the next line of a getline configuration file.
*
* Input:
* gl GetLine * The getline resource object.
* stream void * The pointer representing the stream to be read
* by getc_fn().
* getc_fn GlcGetcFn * A callback function which when called with
* 'stream' as its argument, returns the next
* unread character from the stream.
* origin const char * The name of the entity being read (eg. a
* file name).
* who KtBinder Who bindings are to be installed for.
* Input/Output:
* lineno int * The line number being processed is to be
* maintained in *lineno.
* Output:
* return int 0 - OK.
* 1 - Irrecoverable error.
*/
static int _gl_parse_config_line(GetLine *gl, void *stream, GlcGetcFn *getc_fn,
const char *origin, KtBinder who, int *lineno)
{
char buffer[GL_CONF_BUFLEN+1]; /* The input line buffer */
char *argv[GL_CONF_MAXARG]; /* The argument list */
int argc = 0; /* The number of arguments in argv[] */
int c; /* A character from the file */
int escaped = 0; /* True if the next character is escaped */
int i;
/*
* Skip spaces and tabs.
*/
do c = getc_fn(stream); while(c==' ' || c=='\t');
/*
* Comments extend to the end of the line.
*/
if(c=='#')
do c = getc_fn(stream); while(c != '\n' && c != EOF);
/*
* Ignore empty lines.
*/
if(c=='\n' || c==EOF) {
(*lineno)++;
return 0;
};
/*
* Record the buffer location of the start of the first argument.
*/
argv[argc] = buffer;
/*
* Read the rest of the line, stopping early if a comment is seen, or
* the buffer overflows, and replacing sequences of spaces with a
* '\0', and recording the thus terminated string as an argument.
*/
i = 0;
while(i<GL_CONF_BUFLEN) {
/*
* Did we hit the end of the latest argument?
*/
if(c==EOF || (!escaped && (c==' ' || c=='\n' || c=='\t' || c=='#'))) {
/*
* Terminate the argument.
*/
buffer[i++] = '\0';
argc++;
/*
* Skip spaces and tabs.
*/
while(c==' ' || c=='\t')
c = getc_fn(stream);
/*
* If we hit the end of the line, or the start of a comment, exit the loop.
*/
if(c==EOF || c=='\n' || c=='#')
break;
/*
* Start recording the next argument.
*/
if(argc >= GL_CONF_MAXARG) {
gl_report_config_error(gl, origin, *lineno, "Too many arguments.");
do c = getc_fn(stream); while(c!='\n' && c!=EOF); /* Skip past eol */
return 0;
};
argv[argc] = buffer + i;
/*
* The next character was preceded by spaces, so it isn't escaped.
*/
escaped = 0;
} else {
/*
* If we hit an unescaped backslash, this means that we should arrange
* to treat the next character like a simple alphabetical character.
*/
if(c=='\\' && !escaped) {
escaped = 1;
/*
* Splice lines where the newline is escaped.
*/
} else if(c=='\n' && escaped) {
(*lineno)++;
/*
* Record a normal character, preserving any preceding backslash.
*/
} else {
if(escaped)
buffer[i++] = '\\';
if(i>=GL_CONF_BUFLEN)
break;
escaped = 0;
buffer[i++] = c;
};
/*
* Get the next character.
*/
c = getc_fn(stream);
};
};
/*
* Did the buffer overflow?
*/
if(i>=GL_CONF_BUFLEN) {
gl_report_config_error(gl, origin, *lineno, "Line too long.");
return 0;
};
/*
* The first argument should be a command name.
*/
if(strcmp(argv[0], "bind") == 0) {
const char *action = NULL; /* A NULL action removes a keybinding */
const char *keyseq = NULL;
switch(argc) {
case 3:
action = argv[2];
/* FALLTHROUGH */
case 2: /* Note the intentional fallthrough */
keyseq = argv[1];
/*
* Attempt to record the new keybinding.
*/
if(_kt_set_keybinding(gl->bindings, who, keyseq, action)) {
gl_report_config_error(gl, origin, *lineno,
_kt_last_error(gl->bindings));
};
break;
default:
gl_report_config_error(gl, origin, *lineno, "Wrong number of arguments.");
};
} else if(strcmp(argv[0], "edit-mode") == 0) {
if(argc == 2 && strcmp(argv[1], "emacs") == 0) {
gl_change_editor(gl, GL_EMACS_MODE);
} else if(argc == 2 && strcmp(argv[1], "vi") == 0) {
gl_change_editor(gl, GL_VI_MODE);
} else if(argc == 2 && strcmp(argv[1], "none") == 0) {
gl_change_editor(gl, GL_NO_EDITOR);
} else {
gl_report_config_error(gl, origin, *lineno,
"The argument of editor should be vi or emacs.");
};
} else if(strcmp(argv[0], "nobeep") == 0) {
gl->silence_bell = 1;
} else {
gl_report_config_error(gl, origin, *lineno, "Unknown command name.");
};
/*
* Skip any trailing comment.
*/
while(c != '\n' && c != EOF)
c = getc_fn(stream);
(*lineno)++;
return 0;
}
/*.......................................................................
* This is a private function of _gl_parse_config_line() which prints
* out an error message about the contents of the line, prefixed by the
* name of the origin of the line and its line number.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* origin const char * The name of the entity being read (eg. a
* file name).
* lineno int The line number at which the error occurred.
* errmsg const char * The error message.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_report_config_error(GetLine *gl, const char *origin, int lineno,
const char *errmsg)
{
char lnum[20]; /* A buffer in which to render a single integer */
/*
* Convert the line number into a string.
*/
snprintf(lnum, sizeof(lnum), "%d", lineno);
/*
* Have the string printed on the terminal.
*/
return gl_print_info(gl, origin, ":", lnum, ": ", errmsg, GL_END_INFO);
}
/*.......................................................................
* This is the _gl_parse_config_line() callback function which reads the
* next character from a configuration file.
*/
static GLC_GETC_FN(glc_file_getc)
{
return fgetc((FILE *) stream);
}
/*.......................................................................
* This is the _gl_parse_config_line() callback function which reads the
* next character from a buffer. Its stream argument is a pointer to a
* variable which is, in turn, a pointer into the buffer being read from.
*/
static GLC_GETC_FN(glc_buff_getc)
{
const char **lptr = (char const **) stream;
return **lptr ? *(*lptr)++ : EOF;
}
#ifndef HIDE_FILE_SYSTEM
/*.......................................................................
* When this action is triggered, it arranges to temporarily read command
* lines from the regular file whos name precedes the cursor.
* The current line is first discarded.
*/
static KT_KEY_FN(gl_read_from_file)
{
char *start_path; /* The pointer to the start of the pathname in */
/* gl->line[]. */
FileExpansion *result; /* The results of the filename expansion */
int pathlen; /* The length of the pathname being expanded */
/*
* Locate the start of the filename that precedes the cursor position.
*/
start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
if(!start_path)
return 1;
/*
* Get the length of the pathname string.
*/
pathlen = gl->buff_curpos - (start_path - gl->line);
/*
* Attempt to expand the pathname.
*/
result = ef_expand_file(gl->ef, start_path, pathlen);
/*
* If there was an error, report the error on a new line.
*/
if(!result) {
return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
/*
* If no files matched, report this as well.
*/
} else if(result->nfile == 0 || !result->exists) {
return gl_print_info(gl, "No files match.", GL_END_INFO);
/*
* Complain if more than one file matches.
*/
} else if(result->nfile > 1) {
return gl_print_info(gl, "More than one file matches.", GL_END_INFO);
/*
* Disallow input from anything but normal files. In principle we could
* also support input from named pipes. Terminal files would be a problem
* since we wouldn't know the terminal type, and other types of files
* might cause the library to lock up.
*/
} else if(!_pu_path_is_file(result->files[0])) {
return gl_print_info(gl, "Not a normal file.", GL_END_INFO);
} else {
/*
* Attempt to open and install the specified file for reading.
*/
gl->file_fp = fopen(result->files[0], "r");
if(!gl->file_fp) {
return gl_print_info(gl, "Unable to open: ", result->files[0],
GL_END_INFO);
};
/*
* If needed, expand the record of the maximum file-descriptor that might
* need to be monitored with select().
*/
#ifdef HAVE_SELECT
if(fileno(gl->file_fp) > gl->max_fd)
gl->max_fd = fileno(gl->file_fp);
#endif
/*
* Is non-blocking I/O needed?
*/
if(gl->raw_mode && gl->io_mode==GL_SERVER_MODE &&
gl_nonblocking_io(gl, fileno(gl->file_fp))) {
gl_revert_input(gl);
return gl_print_info(gl, "Can't read file %s with non-blocking I/O",
result->files[0]);
};
/*
* Inform the user what is happening.
*/
if(gl_print_info(gl, "<Taking input from ", result->files[0], ">",
GL_END_INFO))
return 1;
};
return 0;
}
#endif
/*.......................................................................
* Close any temporary file that is being used for input.
*
* Input:
* gl GetLine * The getline resource object.
*/
static void gl_revert_input(GetLine *gl)
{
if(gl->file_fp)
fclose(gl->file_fp);
gl->file_fp = NULL;
gl->endline = 1;
}
/*.......................................................................
* This is the action function that recalls the oldest line in the
* history buffer.
*/
static KT_KEY_FN(gl_beginning_of_history)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Forget any previous recall session.
*/
gl->preload_id = 0;
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* Recall the next oldest line in the history list.
*/
if(_glh_oldest_line(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange to have the cursor placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* If a history session is currently in progress, this action function
* recalls the line that was being edited when the session started. If
* no history session is in progress, it does nothing.
*/
static KT_KEY_FN(gl_end_of_history)
{
/*
* In vi mode, switch to command mode, since the user is very
* likely to want to move around newly recalled lines.
*/
gl_vi_command_mode(gl);
/*
* Forget any previous recall session.
*/
gl->preload_id = 0;
/*
* Record the key sequence number of this search action.
*/
gl->last_search = gl->keyseq_count;
/*
* Recall the next oldest line in the history list.
*/
if(_glh_current_line(gl->glh, gl->line, gl->linelen+1) == NULL)
return 0;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Arrange to have the cursor placed at the end of the new line.
*/
gl->buff_curpos = gl->ntotal;
/*
* Erase and display the new line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* This action function is treated specially, in that its count argument
* is set to the end keystroke of the keysequence that activated it.
* It accumulates a numeric argument, adding one digit on each call in
* which the last keystroke was a numeric digit.
*/
static KT_KEY_FN(gl_digit_argument)
{
/*
* Was the last keystroke a digit?
*/
int is_digit = isdigit((int)(unsigned char) count);
/*
* In vi command mode, a lone '0' means goto-start-of-line.
*/
if(gl->vi.command && gl->number < 0 && count == '0')
return gl_beginning_of_line(gl, count, NULL);
/*
* Are we starting to accumulate a new number?
*/
if(gl->number < 0 || !is_digit)
gl->number = 0;
/*
* Was the last keystroke a digit?
*/
if(is_digit) {
/*
* Read the numeric value of the digit, without assuming ASCII.
*/
int n;
char s[2]; s[0] = count; s[1] = '\0';
n = atoi(s);
/*
* Append the new digit.
*/
gl->number = gl->number * 10 + n;
};
return 0;
}
/*.......................................................................
* The newline action function sets gl->endline to tell
* gl_get_input_line() that the line is now complete.
*/
static KT_KEY_FN(gl_newline)
{
GlhLineID id; /* The last history line recalled while entering this line */
/*
* Flag the line as ended.
*/
gl->endline = 1;
/*
* Record the next position in the history buffer, for potential
* recall by an action function on the next call to gl_get_line().
*/
id = _glh_line_id(gl->glh, 1);
if(id)
gl->preload_id = id;
return 0;
}
/*.......................................................................
* The 'repeat' action function sets gl->endline to tell
* gl_get_input_line() that the line is now complete, and records the
* ID of the next history line in gl->preload_id so that the next call
* to gl_get_input_line() will preload the line with that history line.
*/
static KT_KEY_FN(gl_repeat_history)
{
gl->endline = 1;
gl->preload_id = _glh_line_id(gl->glh, 1);
gl->preload_history = 1;
return 0;
}
/*.......................................................................
* Flush unwritten characters to the terminal.
*
* Input:
* gl GetLine * The getline resource object.
* Output:
* return int 0 - OK.
* 1 - Either an error occured, or the output
* blocked and non-blocking I/O is being used.
* See gl->rtn_status for details.
*/
static int gl_flush_output(GetLine *gl)
{
/*
* Record the fact that we are about to write to the terminal.
*/
gl->pending_io = GLP_WRITE;
/*
* Attempt to flush the output to the terminal.
*/
errno = 0;
switch(_glq_flush_queue(gl->cq, gl->flush_fn, gl)) {
case GLQ_FLUSH_DONE:
return gl->redisplay && !gl->postpone && gl_redisplay(gl, 1, NULL);
break;
case GLQ_FLUSH_AGAIN: /* Output blocked */
gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
return 1;
break;
default: /* Abort the line if an error occurs */
gl_record_status(gl, errno==EINTR ? GLR_SIGNAL : GLR_ERROR, errno);
return 1;
break;
};
}
/*.......................................................................
* This is the callback which _glq_flush_queue() uses to write buffered
* characters to the terminal.
*/
static GL_WRITE_FN(gl_flush_terminal)
{
int ndone = 0; /* The number of characters written so far */
/*
* Get the line-editor resource object.
*/
GetLine *gl = (GetLine *) data;
/*
* Transfer the latest array of characters to stdio.
*/
while(ndone < n) {
int nnew = write(gl->output_fd, s, n-ndone);
/*
* If the write was successful, add to the recorded number of bytes
* that have now been written.
*/
if(nnew > 0) {
ndone += nnew;
/*
* If a signal interrupted the call, restart the write(), since all of
* the signals that gl_get_line() has been told to watch for are
* currently blocked.
*/
} else if(errno == EINTR) {
continue;
/*
* If we managed to write something before an I/O error occurred, or
* output blocked before anything was written, report the number of
* bytes that were successfully written before this happened.
*/
} else if(ndone > 0
#if defined(EAGAIN)
|| errno==EAGAIN
#endif
#if defined(EWOULDBLOCK)
|| errno==EWOULDBLOCK
#endif
) {
return ndone;
/*
* To get here, an error must have occurred before anything new could
* be written.
*/
} else {
return -1;
};
};
/*
* To get here, we must have successfully written the number of
* bytes that was specified.
*/
return n;
}
/*.......................................................................
* Change the style of editing to emulate a given editor.
*
* Input:
* gl GetLine * The getline resource object.
* editor GlEditor The type of editor to emulate.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_change_editor(GetLine *gl, GlEditor editor)
{
/*
* Install the default key-bindings of the requested editor.
*/
switch(editor) {
case GL_EMACS_MODE:
_kt_clear_bindings(gl->bindings, KTB_NORM);
_kt_clear_bindings(gl->bindings, KTB_TERM);
(void) _kt_add_bindings(gl->bindings, KTB_NORM, gl_emacs_bindings,
sizeof(gl_emacs_bindings)/sizeof(gl_emacs_bindings[0]));
break;
case GL_VI_MODE:
_kt_clear_bindings(gl->bindings, KTB_NORM);
_kt_clear_bindings(gl->bindings, KTB_TERM);
(void) _kt_add_bindings(gl->bindings, KTB_NORM, gl_vi_bindings,
sizeof(gl_vi_bindings)/sizeof(gl_vi_bindings[0]));
break;
case GL_NO_EDITOR:
break;
default:
_err_record_msg(gl->err, "Unknown editor", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Record the new editing mode.
*/
gl->editor = editor;
gl->vi.command = 0; /* Start in input mode */
gl->insert_curpos = 0;
/*
* Reinstate terminal-specific bindings.
*/
if(gl->editor != GL_NO_EDITOR && gl->input_fp)
(void) gl_bind_terminal_keys(gl);
return 0;
}
/*.......................................................................
* This is an action function that switches to editing using emacs bindings
*/
static KT_KEY_FN(gl_emacs_editing_mode)
{
return gl_change_editor(gl, GL_EMACS_MODE);
}
/*.......................................................................
* This is an action function that switches to editing using vi bindings
*/
static KT_KEY_FN(gl_vi_editing_mode)
{
return gl_change_editor(gl, GL_VI_MODE);
}
/*.......................................................................
* This is the action function that switches to insert mode.
*/
static KT_KEY_FN(gl_vi_insert)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Switch to vi insert mode.
*/
gl->insert = 1;
gl->vi.command = 0;
gl->insert_curpos = gl->buff_curpos;
return 0;
}
/*.......................................................................
* This is an action function that switches to overwrite mode.
*/
static KT_KEY_FN(gl_vi_overwrite)
{
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Switch to vi overwrite mode.
*/
gl->insert = 0;
gl->vi.command = 0;
gl->insert_curpos = gl->buff_curpos;
return 0;
}
/*.......................................................................
* This action function toggles the case of the character under the
* cursor.
*/
static KT_KEY_FN(gl_change_case)
{
int i;
/*
* Keep a record of the current insert mode and the cursor position.
*/
int insert = gl->insert;
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* We want to overwrite the modified word.
*/
gl->insert = 0;
/*
* Toggle the case of 'count' characters.
*/
for(i=0; i<count && gl->buff_curpos < gl->ntotal; i++) {
char *cptr = gl->line + gl->buff_curpos++;
/*
* Convert the character to upper case?
*/
if(islower((int)(unsigned char) *cptr))
gl_buffer_char(gl, toupper((int) *cptr), cptr - gl->line);
else if(isupper((int)(unsigned char) *cptr))
gl_buffer_char(gl, tolower((int) *cptr), cptr - gl->line);
/*
* Write the possibly modified character back. Note that for non-modified
* characters we want to do this as well, so as to advance the cursor.
*/
if(gl_print_char(gl, *cptr, cptr[1]))
return 1;
};
/*
* Restore the insertion mode.
*/
gl->insert = insert;
return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
}
/*.......................................................................
* This is the action function which implements the vi-style action which
* moves the cursor to the start of the line, then switches to insert mode.
*/
static KT_KEY_FN(gl_vi_insert_at_bol)
{
gl_save_for_undo(gl);
return gl_beginning_of_line(gl, 0, NULL) ||
gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* This is the action function which implements the vi-style action which
* moves the cursor to the end of the line, then switches to insert mode
* to allow text to be appended to the line.
*/
static KT_KEY_FN(gl_vi_append_at_eol)
{
gl_save_for_undo(gl);
gl->vi.command = 0; /* Allow cursor at EOL */
return gl_end_of_line(gl, 0, NULL) ||
gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* This is the action function which implements the vi-style action which
* moves the cursor to right one then switches to insert mode, thus
* allowing text to be appended after the next character.
*/
static KT_KEY_FN(gl_vi_append)
{
gl_save_for_undo(gl);
gl->vi.command = 0; /* Allow cursor at EOL */
return gl_cursor_right(gl, 1, NULL) ||
gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* This action function moves the cursor to the column specified by the
* numeric argument. Column indexes start at 1.
*/
static KT_KEY_FN(gl_goto_column)
{
return gl_place_cursor(gl, count - 1);
}
/*.......................................................................
* Starting with the character under the cursor, replace 'count'
* characters with the next character that the user types.
*/
static KT_KEY_FN(gl_vi_replace_char)
{
char c; /* The replacement character */
int i;
/*
* Keep a record of the current insert mode.
*/
int insert = gl->insert;
/*
* Get the replacement character.
*/
if(gl->vi.repeat.active) {
c = gl->vi.repeat.input_char;
} else {
if(gl_read_terminal(gl, 1, &c))
return 1;
gl->vi.repeat.input_char = c;
};
/*
* Are there 'count' characters to be replaced?
*/
if(gl->ntotal - gl->buff_curpos >= count) {
/*
* If in vi command mode, preserve the current line for potential
* use by vi-undo.
*/
gl_save_for_undo(gl);
/*
* Temporarily switch to overwrite mode.
*/
gl->insert = 0;
/*
* Overwrite the current character plus count-1 subsequent characters
* with the replacement character.
*/
for(i=0; i<count; i++)
gl_add_char_to_line(gl, c);
/*
* Restore the original insert/overwrite mode.
*/
gl->insert = insert;
};
return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
}
/*.......................................................................
* This is an action function which changes all characters between the
* current cursor position and the end of the line.
*/
static KT_KEY_FN(gl_vi_change_rest_of_line)
{
gl_save_for_undo(gl);
gl->vi.command = 0; /* Allow cursor at EOL */
return gl_kill_line(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* This is an action function which changes all characters between the
* start of the line and the current cursor position.
*/
static KT_KEY_FN(gl_vi_change_to_bol)
{
return gl_backward_kill_line(gl,count,NULL) || gl_vi_insert(gl,0,NULL);
}
/*.......................................................................
* This is an action function which deletes the entire contents of the
* current line and switches to insert mode.
*/
static KT_KEY_FN(gl_vi_change_line)
{
return gl_delete_line(gl,count,NULL) || gl_vi_insert(gl,0,NULL);
}
/*.......................................................................
* Starting from the cursor position and looking towards the end of the
* line, copy 'count' characters to the cut buffer.
*/
static KT_KEY_FN(gl_forward_copy_char)
{
/*
* Limit the count to the number of characters available.
*/
if(gl->buff_curpos + count >= gl->ntotal)
count = gl->ntotal - gl->buff_curpos;
if(count < 0)
count = 0;
/*
* Copy the characters to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, count);
gl->cutbuf[count] = '\0';
return 0;
}
/*.......................................................................
* Starting from the character before the cursor position and looking
* backwards towards the start of the line, copy 'count' characters to
* the cut buffer.
*/
static KT_KEY_FN(gl_backward_copy_char)
{
/*
* Limit the count to the number of characters available.
*/
if(count > gl->buff_curpos)
count = gl->buff_curpos;
if(count < 0)
count = 0;
gl_place_cursor(gl, gl->buff_curpos - count);
/*
* Copy the characters to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, count);
gl->cutbuf[count] = '\0';
return 0;
}
/*.......................................................................
* Starting from the cursor position copy to the specified column into the
* cut buffer.
*/
static KT_KEY_FN(gl_copy_to_column)
{
if (--count >= gl->buff_curpos)
return gl_forward_copy_char(gl, count - gl->buff_curpos, NULL);
else
return gl_backward_copy_char(gl, gl->buff_curpos - count, NULL);
}
/*.......................................................................
* Starting from the cursor position copy characters up to a matching
* parenthesis into the cut buffer.
*/
static KT_KEY_FN(gl_copy_to_parenthesis)
{
int curpos = gl_index_of_matching_paren(gl);
if(curpos >= 0) {
gl_save_for_undo(gl);
if(curpos >= gl->buff_curpos)
return gl_forward_copy_char(gl, curpos - gl->buff_curpos + 1, NULL);
else
return gl_backward_copy_char(gl, ++gl->buff_curpos - curpos + 1, NULL);
};
return 0;
}
/*.......................................................................
* Starting from the cursor position copy the rest of the line into the
* cut buffer.
*/
static KT_KEY_FN(gl_copy_rest_of_line)
{
/*
* Copy the characters to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, gl->ntotal - gl->buff_curpos);
gl->cutbuf[gl->ntotal - gl->buff_curpos] = '\0';
return 0;
}
/*.......................................................................
* Copy from the beginning of the line to the cursor position into the
* cut buffer.
*/
static KT_KEY_FN(gl_copy_to_bol)
{
/*
* Copy the characters to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line, gl->buff_curpos);
gl->cutbuf[gl->buff_curpos] = '\0';
gl_place_cursor(gl, 0);
return 0;
}
/*.......................................................................
* Copy the entire line into the cut buffer.
*/
static KT_KEY_FN(gl_copy_line)
{
/*
* Copy the characters to the cut buffer.
*/
memcpy(gl->cutbuf, gl->line, gl->ntotal);
gl->cutbuf[gl->ntotal] = '\0';
return 0;
}
/*.......................................................................
* Search forwards for the next character that the user enters.
*/
static KT_KEY_FN(gl_forward_find_char)
{
int pos = gl_find_char(gl, count, 1, 1, '\0');
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Search backwards for the next character that the user enters.
*/
static KT_KEY_FN(gl_backward_find_char)
{
int pos = gl_find_char(gl, count, 0, 1, '\0');
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Search forwards for the next character that the user enters. Move up to,
* but not onto, the found character.
*/
static KT_KEY_FN(gl_forward_to_char)
{
int pos = gl_find_char(gl, count, 1, 0, '\0');
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Search backwards for the next character that the user enters. Move back to,
* but not onto, the found character.
*/
static KT_KEY_FN(gl_backward_to_char)
{
int pos = gl_find_char(gl, count, 0, 0, '\0');
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Searching in a given direction, return the index of a given (or
* read) character in the input line, or the character that precedes
* it in the specified search direction. Return -1 if not found.
*
* Input:
* gl GetLine * The getline resource object.
* count int The number of times to search.
* forward int True if searching forward.
* onto int True if the search should end on top of the
* character, false if the search should stop
* one character before the character in the
* specified search direction.
* c char The character to be sought, or '\0' if the
* character should be read from the user.
* Output:
* return int The index of the character in gl->line[], or
* -1 if not found.
*/
static int gl_find_char(GetLine *gl, int count, int forward, int onto, char c)
{
int pos; /* The index reached in searching the input line */
int i;
/*
* Get a character from the user?
*/
if(!c) {
/*
* If we are in the process of repeating a previous change command, substitute
* the last find character.
*/
if(gl->vi.repeat.active) {
c = gl->vi.find_char;
} else {
if(gl_read_terminal(gl, 1, &c))
return -1;
/*
* Record the details of the new search, for use by repeat finds.
*/
gl->vi.find_forward = forward;
gl->vi.find_onto = onto;
gl->vi.find_char = c;
};
};
/*
* Which direction should we search?
*/
if(forward) {
/*
* Search forwards 'count' times for the character, starting with the
* character that follows the cursor.
*/
for(i=0, pos=gl->buff_curpos; i<count && pos < gl->ntotal; i++) {
/*
* Advance past the last match (or past the current cursor position
* on the first search).
*/
pos++;
/*
* Search for the next instance of c.
*/
for( ; pos<gl->ntotal && c!=gl->line[pos]; pos++)
;
};
/*
* If the character was found and we have been requested to return the
* position of the character that precedes the desired character, then
* we have gone one character too far.
*/
if(!onto && pos<gl->ntotal)
pos--;
} else {
/*
* Search backwards 'count' times for the character, starting with the
* character that precedes the cursor.
*/
for(i=0, pos=gl->buff_curpos; i<count && pos >= gl->insert_curpos; i++) {
/*
* Step back one from the last match (or from the current cursor
* position on the first search).
*/
pos--;
/*
* Search for the next instance of c.
*/
for( ; pos>=gl->insert_curpos && c!=gl->line[pos]; pos--)
;
};
/*
* If the character was found and we have been requested to return the
* position of the character that precedes the desired character, then
* we have gone one character too far.
*/
if(!onto && pos>=gl->insert_curpos)
pos++;
};
/*
* If found, return the cursor position of the count'th match.
* Otherwise ring the terminal bell.
*/
if(pos >= gl->insert_curpos && pos < gl->ntotal) {
return pos;
} else {
(void) gl_ring_bell(gl, 1, NULL);
return -1;
}
}
/*.......................................................................
* Repeat the last character search in the same direction as the last
* search.
*/
static KT_KEY_FN(gl_repeat_find_char)
{
int pos = gl->vi.find_char ?
gl_find_char(gl, count, gl->vi.find_forward, gl->vi.find_onto,
gl->vi.find_char) : -1;
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Repeat the last character search in the opposite direction as the last
* search.
*/
static KT_KEY_FN(gl_invert_refind_char)
{
int pos = gl->vi.find_char ?
gl_find_char(gl, count, !gl->vi.find_forward, gl->vi.find_onto,
gl->vi.find_char) : -1;
return pos >= 0 && gl_place_cursor(gl, pos);
}
/*.......................................................................
* Search forward from the current position of the cursor for 'count'
* word endings, returning the index of the last one found, or the end of
* the line if there were less than 'count' words.
*
* Input:
* gl GetLine * The getline resource object.
* n int The number of word boundaries to search for.
* Output:
* return int The buffer index of the located position.
*/
static int gl_nth_word_end_forward(GetLine *gl, int n)
{
int bufpos; /* The buffer index being checked. */
int i;
/*
* In order to guarantee forward motion to the next word ending,
* we need to start from one position to the right of the cursor
* position, since this may already be at the end of a word.
*/
bufpos = gl->buff_curpos + 1;
/*
* If we are at the end of the line, return the index of the last
* real character on the line. Note that this will be -1 if the line
* is empty.
*/
if(bufpos >= gl->ntotal)
return gl->ntotal - 1;
/*
* Search 'n' times, unless the end of the input line is reached first.
*/
for(i=0; i<n && bufpos<gl->ntotal; i++) {
/*
* If we are not already within a word, skip to the start of the next word.
*/
for( ; bufpos<gl->ntotal && !gl_is_word_char((int)gl->line[bufpos]);
bufpos++)
;
/*
* Find the end of the next word.
*/
for( ; bufpos<gl->ntotal && gl_is_word_char((int)gl->line[bufpos]);
bufpos++)
;
};
/*
* We will have overshot.
*/
return bufpos > 0 ? bufpos-1 : bufpos;
}
/*.......................................................................
* Search forward from the current position of the cursor for 'count'
* word starts, returning the index of the last one found, or the end of
* the line if there were less than 'count' words.
*
* Input:
* gl GetLine * The getline resource object.
* n int The number of word boundaries to search for.
* Output:
* return int The buffer index of the located position.
*/
static int gl_nth_word_start_forward(GetLine *gl, int n)
{
int bufpos; /* The buffer index being checked. */
int i;
/*
* Get the current cursor position.
*/
bufpos = gl->buff_curpos;
/*
* Search 'n' times, unless the end of the input line is reached first.
*/
for(i=0; i<n && bufpos<gl->ntotal; i++) {
/*
* Find the end of the current word.
*/
for( ; bufpos<gl->ntotal && gl_is_word_char((int)gl->line[bufpos]);
bufpos++)
;
/*
* Skip to the start of the next word.
*/
for( ; bufpos<gl->ntotal && !gl_is_word_char((int)gl->line[bufpos]);
bufpos++)
;
};
return bufpos;
}
/*.......................................................................
* Search backward from the current position of the cursor for 'count'
* word starts, returning the index of the last one found, or the start
* of the line if there were less than 'count' words.
*
* Input:
* gl GetLine * The getline resource object.
* n int The number of word boundaries to search for.
* Output:
* return int The buffer index of the located position.
*/
static int gl_nth_word_start_backward(GetLine *gl, int n)
{
int bufpos; /* The buffer index being checked. */
int i;
/*
* Get the current cursor position.
*/
bufpos = gl->buff_curpos;
/*
* Search 'n' times, unless the beginning of the input line (or vi insertion
* point) is reached first.
*/
for(i=0; i<n && bufpos > gl->insert_curpos; i++) {
/*
* Starting one character back from the last search, so as not to keep
* settling on the same word-start, search backwards until finding a
* word character.
*/
while(--bufpos >= gl->insert_curpos &&
!gl_is_word_char((int)gl->line[bufpos]))
;
/*
* Find the start of the word.
*/
while(--bufpos >= gl->insert_curpos &&
gl_is_word_char((int)gl->line[bufpos]))
;
/*
* We will have gone one character too far.
*/
bufpos++;
};
return bufpos >= gl->insert_curpos ? bufpos : gl->insert_curpos;
}
/*.......................................................................
* Copy one or more words into the cut buffer without moving the cursor
* or deleting text.
*/
static KT_KEY_FN(gl_forward_copy_word)
{
/*
* Find the location of the count'th start or end of a word
* after the cursor, depending on whether in emacs or vi mode.
*/
int next = gl->editor == GL_EMACS_MODE ?
gl_nth_word_end_forward(gl, count) :
gl_nth_word_start_forward(gl, count);
/*
* How many characters are to be copied into the cut buffer?
*/
int n = next - gl->buff_curpos;
/*
* Copy the specified segment and terminate the string.
*/
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, n);
gl->cutbuf[n] = '\0';
return 0;
}
/*.......................................................................
* Copy one or more words preceding the cursor into the cut buffer,
* without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_backward_copy_word)
{
/*
* Find the location of the count'th start of word before the cursor.
*/
int next = gl_nth_word_start_backward(gl, count);
/*
* How many characters are to be copied into the cut buffer?
*/
int n = gl->buff_curpos - next;
gl_place_cursor(gl, next);
/*
* Copy the specified segment and terminate the string.
*/
memcpy(gl->cutbuf, gl->line + next, n);
gl->cutbuf[n] = '\0';
return 0;
}
/*.......................................................................
* Copy the characters between the cursor and the count'th instance of
* a specified character in the input line, into the cut buffer.
*
* Input:
* gl GetLine * The getline resource object.
* count int The number of times to search.
* c char The character to be searched for, or '\0' if
* the character should be read from the user.
* forward int True if searching forward.
* onto int True if the search should end on top of the
* character, false if the search should stop
* one character before the character in the
* specified search direction.
* Output:
* return int 0 - OK.
* 1 - Error.
*
*/
static int gl_copy_find(GetLine *gl, int count, char c, int forward, int onto)
{
int n; /* The number of characters in the cut buffer */
/*
* Search for the character, and abort the operation if not found.
*/
int pos = gl_find_char(gl, count, forward, onto, c);
if(pos < 0)
return 0;
/*
* Copy the specified segment.
*/
if(forward) {
n = pos + 1 - gl->buff_curpos;
memcpy(gl->cutbuf, gl->line + gl->buff_curpos, n);
} else {
n = gl->buff_curpos - pos;
memcpy(gl->cutbuf, gl->line + pos, n);
if(gl->editor == GL_VI_MODE)
gl_place_cursor(gl, pos);
}
/*
* Terminate the copy.
*/
gl->cutbuf[n] = '\0';
return 0;
}
/*.......................................................................
* Copy a section up to and including a specified character into the cut
* buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_forward_copy_find)
{
return gl_copy_find(gl, count, '\0', 1, 1);
}
/*.......................................................................
* Copy a section back to and including a specified character into the cut
* buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_backward_copy_find)
{
return gl_copy_find(gl, count, '\0', 0, 1);
}
/*.......................................................................
* Copy a section up to and not including a specified character into the cut
* buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_forward_copy_to)
{
return gl_copy_find(gl, count, '\0', 1, 0);
}
/*.......................................................................
* Copy a section back to and not including a specified character into the cut
* buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_backward_copy_to)
{
return gl_copy_find(gl, count, '\0', 0, 0);
}
/*.......................................................................
* Copy to a character specified in a previous search into the cut
* buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_copy_refind)
{
return gl_copy_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
gl->vi.find_onto);
}
/*.......................................................................
* Copy to a character specified in a previous search, but in the opposite
* direction, into the cut buffer without moving the cursor or deleting text.
*/
static KT_KEY_FN(gl_copy_invert_refind)
{
return gl_copy_find(gl, count, gl->vi.find_char, !gl->vi.find_forward,
gl->vi.find_onto);
}
/*.......................................................................
* Set the position of the cursor in the line input buffer and the
* terminal.
*
* Input:
* gl GetLine * The getline resource object.
* buff_curpos int The new buffer cursor position.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_place_cursor(GetLine *gl, int buff_curpos)
{
/*
* Don't allow the cursor position to go out of the bounds of the input
* line.
*/
if(buff_curpos >= gl->ntotal)
buff_curpos = gl->vi.command ? gl->ntotal-1 : gl->ntotal;
if(buff_curpos < 0)
buff_curpos = 0;
/*
* Record the new buffer position.
*/
gl->buff_curpos = buff_curpos;
/*
* Move the terminal cursor to the corresponding character.
*/
return gl_set_term_curpos(gl, gl->prompt_len +
gl_displayed_string_width(gl, gl->line, buff_curpos, gl->prompt_len));
}
/*.......................................................................
* In vi command mode, this function saves the current line to the
* historical buffer needed by the undo command. In emacs mode it does
* nothing. In order to allow action functions to call other action
* functions, gl_interpret_char() sets gl->vi.undo.saved to 0 before
* invoking an action, and thereafter once any call to this function
* has set it to 1, further calls are ignored.
*
* Input:
* gl GetLine * The getline resource object.
*/
static void gl_save_for_undo(GetLine *gl)
{
if(gl->vi.command && !gl->vi.undo.saved) {
strlcpy(gl->vi.undo.line, gl->line, gl->linelen);
gl->vi.undo.buff_curpos = gl->buff_curpos;
gl->vi.undo.ntotal = gl->ntotal;
gl->vi.undo.saved = 1;
};
if(gl->vi.command && !gl->vi.repeat.saved &&
gl->current_action.fn != gl_vi_repeat_change) {
gl->vi.repeat.action = gl->current_action;
gl->vi.repeat.count = gl->current_count;
gl->vi.repeat.saved = 1;
};
return;
}
/*.......................................................................
* In vi mode, restore the line to the way it was before the last command
* mode operation, storing the current line in the buffer so that the
* undo operation itself can subsequently be undone.
*/
static KT_KEY_FN(gl_vi_undo)
{
/*
* Get pointers into the two lines.
*/
char *undo_ptr = gl->vi.undo.line;
char *line_ptr = gl->line;
/*
* Swap the characters of the two buffers up to the length of the shortest
* line.
*/
while(*undo_ptr && *line_ptr) {
char c = *undo_ptr;
*undo_ptr++ = *line_ptr;
*line_ptr++ = c;
};
/*
* Copy the rest directly.
*/
if(gl->ntotal > gl->vi.undo.ntotal) {
strlcpy(undo_ptr, line_ptr, gl->linelen);
*line_ptr = '\0';
} else {
strlcpy(line_ptr, undo_ptr, gl->linelen);
*undo_ptr = '\0';
};
/*
* Record the length of the stored string.
*/
gl->vi.undo.ntotal = gl->ntotal;
/*
* Accomodate the new contents of gl->line[].
*/
gl_update_buffer(gl);
/*
* Set both cursor positions to the leftmost of the saved and current
* cursor positions to emulate what vi does.
*/
if(gl->buff_curpos < gl->vi.undo.buff_curpos)
gl->vi.undo.buff_curpos = gl->buff_curpos;
else
gl->buff_curpos = gl->vi.undo.buff_curpos;
/*
* Since we have bipassed calling gl_save_for_undo(), record repeat
* information inline.
*/
gl->vi.repeat.action.fn = gl_vi_undo;
gl->vi.repeat.action.data = NULL;
gl->vi.repeat.count = 1;
/*
* Display the restored line.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* Delete the following word and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_forward_change_word)
{
gl_save_for_undo(gl);
gl->vi.command = 0; /* Allow cursor at EOL */
return gl_forward_delete_word(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* Delete the preceding word and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_backward_change_word)
{
return gl_backward_delete_word(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* Delete the following section and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_forward_change_find)
{
return gl_delete_find(gl, count, '\0', 1, 1, 1);
}
/*.......................................................................
* Delete the preceding section and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_backward_change_find)
{
return gl_delete_find(gl, count, '\0', 0, 1, 1);
}
/*.......................................................................
* Delete the following section and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_forward_change_to)
{
return gl_delete_find(gl, count, '\0', 1, 0, 1);
}
/*.......................................................................
* Delete the preceding section and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_backward_change_to)
{
return gl_delete_find(gl, count, '\0', 0, 0, 1);
}
/*.......................................................................
* Delete to a character specified by a previous search and leave the user
* in vi insert mode.
*/
static KT_KEY_FN(gl_vi_change_refind)
{
return gl_delete_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
gl->vi.find_onto, 1);
}
/*.......................................................................
* Delete to a character specified by a previous search, but in the opposite
* direction, and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_change_invert_refind)
{
return gl_delete_find(gl, count, gl->vi.find_char, !gl->vi.find_forward,
gl->vi.find_onto, 1);
}
/*.......................................................................
* Delete the following character and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_forward_change_char)
{
gl_save_for_undo(gl);
gl->vi.command = 0; /* Allow cursor at EOL */
return gl_delete_chars(gl, count, 1) || gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* Delete the preceding character and leave the user in vi insert mode.
*/
static KT_KEY_FN(gl_vi_backward_change_char)
{
return gl_backward_delete_char(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
}
/*.......................................................................
* Starting from the cursor position change characters to the specified column.
*/
static KT_KEY_FN(gl_vi_change_to_column)
{
if (--count >= gl->buff_curpos)
return gl_vi_forward_change_char(gl, count - gl->buff_curpos, NULL);
else
return gl_vi_backward_change_char(gl, gl->buff_curpos - count, NULL);
}
/*.......................................................................
* Starting from the cursor position change characters to a matching
* parenthesis.
*/
static KT_KEY_FN(gl_vi_change_to_parenthesis)
{
int curpos = gl_index_of_matching_paren(gl);
if(curpos >= 0) {
gl_save_for_undo(gl);
if(curpos >= gl->buff_curpos)
return gl_vi_forward_change_char(gl, curpos - gl->buff_curpos + 1, NULL);
else
return gl_vi_backward_change_char(gl, ++gl->buff_curpos - curpos + 1,
NULL);
};
return 0;
}
/*.......................................................................
* If in vi mode, switch to vi command mode.
*
* Input:
* gl GetLine * The getline resource object.
*/
static void gl_vi_command_mode(GetLine *gl)
{
if(gl->editor == GL_VI_MODE && !gl->vi.command) {
gl->insert = 1;
gl->vi.command = 1;
gl->vi.repeat.input_curpos = gl->insert_curpos;
gl->vi.repeat.command_curpos = gl->buff_curpos;
gl->insert_curpos = 0; /* unrestrict left motion boundary */
gl_cursor_left(gl, 1, NULL); /* Vi moves 1 left on entering command mode */
};
}
/*.......................................................................
* This is an action function which rings the terminal bell.
*/
static KT_KEY_FN(gl_ring_bell)
{
return gl->silence_bell ? 0 :
gl_print_control_sequence(gl, 1, gl->sound_bell);
}
/*.......................................................................
* This is the action function which implements the vi-repeat-change
* action.
*/
static KT_KEY_FN(gl_vi_repeat_change)
{
int status; /* The return status of the repeated action function */
int i;
/*
* Nothing to repeat?
*/
if(!gl->vi.repeat.action.fn)
return gl_ring_bell(gl, 1, NULL);
/*
* Provide a way for action functions to know whether they are being
* called by us.
*/
gl->vi.repeat.active = 1;
/*
* Re-run the recorded function.
*/
status = gl->vi.repeat.action.fn(gl, gl->vi.repeat.count,
gl->vi.repeat.action.data);
/*
* Mark the repeat as completed.
*/
gl->vi.repeat.active = 0;
/*
* Is we are repeating a function that has just switched to input
* mode to allow the user to type, re-enter the text that the user
* previously entered.
*/
if(status==0 && !gl->vi.command) {
/*
* Make sure that the current line has been saved.
*/
gl_save_for_undo(gl);
/*
* Repeat a previous insertion or overwrite?
*/
if(gl->vi.repeat.input_curpos >= 0 &&
gl->vi.repeat.input_curpos <= gl->vi.repeat.command_curpos &&
gl->vi.repeat.command_curpos <= gl->vi.undo.ntotal) {
/*
* Using the current line which is saved in the undo buffer, plus
* the range of characters therein, as recorded by gl_vi_command_mode(),
* add the characters that the user previously entered, to the input
* line.
*/
for(i=gl->vi.repeat.input_curpos; i<gl->vi.repeat.command_curpos; i++) {
if(gl_add_char_to_line(gl, gl->vi.undo.line[i]))
return 1;
};
};
/*
* Switch back to command mode, now that the insertion has been repeated.
*/
gl_vi_command_mode(gl);
};
return status;
}
/*.......................................................................
* If the cursor is currently over a parenthesis character, return the
* index of its matching parenthesis. If not currently over a parenthesis
* character, return the next close parenthesis character to the right of
* the cursor. If the respective parenthesis character isn't found,
* ring the terminal bell and return -1.
*
* Input:
* gl GetLine * The getline resource object.
* Output:
* return int Either the index of the matching parenthesis,
* or -1 if not found.
*/
static int gl_index_of_matching_paren(GetLine *gl)
{
int i;
/*
* List the recognized parentheses, and their matches.
*/
const char *o_paren = "([{";
const char *c_paren = ")]}";
const char *cptr;
/*
* Get the character that is currently under the cursor.
*/
char c = gl->line[gl->buff_curpos];
/*
* If the character under the cursor is an open parenthesis, look forward
* for the matching close parenthesis.
*/
if((cptr=strchr(o_paren, c))) {
char match = c_paren[cptr - o_paren];
int matches_needed = 1;
for(i=gl->buff_curpos+1; i<gl->ntotal; i++) {
if(gl->line[i] == c)
matches_needed++;
else if(gl->line[i] == match && --matches_needed==0)
return i;
};
/*
* If the character under the cursor is an close parenthesis, look forward
* for the matching open parenthesis.
*/
} else if((cptr=strchr(c_paren, c))) {
char match = o_paren[cptr - c_paren];
int matches_needed = 1;
for(i=gl->buff_curpos-1; i>=0; i--) {
if(gl->line[i] == c)
matches_needed++;
else if(gl->line[i] == match && --matches_needed==0)
return i;
};
/*
* If not currently over a parenthesis character, search forwards for
* the first close parenthesis (this is what the vi % binding does).
*/
} else {
for(i=gl->buff_curpos+1; i<gl->ntotal; i++)
if(strchr(c_paren, gl->line[i]) != NULL)
return i;
};
/*
* Not found.
*/
(void) gl_ring_bell(gl, 1, NULL);
return -1;
}
/*.......................................................................
* If the cursor is currently over a parenthesis character, this action
* function moves the cursor to its matching parenthesis.
*/
static KT_KEY_FN(gl_find_parenthesis)
{
int curpos = gl_index_of_matching_paren(gl);
if(curpos >= 0)
return gl_place_cursor(gl, curpos);
return 0;
}
/*.......................................................................
* Handle the receipt of the potential start of a new key-sequence from
* the user.
*
* Input:
* gl GetLine * The resource object of this library.
* first_char char The first character of the sequence.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_interpret_char(GetLine *gl, char first_char)
{
char keyseq[GL_KEY_MAX+1]; /* A special key sequence being read */
int nkey=0; /* The number of characters in the key sequence */
int count; /* The repeat count of an action function */
int ret; /* The return value of an action function */
int i;
/*
* Get the first character.
*/
char c = first_char;
/*
* If editing is disabled, just add newly entered characters to the
* input line buffer, and watch for the end of the line.
*/
if(gl->editor == GL_NO_EDITOR) {
gl_discard_chars(gl, 1);
if(gl->ntotal >= gl->linelen)
return 0;
if(c == '\n' || c == '\r')
return gl_newline(gl, 1, NULL);
gl_buffer_char(gl, c, gl->ntotal);
return 0;
};
/*
* If the user is in the process of specifying a repeat count and the
* new character is a digit, increment the repeat count accordingly.
*/
if(gl->number >= 0 && isdigit((int)(unsigned char) c)) {
gl_discard_chars(gl, 1);
return gl_digit_argument(gl, c, NULL);
/*
* In vi command mode, all key-sequences entered need to be
* either implicitly or explicitly prefixed with an escape character.
*/
} else if(gl->vi.command && c != GL_ESC_CHAR) {
keyseq[nkey++] = GL_ESC_CHAR;
/*
* If the first character of the sequence is a printable character,
* then to avoid confusion with the special "up", "down", "left"
* or "right" cursor key bindings, we need to prefix the
* printable character with a backslash escape before looking it up.
*/
} else if(!IS_META_CHAR(c) && !IS_CTRL_CHAR(c)) {
keyseq[nkey++] = '\\';
};
/*
* Compose a potentially multiple key-sequence in gl->keyseq.
*/
while(nkey < GL_KEY_MAX) {
KtAction *action; /* An action function */
KeySym *keysym; /* The symbol-table entry of a key-sequence */
int nsym; /* The number of ambiguously matching key-sequences */
/*
* If the character is an unprintable meta character, split it
* into two characters, an escape character and the character
* that was modified by the meta key.
*/
if(IS_META_CHAR(c)) {
keyseq[nkey++] = GL_ESC_CHAR;
c = META_TO_CHAR(c);
continue;
};
/*
* Append the latest character to the key sequence.
*/
keyseq[nkey++] = c;
/*
* When doing vi-style editing, an escape at the beginning of any binding
* switches to command mode.
*/
if(keyseq[0] == GL_ESC_CHAR && !gl->vi.command)
gl_vi_command_mode(gl);
/*
* Lookup the key sequence.
*/
switch(_kt_lookup_keybinding(gl->bindings, keyseq, nkey, &keysym, &nsym)) {
case KT_EXACT_MATCH:
/*
* Get the matching action function.
*/
action = keysym->actions + keysym->binder;
/*
* Get the repeat count, passing the last keystroke if executing the
* digit-argument action.
*/
if(action->fn == gl_digit_argument) {
count = c;
} else {
count = gl->number >= 0 ? gl->number : 1;
};
/*
* Record the function that is being invoked.
*/
gl->current_action = *action;
gl->current_count = count;
/*
* Mark the current line as not yet preserved for use by the vi undo command.
*/
gl->vi.undo.saved = 0;
gl->vi.repeat.saved = 0;
/*
* Execute the action function. Note the action function can tell
* whether the provided repeat count was defaulted or specified
* explicitly by looking at whether gl->number is -1 or not. If
* it is negative, then no repeat count was specified by the user.
*/
ret = action->fn(gl, count, action->data);
/*
* In server mode, the action will return immediately if it tries to
* read input from the terminal, and no input is currently available.
* If this happens, abort. Note that gl_get_input_line() will rewind
* the read-ahead buffer to allow the next call to redo the function
* from scratch.
*/
if(gl->rtn_status == GLR_BLOCKED && gl->pending_io==GLP_READ)
return 1;
/*
* Discard the now processed characters from the key sequence buffer.
*/
gl_discard_chars(gl, gl->nread);
/*
* If the latest action function wasn't a history action, cancel any
* current history search.
*/
if(gl->last_search != gl->keyseq_count)
_glh_cancel_search(gl->glh);
/*
* Reset the repeat count after running action functions.
*/
if(action->fn != gl_digit_argument)
gl->number = -1;
return ret ? 1 : 0;
break;
case KT_AMBIG_MATCH: /* Ambiguous match - so read the next character */
if(gl_read_terminal(gl, 1, &c))
return 1;
break;
case KT_NO_MATCH:
/*
* If the first character looked like it might be a prefix of a key-sequence
* but it turned out not to be, ring the bell to tell the user that it
* wasn't recognised.
*/
if(keyseq[0] != '\\' && keyseq[0] != '\t') {
gl_ring_bell(gl, 1, NULL);
} else {
/*
* The user typed a single printable character that doesn't match
* the start of any keysequence, so add it to the line in accordance
* with the current repeat count.
*/
count = gl->number >= 0 ? gl->number : 1;
for(i=0; i<count; i++)
gl_add_char_to_line(gl, first_char);
gl->number = -1;
};
gl_discard_chars(gl, 1);
_glh_cancel_search(gl->glh);
return 0;
break;
case KT_BAD_MATCH:
gl_ring_bell(gl, 1, NULL);
gl_discard_chars(gl, gl->nread);
_glh_cancel_search(gl->glh);
return 1;
break;
};
};
/*
* If the key sequence was too long to match, ring the bell, then
* discard the first character, so that the next attempt to match a
* key-sequence continues with the next key press. In practice this
* shouldn't happen, since one isn't allowed to bind action functions
* to keysequences that are longer than GL_KEY_MAX.
*/
gl_ring_bell(gl, 1, NULL);
gl_discard_chars(gl, 1);
return 0;
}
/*.......................................................................
* Configure the application and/or user-specific behavior of
* gl_get_line().
*
* Note that calling this function between calling new_GetLine() and
* the first call to gl_get_line(), disables the otherwise automatic
* reading of ~/.teclarc on the first call to gl_get_line().
*
* Input:
* gl GetLine * The resource object of this library.
* app_string const char * Either NULL, or a string containing one
* or more .teclarc command lines, separated
* by newline characters. This can be used to
* establish an application-specific
* configuration, without the need for an external
* file. This is particularly useful in embedded
* environments where there is no filesystem.
* app_file const char * Either NULL, or the pathname of an
* application-specific .teclarc file. The
* contents of this file, if provided, are
* read after the contents of app_string[].
* user_file const char * Either NULL, or the pathname of a
* user-specific .teclarc file. Except in
* embedded applications, this should
* usually be "~/.teclarc".
* Output:
* return int 0 - OK.
* 1 - Bad argument(s).
*/
int gl_configure_getline(GetLine *gl, const char *app_string,
const char *app_file, const char *user_file)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_configure_getline() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_configure_getline(gl, app_string, app_file, user_file);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_configure_getline() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_configure_getline(GetLine *gl, const char *app_string,
const char *app_file, const char *user_file)
{
/*
* Mark getline as having been explicitly configured.
*/
gl->configured = 1;
/*
* Start by parsing the configuration string, if provided.
*/
if(app_string)
(void) _gl_read_config_string(gl, app_string, KTB_NORM);
/*
* Now parse the application-specific configuration file, if provided.
*/
if(app_file)
(void) _gl_read_config_file(gl, app_file, KTB_NORM);
/*
* Finally, parse the user-specific configuration file, if provided.
*/
if(user_file)
(void) _gl_read_config_file(gl, user_file, KTB_USER);
/*
* Record the names of the configuration files to allow them to
* be re-read if requested at a later time.
*/
if(gl_record_string(&gl->app_file, app_file) ||
gl_record_string(&gl->user_file, user_file)) {
errno = ENOMEM;
_err_record_msg(gl->err,
"Insufficient memory to record tecla configuration file names",
END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Replace a malloc'd string (or NULL), with another malloc'd copy of
* a string (or NULL).
*
* Input:
* sptr char ** On input if *sptr!=NULL, *sptr will be
* free'd and *sptr will be set to NULL. Then,
* on output, if string!=NULL a malloc'd copy
* of this string will be assigned to *sptr.
* string const char * The string to be copied, or NULL to simply
* discard any existing string.
* Output:
* return int 0 - OK.
* 1 - Malloc failure (no error message is generated).
*/
static int gl_record_string(char **sptr, const char *string)
{
/*
* If the original string is the same string, don't do anything.
*/
if(*sptr == string || (*sptr && string && strcmp(*sptr, string)==0))
return 0;
/*
* Discard any existing cached string.
*/
if(*sptr) {
free(*sptr);
*sptr = NULL;
};
/*
* Allocate memory for a copy of the specified string.
*/
if(string) {
size_t ssz = strlen(string) + 1;
*sptr = (char *) malloc(ssz);
if(!*sptr)
return 1;
/*
* Copy the string.
*/
strlcpy(*sptr, string, ssz);
};
return 0;
}
#ifndef HIDE_FILE_SYSTEM
/*.......................................................................
* Re-read any application-specific and user-specific files previously
* specified via the gl_configure_getline() function.
*/
static KT_KEY_FN(gl_read_init_files)
{
return _gl_configure_getline(gl, NULL, gl->app_file, gl->user_file);
}
#endif
/*.......................................................................
* Save the contents of the history buffer to a given new file.
*
* Input:
* gl GetLine * The resource object of this library.
* filename const char * The name of the new file to write to.
* comment const char * Extra information such as timestamps will
* be recorded on a line started with this
* string, the idea being that the file can
* double as a command file. Specify "" if
* you don't care.
* max_lines int The maximum number of lines to save, or -1
* to save all of the lines in the history
* list.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_save_history(GetLine *gl, const char *filename, const char *comment,
int max_lines)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_save_history() */
/*
* Check the arguments.
*/
if(!gl || !filename || !comment) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_save_history(gl, filename, comment, max_lines);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_save_history() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_save_history(GetLine *gl, const char *filename,
const char *comment, int max_lines)
{
/*
* If filesystem access is to be excluded, then history files can't
* be written.
*/
#ifdef WITHOUT_FILE_SYSTEM
_err_record_msg(gl->err, "Can't save history without filesystem access",
END_ERR_MSG);
errno = EINVAL;
return 1;
#else
FileExpansion *expansion; /* The expansion of the filename */
/*
* Expand the filename.
*/
expansion = ef_expand_file(gl->ef, filename, -1);
if(!expansion) {
gl_print_info(gl, "Unable to expand ", filename, " (",
ef_last_error(gl->ef), ").", GL_END_INFO);
return 1;
};
/*
* Attempt to save to the specified file.
*/
if(_glh_save_history(gl->glh, expansion->files[0], comment, max_lines)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
return 0;
#endif
}
/*.......................................................................
* Restore the contents of the history buffer from a given new file.
*
* Input:
* gl GetLine * The resource object of this library.
* filename const char * The name of the new file to write to.
* comment const char * This must be the same string that was
* passed to gl_save_history() when the file
* was written.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_load_history(GetLine *gl, const char *filename, const char *comment)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_load_history() */
/*
* Check the arguments.
*/
if(!gl || !filename || !comment) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_load_history(gl, filename, comment);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_load_history() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_load_history(GetLine *gl, const char *filename,
const char *comment)
{
/*
* If filesystem access is to be excluded, then history files can't
* be read.
*/
#ifdef WITHOUT_FILE_SYSTEM
_err_record_msg(gl->err, "Can't load history without filesystem access",
END_ERR_MSG);
errno = EINVAL;
return 1;
#else
FileExpansion *expansion; /* The expansion of the filename */
/*
* Expand the filename.
*/
expansion = ef_expand_file(gl->ef, filename, -1);
if(!expansion) {
gl_print_info(gl, "Unable to expand ", filename, " (",
ef_last_error(gl->ef), ").", GL_END_INFO);
return 1;
};
/*
* Attempt to load from the specified file.
*/
if(_glh_load_history(gl->glh, expansion->files[0], comment,
gl->cutbuf, gl->linelen+1)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
gl->cutbuf[0] = '\0';
return 1;
};
gl->cutbuf[0] = '\0';
return 0;
#endif
}
/*.......................................................................
* Where possible, register a function and associated data to be called
* whenever a specified event is seen on a file descriptor.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* fd int The file descriptor to watch.
* event GlFdEvent The type of activity to watch for.
* callback GlFdEventFn * The function to call when the specified
* event occurs. Setting this to 0 removes
* any existing callback.
* data void * A pointer to arbitrary data to pass to the
* callback function.
* Output:
* return int 0 - OK.
* 1 - Either gl==NULL, or this facility isn't
* available on the the host system
* (ie. select() isn't available). No
* error message is generated in the latter
* case.
*/
int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
GlFdEventFn *callback, void *data)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_watch_fd() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
if(fd < 0) {
_err_record_msg(gl->err, "Error: fd < 0", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_watch_fd(gl, fd, event, callback, data);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_watch_fd() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
GlFdEventFn *callback, void *data)
#if !defined(HAVE_SELECT)
{return 1;} /* The facility isn't supported on this system */
#else
{
GlFdNode *prev; /* The node that precedes 'node' in gl->fd_nodes */
GlFdNode *node; /* The file-descriptor node being checked */
/*
* Search the list of already registered fd activity nodes for the specified
* file descriptor.
*/
for(prev=NULL,node=gl->fd_nodes; node && node->fd != fd;
prev=node, node=node->next)
;
/*
* Hasn't a node been allocated for this fd yet?
*/
if(!node) {
/*
* If there is no callback to record, just ignore the call.
*/
if(!callback)
return 0;
/*
* Allocate the new node.
*/
node = (GlFdNode *) _new_FreeListNode(gl->fd_node_mem);
if(!node) {
errno = ENOMEM;
_err_record_msg(gl->err, "Insufficient memory", END_ERR_MSG);
return 1;
};
/*
* Prepend the node to the list.
*/
node->next = gl->fd_nodes;
gl->fd_nodes = node;
/*
* Initialize the node.
*/
node->fd = fd;
node->rd.fn = 0;
node->rd.data = NULL;
node->ur = node->wr = node->rd;
};
/*
* Record the new callback.
*/
switch(event) {
case GLFD_READ:
node->rd.fn = callback;
node->rd.data = data;
if(callback)
FD_SET(fd, &gl->rfds);
else
FD_CLR(fd, &gl->rfds);
break;
case GLFD_WRITE:
node->wr.fn = callback;
node->wr.data = data;
if(callback)
FD_SET(fd, &gl->wfds);
else
FD_CLR(fd, &gl->wfds);
break;
case GLFD_URGENT:
node->ur.fn = callback;
node->ur.data = data;
if(callback)
FD_SET(fd, &gl->ufds);
else
FD_CLR(fd, &gl->ufds);
break;
};
/*
* Keep a record of the largest file descriptor being watched.
*/
if(fd > gl->max_fd)
gl->max_fd = fd;
/*
* If we are deleting an existing callback, also delete the parent
* activity node if no callbacks are registered to the fd anymore.
*/
if(!callback) {
if(!node->rd.fn && !node->wr.fn && !node->ur.fn) {
if(prev)
prev->next = node->next;
else
gl->fd_nodes = node->next;
node = (GlFdNode *) _del_FreeListNode(gl->fd_node_mem, node);
};
};
return 0;
}
#endif
/*.......................................................................
* On systems with the select() system call, the gl_inactivity_timeout()
* function provides the option of setting (or cancelling) an
* inactivity timeout. Inactivity, in this case, refers both to
* terminal input received from the user, and to I/O on any file
* descriptors registered by calls to gl_watch_fd(). If at any time,
* no activity is seen for the requested time period, the specified
* timeout callback function is called. On returning, this callback
* returns a code which tells gl_get_line() what to do next. Note that
* each call to gl_inactivity_timeout() replaces any previously installed
* timeout callback, and that specifying a callback of 0, turns off
* inactivity timing.
*
* Beware that although the timeout argument includes a nano-second
* component, few computer clocks presently have resolutions finer
* than a few milliseconds, so asking for less than a few milliseconds
* is equivalent to zero on a lot of systems.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* callback GlTimeoutFn * The function to call when the inactivity
* timeout is exceeded. To turn off
* inactivity timeouts altogether, send 0.
* data void * A pointer to arbitrary data to pass to the
* callback function.
* sec unsigned long The number of whole seconds in the timeout.
* nsec unsigned long The fractional number of seconds in the
* timeout, expressed in nano-seconds (see
* the caveat above).
* Output:
* return int 0 - OK.
* 1 - Either gl==NULL, or this facility isn't
* available on the the host system
* (ie. select() isn't available). No
* error message is generated in the latter
* case.
*/
int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *timeout_fn, void *data,
unsigned long sec, unsigned long nsec)
#if !defined(HAVE_SELECT)
{return 1;} /* The facility isn't supported on this system */
#else
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Install a new timeout?
*/
if(timeout_fn) {
gl->timer.dt.tv_sec = sec;
gl->timer.dt.tv_usec = nsec / 1000;
gl->timer.fn = timeout_fn;
gl->timer.data = data;
} else {
gl->timer.fn = 0;
gl->timer.data = NULL;
};
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return 0;
}
#endif
/*.......................................................................
* When select() is available, this is a private function of
* gl_read_input() which responds to file-descriptor events registered by
* the caller. Note that it assumes that it is being called from within
* gl_read_input()'s sigsetjump() clause.
*
* Input:
* gl GetLine * The resource object of this module.
* fd int The file descriptor to be watched for user input.
* Output:
* return int 0 - OK.
* 1 - An error occurred.
*/
static int gl_event_handler(GetLine *gl, int fd)
{
#if !defined(HAVE_SELECT)
return 0;
#else
/*
* Set up a zero-second timeout.
*/
struct timeval zero;
zero.tv_sec = zero.tv_usec = 0;
/*
* If at any time no external callbacks remain, quit the loop return,
* so that we can simply wait in read(). This is designed as an
* optimization for when no callbacks have been registered on entry to
* this function, but since callbacks can delete themselves, it can
* also help later.
*/
while(gl->fd_nodes || gl->timer.fn) {
int nready; /* The number of file descriptors that are ready for I/O */
/*
* Get the set of descriptors to be watched.
*/
fd_set rfds = gl->rfds;
fd_set wfds = gl->wfds;
fd_set ufds = gl->ufds;
/*
* Get the appropriate timeout.
*/
struct timeval dt = gl->timer.fn ? gl->timer.dt : zero;
/*
* Add the specified user-input file descriptor to the set that is to
* be watched.
*/
FD_SET(fd, &rfds);
/*
* Unblock the signals that we are watching, while select is blocked
* waiting for I/O.
*/
gl_catch_signals(gl);
/*
* Wait for activity on any of the file descriptors.
*/
nready = select(gl->max_fd+1, &rfds, &wfds, &ufds,
(gl->timer.fn || gl->io_mode==GL_SERVER_MODE) ? &dt : NULL);
/*
* We don't want to do a longjmp in the middle of a callback that
* might be modifying global or heap data, so block all the signals
* that we are trapping before executing callback functions. Note that
* the caller will unblock them again when it needs to, so there is
* no need to undo this before returning.
*/
gl_mask_signals(gl, NULL);
/*
* If select() returns but none of the file descriptors are reported
* to have activity, then select() timed out.
*/
if(nready == 0) {
/*
* Note that in non-blocking server mode, the inactivity timer is used
* to allow I/O to block for a specified amount of time, so in this
* mode we return the postponed blocked status when an abort is
* requested.
*/
if(gl_call_timeout_handler(gl)) {
return 1;
} else if(gl->io_mode == GL_SERVER_MODE) {
gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
return 1;
};
/*
* If nready < 0, this means an error occurred.
*/
} else if(nready < 0) {
if(errno != EINTR) {
gl_record_status(gl, GLR_ERROR, errno);
return 1;
};
/*
* If the user-input file descriptor has data available, return.
*/
} else if(FD_ISSET(fd, &rfds)) {
return 0;
/*
* Check for activity on any of the file descriptors registered by the
* calling application, and call the associated callback functions.
*/
} else {
GlFdNode *node; /* The fd event node being checked */
/*
* Search the list for the file descriptor that caused select() to return.
*/
for(node=gl->fd_nodes; node; node=node->next) {
/*
* Is there urgent out of band data waiting to be read on fd?
*/
if(node->ur.fn && FD_ISSET(node->fd, &ufds)) {
if(gl_call_fd_handler(gl, &node->ur, node->fd, GLFD_URGENT))
return 1;
break; /* The callback may have changed the list of nodes */
/*
* Is the fd readable?
*/
} else if(node->rd.fn && FD_ISSET(node->fd, &rfds)) {
if(gl_call_fd_handler(gl, &node->rd, node->fd, GLFD_READ))
return 1;
break; /* The callback may have changed the list of nodes */
/*
* Is the fd writable?
*/
} else if(node->wr.fn && FD_ISSET(node->fd, &wfds)) {
if(gl_call_fd_handler(gl, &node->wr, node->fd, GLFD_WRITE))
return 1;
break; /* The callback may have changed the list of nodes */
};
};
};
/*
* Just in case the above event handlers asked for the input line to
* be redrawn, flush any pending output.
*/
if(gl_flush_output(gl))
return 1;
};
return 0;
}
#endif
#if defined(HAVE_SELECT)
/*.......................................................................
* This is a private function of gl_event_handler(), used to call a
* file-descriptor callback.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* gfh GlFdHandler * The I/O handler.
* fd int The file-descriptor being reported.
* event GlFdEvent The I/O event being reported.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_call_fd_handler(GetLine *gl, GlFdHandler *gfh, int fd,
GlFdEvent event)
{
Termios attr; /* The terminal attributes */
int waserr = 0; /* True after any error */
/*
* Re-enable conversion of newline characters to carriage-return/linefeed,
* so that the callback can write to the terminal without having to do
* anything special.
*/
if(tcgetattr(gl->input_fd, &attr)) {
_err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
return 1;
};
attr.c_oflag |= OPOST;
while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
return 1;
};
};
/*
* Invoke the application's callback function.
*/
switch(gfh->fn(gl, gfh->data, fd, event)) {
default:
case GLFD_ABORT:
gl_record_status(gl, GLR_FDABORT, 0);
waserr = 1;
break;
case GLFD_REFRESH:
gl_queue_redisplay(gl);
break;
case GLFD_CONTINUE:
break;
};
/*
* Disable conversion of newline characters to carriage-return/linefeed.
*/
attr.c_oflag &= ~(OPOST);
while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
return 1;
};
};
return waserr;
}
/*.......................................................................
* This is a private function of gl_event_handler(), used to call a
* inactivity timer callbacks.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_call_timeout_handler(GetLine *gl)
{
Termios attr; /* The terminal attributes */
int waserr = 0; /* True after any error */
/*
* Make sure that there is an inactivity timeout callback.
*/
if(!gl->timer.fn)
return 0;
/*
* Re-enable conversion of newline characters to carriage-return/linefeed,
* so that the callback can write to the terminal without having to do
* anything special.
*/
if(tcgetattr(gl->input_fd, &attr)) {
_err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
return 1;
};
attr.c_oflag |= OPOST;
while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
return 1;
};
};
/*
* Invoke the application's callback function.
*/
switch(gl->timer.fn(gl, gl->timer.data)) {
default:
case GLTO_ABORT:
gl_record_status(gl, GLR_TIMEOUT, 0);
waserr = 1;
break;
case GLTO_REFRESH:
gl_queue_redisplay(gl);
break;
case GLTO_CONTINUE:
break;
};
/*
* Disable conversion of newline characters to carriage-return/linefeed.
*/
attr.c_oflag &= ~(OPOST);
while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
if(errno != EINTR) {
_err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
return 1;
};
};
return waserr;
}
#endif /* HAVE_SELECT */
/*.......................................................................
* Switch history groups. History groups represent separate history
* lists recorded within a single history buffer. Different groups
* are distinguished by integer identifiers chosen by the calling
* appplicaton. Initially new_GetLine() sets the group identifier to
* 0. Whenever a new line is appended to the history list, the current
* group identifier is recorded with it, and history lookups only
* consider lines marked with the current group identifier.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* id unsigned The new history group identifier.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_group_history(GetLine *gl, unsigned id)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of this function */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals while we install the new configuration.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* If the group isn't being changed, do nothing.
*/
if(_glh_get_group(gl->glh) == id) {
status = 0;
/*
* Establish the new group.
*/
} else if(_glh_set_group(gl->glh, id)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
status = 1;
/*
* Prevent history information from the previous group being
* inappropriately used by the next call to gl_get_line().
*/
} else {
gl->preload_history = 0;
gl->last_search = -1;
status = 0;
};
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* Display the contents of the history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* fp FILE * The stdio output stream to write to.
* fmt const char * A format string. This containing characters to be
* written verbatim, plus any of the following
* format directives:
* %D - The date, formatted like 2001-11-20
* %T - The time of day, formatted like 23:59:59
* %N - The sequential entry number of the
* line in the history buffer.
* %G - The number of the history group that
* the line belongs to.
* %% - A literal % character.
* %H - The history line itself.
* Note that a '\n' newline character is not
* appended by default.
* all_groups int If true, display history lines from all
* history groups. Otherwise only display
* those of the current history group.
* max_lines int If max_lines is < 0, all available lines
* are displayed. Otherwise only the most
* recent max_lines lines will be displayed.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_show_history(GetLine *gl, FILE *fp, const char *fmt, int all_groups,
int max_lines)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of this function */
/*
* Check the arguments.
*/
if(!gl || !fp || !fmt) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Display the specified history group(s) while signals are blocked.
*/
status = _glh_show_history(gl->glh, _io_write_stdio, fp, fmt, all_groups,
max_lines) || fflush(fp)==EOF;
if(!status)
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* Update if necessary, and return the current size of the terminal.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* def_ncolumn int If the number of columns in the terminal
* can't be determined, substitute this number.
* def_nline int If the number of lines in the terminal can't
* be determined, substitute this number.
* Output:
* return GlTerminalSize The current terminal size.
*/
GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline)
{
GlTerminalSize size; /* The object to be returned */
sigset_t oldset; /* The signals that were blocked on entry */
/* to this function */
/*
* Block all signals while accessing gl.
*/
gl_mask_signals(gl, &oldset);
/*
* Lookup/configure the terminal size.
*/
_gl_terminal_size(gl, def_ncolumn, def_nline, &size);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return size;
}
/*.......................................................................
* This is the private body of the gl_terminal_size() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static void _gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline,
GlTerminalSize *size)
{
const char *env; /* The value of an environment variable */
int n; /* A number read from env[] */
/*
* Set the number of lines and columns to non-sensical values so that
* we know later if they have been set.
*/
gl->nline = 0;
gl->ncolumn = 0;
/*
* Are we reading from a terminal?
*/
if(gl->is_term) {
/*
* Ask the terminal directly if possible.
*/
(void) _gl_update_size(gl);
/*
* If gl_update_size() couldn't ask the terminal, it will have
* left gl->nrow and gl->ncolumn unchanged. If these values haven't
* been changed from their initial values of zero, we need to find
* a different method to get the terminal size.
*
* If the number of lines isn't known yet, first see if the
* LINES environment ariable exists and specifies a believable number.
* If this doesn't work, look up the default size in the terminal
* information database.
*/
if(gl->nline < 1) {
if((env = getenv("LINES")) && (n=atoi(env)) > 0)
gl->nline = n;
#ifdef USE_TERMINFO
else
gl->nline = tigetnum((char *)"lines");
#elif defined(USE_TERMCAP)
else
gl->nline = tgetnum("li");
#endif
};
/*
* If the number of lines isn't known yet, first see if the COLUMNS
* environment ariable exists and specifies a believable number. If
* this doesn't work, look up the default size in the terminal
* information database.
*/
if(gl->ncolumn < 1) {
if((env = getenv("COLUMNS")) && (n=atoi(env)) > 0)
gl->ncolumn = n;
#ifdef USE_TERMINFO
else
gl->ncolumn = tigetnum((char *)"cols");
#elif defined(USE_TERMCAP)
else
gl->ncolumn = tgetnum("co");
#endif
};
};
/*
* If we still haven't been able to acquire reasonable values, substitute
* the default values specified by the caller.
*/
if(gl->nline <= 0)
gl->nline = def_nline;
if(gl->ncolumn <= 0)
gl->ncolumn = def_ncolumn;
/*
* Copy the new size into the return value.
*/
if(size) {
size->nline = gl->nline;
size->ncolumn = gl->ncolumn;
};
return;
}
/*.......................................................................
* Resize or delete the history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* bufsize size_t The number of bytes in the history buffer, or 0
* to delete the buffer completely.
* Output:
* return int 0 - OK.
* 1 - Insufficient memory (the previous buffer
* will have been retained). No error message
* will be displayed.
*/
int gl_resize_history(GetLine *gl, size_t bufsize)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of this function */
/*
* Check the arguments.
*/
if(!gl)
return 1;
/*
* Block all signals while modifying the contents of gl.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Perform the resize while signals are blocked.
*/
status = _glh_resize_history(gl->glh, bufsize);
if(status)
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* Set an upper limit to the number of lines that can be recorded in the
* history list, or remove a previously specified limit.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* max_lines int The maximum number of lines to allow, or -1 to
* cancel a previous limit and allow as many lines
* as will fit in the current history buffer size.
*/
void gl_limit_history(GetLine *gl, int max_lines)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Apply the limit while signals are blocked.
*/
_glh_limit_history(gl->glh, max_lines);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Discard either all historical lines, or just those associated with the
* current history group.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* all_groups int If true, clear all of the history. If false,
* clear only the stored lines associated with the
* currently selected history group.
*/
void gl_clear_history(GetLine *gl, int all_groups)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Clear the history buffer while signals are blocked.
*/
_glh_clear_history(gl->glh, all_groups);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Temporarily enable or disable the gl_get_line() history mechanism.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* enable int If true, turn on the history mechanism. If
* false, disable it.
*/
void gl_toggle_history(GetLine *gl, int enable)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Change the history recording mode while signals are blocked.
*/
_glh_toggle_history(gl->glh, enable);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Lookup a history line by its sequential number of entry in the
* history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* id unsigned long The identification number of the line to
* be returned, where 0 denotes the first line
* that was entered in the history list, and
* each subsequently added line has a number
* one greater than the previous one. For
* the range of lines currently in the list,
* see the gl_range_of_history() function.
* Input/Output:
* line GlHistoryLine * A pointer to the variable in which to
* return the details of the line.
* Output:
* return int 0 - The line is no longer in the history
* list, and *line has not been changed.
* 1 - The requested line can be found in
* *line. Note that line->line is part
* of the history buffer, so a
* private copy should be made if you
* wish to use it after subsequent calls
* to any functions that take *gl as an
* argument.
*/
int gl_lookup_history(GetLine *gl, unsigned long id, GlHistoryLine *line)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of this function */
/*
* Check the arguments.
*/
if(!gl)
return 0;
/*
* Block all signals while modifying the contents of gl.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Perform the lookup while signals are blocked.
*/
status = _glh_lookup_history(gl->glh, (GlhLineID) id, &line->line,
&line->group, &line->timestamp);
if(status)
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* Query the state of the history list. Note that any of the input/output
* pointers can be specified as NULL.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* state GlHistoryState * A pointer to the variable in which to record
* the return values.
*/
void gl_state_of_history(GetLine *gl, GlHistoryState *state)
{
if(gl && state) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Lookup the status while signals are blocked.
*/
_glh_state_of_history(gl->glh, &state->enabled, &state->group,
&state->max_lines);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Query the number and range of lines in the history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* range GlHistoryRange * A pointer to the variable in which to record
* the return values. If range->nline=0, the
* range of lines will be given as 0-0.
*/
void gl_range_of_history(GetLine *gl, GlHistoryRange *range)
{
if(gl && range) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Lookup the information while signals are blocked.
*/
_glh_range_of_history(gl->glh, &range->oldest, &range->newest,
&range->nlines);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Return the size of the history buffer and the amount of the
* buffer that is currently in use.
*
* Input:
* gl GetLine * The gl_get_line() resource object.
* Input/Output:
* GlHistorySize size * A pointer to the variable in which to return
* the results.
*/
void gl_size_of_history(GetLine *gl, GlHistorySize *size)
{
if(gl && size) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Lookup the information while signals are blocked.
*/
_glh_size_of_history(gl->glh, &size->size, &size->used);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* This is the action function that lists the contents of the history
* list.
*/
static KT_KEY_FN(gl_list_history)
{
/*
* Start a new line.
*/
if(gl_start_newline(gl, 1))
return 1;
/*
* List history lines that belong to the current group.
*/
_glh_show_history(gl->glh, gl_write_fn, gl, "%N %T %H\r\n", 0,
count<=1 ? -1 : count);
/*
* Arrange for the input line to be redisplayed.
*/
gl_queue_redisplay(gl);
return 0;
}
/*.......................................................................
* Specify whether text that users type should be displayed or hidden.
* In the latter case, only the prompt is displayed, and the final
* input line is not archived in the history list.
*
* Input:
* gl GetLine * The gl_get_line() resource object.
* enable int 0 - Disable echoing.
* 1 - Enable echoing.
* -1 - Just query the mode without changing it.
* Output:
* return int The echoing disposition that was in effect
* before this function was called:
* 0 - Echoing was disabled.
* 1 - Echoing was enabled.
*/
int gl_echo_mode(GetLine *gl, int enable)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
int was_echoing; /* The echoing disposition on entry to this function */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Install the new disposition while signals are blocked.
*/
was_echoing = gl->echo;
if(enable >= 0)
gl->echo = enable;
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
/*
* Return the original echoing disposition.
*/
return was_echoing;
};
return 1;
}
/*.......................................................................
* Display the prompt.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_display_prompt(GetLine *gl)
{
const char *pptr; /* A pointer into gl->prompt[] */
unsigned old_attr=0; /* The current text display attributes */
unsigned new_attr=0; /* The requested text display attributes */
/*
* Temporarily switch to echoing output characters.
*/
int kept_echo = gl->echo;
gl->echo = 1;
/*
* In case the screen got messed up, send a carriage return to
* put the cursor at the beginning of the current terminal line.
*/
if(gl_print_control_sequence(gl, 1, gl->bol))
return 1;
/*
* Mark the line as partially displayed.
*/
gl->displayed = 1;
/*
* Write the prompt, using the currently selected prompt style.
*/
switch(gl->prompt_style) {
case GL_LITERAL_PROMPT:
if(gl_print_string(gl, gl->prompt, '\0'))
return 1;
break;
case GL_FORMAT_PROMPT:
for(pptr=gl->prompt; *pptr; pptr++) {
/*
* Does the latest character appear to be the start of a directive?
*/
if(*pptr == '%') {
/*
* Check for and act on attribute changing directives.
*/
switch(pptr[1]) {
/*
* Add or remove a text attribute from the new set of attributes.
*/
case 'B': case 'U': case 'S': case 'P': case 'F': case 'V':
case 'b': case 'u': case 's': case 'p': case 'f': case 'v':
switch(*++pptr) {
case 'B': /* Switch to a bold font */
new_attr |= GL_TXT_BOLD;
break;
case 'b': /* Switch to a non-bold font */
new_attr &= ~GL_TXT_BOLD;
break;
case 'U': /* Start underlining */
new_attr |= GL_TXT_UNDERLINE;
break;
case 'u': /* Stop underlining */
new_attr &= ~GL_TXT_UNDERLINE;
break;
case 'S': /* Start highlighting */
new_attr |= GL_TXT_STANDOUT;
break;
case 's': /* Stop highlighting */
new_attr &= ~GL_TXT_STANDOUT;
break;
case 'P': /* Switch to a pale font */
new_attr |= GL_TXT_DIM;
break;
case 'p': /* Switch to a non-pale font */
new_attr &= ~GL_TXT_DIM;
break;
case 'F': /* Switch to a flashing font */
new_attr |= GL_TXT_BLINK;
break;
case 'f': /* Switch to a steady font */
new_attr &= ~GL_TXT_BLINK;
break;
case 'V': /* Switch to reverse video */
new_attr |= GL_TXT_REVERSE;
break;
case 'v': /* Switch out of reverse video */
new_attr &= ~GL_TXT_REVERSE;
break;
};
continue;
/*
* A literal % is represented by %%. Skip the leading %.
*/
case '%':
pptr++;
break;
};
};
/*
* Many terminals, when asked to turn off a single text attribute, turn
* them all off, so the portable way to turn one off individually is to
* explicitly turn them all off, then specify those that we want from
* scratch.
*/
if(old_attr & ~new_attr) {
if(gl_print_control_sequence(gl, 1, gl->text_attr_off))
return 1;
old_attr = 0;
};
/*
* Install new text attributes?
*/
if(new_attr != old_attr) {
if(new_attr & GL_TXT_BOLD && !(old_attr & GL_TXT_BOLD) &&
gl_print_control_sequence(gl, 1, gl->bold))
return 1;
if(new_attr & GL_TXT_UNDERLINE && !(old_attr & GL_TXT_UNDERLINE) &&
gl_print_control_sequence(gl, 1, gl->underline))
return 1;
if(new_attr & GL_TXT_STANDOUT && !(old_attr & GL_TXT_STANDOUT) &&
gl_print_control_sequence(gl, 1, gl->standout))
return 1;
if(new_attr & GL_TXT_DIM && !(old_attr & GL_TXT_DIM) &&
gl_print_control_sequence(gl, 1, gl->dim))
return 1;
if(new_attr & GL_TXT_REVERSE && !(old_attr & GL_TXT_REVERSE) &&
gl_print_control_sequence(gl, 1, gl->reverse))
return 1;
if(new_attr & GL_TXT_BLINK && !(old_attr & GL_TXT_BLINK) &&
gl_print_control_sequence(gl, 1, gl->blink))
return 1;
old_attr = new_attr;
};
/*
* Display the latest character.
*/
if(gl_print_char(gl, *pptr, pptr[1]))
return 1;
};
/*
* Turn off all text attributes now that we have finished drawing
* the prompt.
*/
if(gl_print_control_sequence(gl, 1, gl->text_attr_off))
return 1;
break;
};
/*
* Restore the original echo mode.
*/
gl->echo = kept_echo;
/*
* The prompt has now been displayed at least once.
*/
gl->prompt_changed = 0;
return 0;
}
/*.......................................................................
* This function can be called from gl_get_line() callbacks to have
* the prompt changed when they return. It has no effect if gl_get_line()
* is not currently being invoked.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* prompt const char * The new prompt.
*/
void gl_replace_prompt(GetLine *gl, const char *prompt)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Replace the prompt.
*/
_gl_replace_prompt(gl, prompt);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* This is the private body of the gl_replace_prompt() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static void _gl_replace_prompt(GetLine *gl, const char *prompt)
{
size_t size;
/*
* Substitute an empty prompt?
*/
if(!prompt)
prompt = "";
/*
* Gaurd against aliasing between prompt and gl->prompt.
*/
if(gl->prompt != prompt) {
/*
* Get the length of the new prompt string.
*/
size_t slen = strlen(prompt);
/*
* If needed, allocate a new buffer for the prompt string.
*/
size = sizeof(char) * (slen + 1);
if(!gl->prompt || slen > strlen(gl->prompt)) {
char *new_prompt = gl->prompt ? realloc(gl->prompt, size) : malloc(size);
if(!new_prompt)
return;
gl->prompt = new_prompt;
};
/*
* Make a copy of the new prompt.
*/
strlcpy(gl->prompt, prompt, size);
};
/*
* Record the statistics of the new prompt.
*/
gl->prompt_len = gl_displayed_prompt_width(gl);
gl->prompt_changed = 1;
gl_queue_redisplay(gl);
return;
}
/*.......................................................................
* Work out the length of the current prompt on the terminal, according
* to the current prompt formatting style.
*
* Input:
* gl GetLine * The resource object of this library.
* Output:
* return int The number of displayed characters.
*/
static int gl_displayed_prompt_width(GetLine *gl)
{
int slen=0; /* The displayed number of characters */
const char *pptr; /* A pointer into prompt[] */
/*
* The length differs according to the prompt display style.
*/
switch(gl->prompt_style) {
case GL_LITERAL_PROMPT:
return gl_displayed_string_width(gl, gl->prompt, -1, 0);
break;
case GL_FORMAT_PROMPT:
/*
* Add up the length of the displayed string, while filtering out
* attribute directives.
*/
for(pptr=gl->prompt; *pptr; pptr++) {
/*
* Does the latest character appear to be the start of a directive?
*/
if(*pptr == '%') {
/*
* Check for and skip attribute changing directives.
*/
switch(pptr[1]) {
case 'B': case 'b': case 'U': case 'u': case 'S': case 's':
pptr++;
continue;
/*
* A literal % is represented by %%. Skip the leading %.
*/
case '%':
pptr++;
break;
};
};
slen += gl_displayed_char_width(gl, *pptr, slen);
};
break;
};
return slen;
}
/*.......................................................................
* Specify whether to heed text attribute directives within prompt
* strings.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* style GlPromptStyle The style of prompt (see the definition of
* GlPromptStyle in libtecla.h for details).
*/
void gl_prompt_style(GetLine *gl, GlPromptStyle style)
{
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Install the new style in gl while signals are blocked.
*/
if(style != gl->prompt_style) {
gl->prompt_style = style;
gl->prompt_len = gl_displayed_prompt_width(gl);
gl->prompt_changed = 1;
gl_queue_redisplay(gl);
};
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
}
/*.......................................................................
* Tell gl_get_line() how to respond to a given signal. This can be used
* both to override the default responses to signals that gl_get_line()
* normally catches and to add new signals to the list that are to be
* caught.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* signo int The number of the signal to be caught.
* flags unsigned A bitwise union of GlSignalFlags enumerators.
* after GlAfterSignal What to do after the application's signal
* handler has been called.
* errno_value int The value to set errno to.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
GlAfterSignal after, int errno_value)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of this function */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals while modifying the contents of gl.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Perform the modification while signals are blocked.
*/
status = _gl_trap_signal(gl, signo, flags, after, errno_value);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_trap_signal() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_trap_signal(GetLine *gl, int signo, unsigned flags,
GlAfterSignal after, int errno_value)
{
GlSignalNode *sig;
/*
* Complain if an attempt is made to trap untrappable signals.
* These would otherwise cause errors later in gl_mask_signals().
*/
if(0
#ifdef SIGKILL
|| signo==SIGKILL
#endif
#ifdef SIGBLOCK
|| signo==SIGBLOCK
#endif
) {
return 1;
};
/*
* See if the signal has already been registered.
*/
for(sig=gl->sigs; sig && sig->signo != signo; sig = sig->next)
;
/*
* If the signal hasn't already been registered, allocate a node for
* it.
*/
if(!sig) {
sig = (GlSignalNode *) _new_FreeListNode(gl->sig_mem);
if(!sig)
return 1;
/*
* Add the new node to the head of the list.
*/
sig->next = gl->sigs;
gl->sigs = sig;
/*
* Record the signal number.
*/
sig->signo = signo;
/*
* Create a signal set that includes just this signal.
*/
sigemptyset(&sig->proc_mask);
if(sigaddset(&sig->proc_mask, signo) == -1) {
_err_record_msg(gl->err, "sigaddset error", END_ERR_MSG);
sig = (GlSignalNode *) _del_FreeListNode(gl->sig_mem, sig);
return 1;
};
/*
* Add the signal to the bit-mask of signals being trapped.
*/
sigaddset(&gl->all_signal_set, signo);
};
/*
* Record the new signal attributes.
*/
sig->flags = flags;
sig->after = after;
sig->errno_value = errno_value;
return 0;
}
/*.......................................................................
* Remove a signal from the list of signals that gl_get_line() traps.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* signo int The number of the signal to be ignored.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_ignore_signal(GetLine *gl, int signo)
{
GlSignalNode *sig; /* The gl->sigs list node of the specified signal */
GlSignalNode *prev; /* The node that precedes sig in the list */
sigset_t oldset; /* The signals that were blocked on entry to this */
/* function. */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals while modifying the contents of gl.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Find the node of the gl->sigs list which records the disposition
* of the specified signal.
*/
for(prev=NULL,sig=gl->sigs; sig && sig->signo != signo;
prev=sig,sig=sig->next)
;
if(sig) {
/*
* Remove the node from the list.
*/
if(prev)
prev->next = sig->next;
else
gl->sigs = sig->next;
/*
* Return the node to the freelist.
*/
sig = (GlSignalNode *) _del_FreeListNode(gl->sig_mem, sig);
/*
* Remove the signal from the bit-mask union of signals being trapped.
*/
sigdelset(&gl->all_signal_set, signo);
};
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return 0;
}
/*.......................................................................
* This function is called when an input line has been completed. It
* appends the specified newline character, terminates the line,
* records the line in the history buffer if appropriate, and positions
* the terminal cursor at the start of the next line.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* newline_char int The newline character to add to the end
* of the line.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_line_ended(GetLine *gl, int newline_char)
{
/*
* If the newline character is printable, display it at the end of
* the line, and add it to the input line buffer.
*/
if(isprint((int)(unsigned char) newline_char)) {
if(gl_end_of_line(gl, 1, NULL) || gl_add_char_to_line(gl, newline_char))
return 1;
} else {
/*
* Otherwise just append a newline character to the input line buffer.
*/
newline_char = '\n';
gl_buffer_char(gl, newline_char, gl->ntotal);
};
/*
* Add the line to the history buffer if it was entered with a
* newline character.
*/
if(gl->echo && gl->automatic_history && newline_char=='\n')
(void) _gl_append_history(gl, gl->line);
/*
* Except when depending on the system-provided line editing, start a new
* line after the end of the line that has just been entered.
*/
if(gl->editor != GL_NO_EDITOR && gl_start_newline(gl, 1))
return 1;
/*
* Record the successful return status.
*/
gl_record_status(gl, GLR_NEWLINE, 0);
/*
* Attempt to flush any pending output.
*/
(void) gl_flush_output(gl);
/*
* The next call to gl_get_line() will write the prompt for a new line
* (or continue the above flush if incomplete), so if we manage to
* flush the terminal now, report that we are waiting to write to the
* terminal.
*/
gl->pending_io = GLP_WRITE;
return 0;
}
/*.......................................................................
* Return the last signal that was caught by the most recent call to
* gl_get_line(), or -1 if no signals were caught. This is useful if
* gl_get_line() returns errno=EINTR and you need to find out what signal
* caused it to abort.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int The last signal caught by the most recent
* call to gl_get_line(), or -1 if no signals
* were caught.
*/
int gl_last_signal(GetLine *gl)
{
int signo = -1; /* The requested signal number */
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Access gl now that signals are blocked.
*/
signo = gl->last_signal;
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
return signo;
}
/*.......................................................................
* Prepare to edit a new line.
*
* Input:
* gl GetLine * The resource object of this library.
* prompt char * The prompt to prefix the line with, or NULL to
* use the same prompt that was used by the previous
* line.
* start_line char * The initial contents of the input line, or NULL
* if it should start out empty.
* start_pos int If start_line isn't NULL, this specifies the
* index of the character over which the cursor
* should initially be positioned within the line.
* If you just want it to follow the last character
* of the line, send -1.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_present_line(GetLine *gl, const char *prompt,
const char *start_line, int start_pos)
{
/*
* Reset the properties of the line.
*/
gl_reset_input_line(gl);
/*
* Record the new prompt and its displayed width.
*/
if(prompt)
_gl_replace_prompt(gl, prompt);
/*
* Reset the history search pointers.
*/
if(_glh_cancel_search(gl->glh)) {
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return 1;
};
/*
* If the previous line was entered via the repeat-history action,
* preload the specified history line.
*/
if(gl->preload_history) {
gl->preload_history = 0;
if(gl->preload_id) {
if(_glh_recall_line(gl->glh, gl->preload_id, gl->line, gl->linelen+1)) {
gl_update_buffer(gl); /* Compute gl->ntotal etc.. */
gl->buff_curpos = gl->ntotal;
} else {
gl_truncate_buffer(gl, 0);
};
gl->preload_id = 0;
};
/*
* Present a specified initial line?
*/
} else if(start_line) {
char *cptr; /* A pointer into gl->line[] */
/*
* Measure the length of the starting line.
*/
int start_len = strlen(start_line);
/*
* If the length of the line is greater than the available space,
* truncate it.
*/
if(start_len > gl->linelen)
start_len = gl->linelen;
/*
* Load the line into the buffer.
*/
if(start_line != gl->line)
gl_buffer_string(gl, start_line, start_len, 0);
/*
* Strip off any trailing newline and carriage return characters.
*/
for(cptr=gl->line + gl->ntotal - 1; cptr >= gl->line &&
(*cptr=='\n' || *cptr=='\r'); cptr--,gl->ntotal--)
;
gl_truncate_buffer(gl, gl->ntotal < 0 ? 0 : gl->ntotal);
/*
* Where should the cursor be placed within the line?
*/
if(start_pos < 0 || start_pos > gl->ntotal) {
if(gl_place_cursor(gl, gl->ntotal))
return 1;
} else {
if(gl_place_cursor(gl, start_pos))
return 1;
};
/*
* Clear the input line?
*/
} else {
gl_truncate_buffer(gl, 0);
};
/*
* Arrange for the line to be displayed by gl_flush_output().
*/
gl_queue_redisplay(gl);
/*
* Update the display.
*/
return gl_flush_output(gl);
}
/*.......................................................................
* Reset all line input parameters for a new input line.
*
* Input:
* gl GetLine * The line editor resource object.
*/
static void gl_reset_input_line(GetLine *gl)
{
gl->ntotal = 0;
gl->line[0] = '\0';
gl->buff_curpos = 0;
gl->term_curpos = 0;
gl->term_len = 0;
gl->insert_curpos = 0;
gl->number = -1;
gl->displayed = 0;
gl->endline = 0;
gl->redisplay = 0;
gl->postpone = 0;
gl->nbuf = 0;
gl->nread = 0;
gl->vi.command = 0;
gl->vi.undo.line[0] = '\0';
gl->vi.undo.ntotal = 0;
gl->vi.undo.buff_curpos = 0;
gl->vi.repeat.action.fn = 0;
gl->vi.repeat.action.data = 0;
gl->last_signal = -1;
}
/*.......................................................................
* Print an informational message to the terminal, after starting a new
* line.
*
* Input:
* gl GetLine * The line editor resource object.
* ... const char * Zero or more strings to be printed.
* ... void * The last argument must always be GL_END_INFO.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_print_info(GetLine *gl, ...)
{
va_list ap; /* The variable argument list */
const char *s; /* The string being printed */
int waserr = 0; /* True after an error */
/*
* Only display output when echoing is on.
*/
if(gl->echo) {
/*
* Skip to the start of the next empty line before displaying the message.
*/
if(gl_start_newline(gl, 1))
return 1;
/*
* Display the list of provided messages.
*/
va_start(ap, gl);
while(!waserr && (s = va_arg(ap, const char *)) != GL_END_INFO)
waserr = gl_print_raw_string(gl, 1, s, -1);
va_end(ap);
/*
* Start a newline.
*/
waserr = waserr || gl_print_raw_string(gl, 1, "\n\r", -1);
/*
* Arrange for the input line to be redrawn.
*/
gl_queue_redisplay(gl);
};
return waserr;
}
/*.......................................................................
* Go to the start of the next empty line, ready to output miscellaneous
* text to the screen.
*
* Note that when async-signal safety is required, the 'buffered'
* argument must be 0.
*
* Input:
* gl GetLine * The line editor resource object.
* buffered int If true, used buffered I/O when writing to
* the terminal. Otherwise use async-signal-safe
* unbuffered I/O.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_start_newline(GetLine *gl, int buffered)
{
int waserr = 0; /* True after any I/O error */
/*
* Move the cursor to the start of the terminal line that follows the
* last line of the partially enterred line. In order that this
* function remain async-signal safe when write_fn is signal safe, we
* can't call our normal output functions, since they call tputs(),
* who's signal saftey isn't defined. Fortunately, we can simply use
* \r and \n to move the cursor to the right place.
*/
if(gl->displayed) { /* Is an input line currently displayed? */
/*
* On which terminal lines are the cursor and the last character of the
* input line?
*/
int curs_line = gl->term_curpos / gl->ncolumn;
int last_line = gl->term_len / gl->ncolumn;
/*
* Move the cursor to the start of the line that follows the last
* terminal line that is occupied by the input line.
*/
for( ; curs_line < last_line + 1; curs_line++)
waserr = waserr || gl_print_raw_string(gl, buffered, "\n", 1);
waserr = waserr || gl_print_raw_string(gl, buffered, "\r", 1);
/*
* Mark the line as no longer displayed.
*/
gl_line_erased(gl);
};
return waserr;
}
/*.......................................................................
* The callback through which all terminal output is routed.
* This simply appends characters to a queue buffer, which is
* subsequently flushed to the output channel by gl_flush_output().
*
* Input:
* data void * The pointer to a GetLine line editor resource object
* cast to (void *).
* s const char * The string to be written.
* n int The number of characters to write from s[].
* Output:
* return int The number of characters written. This will always
* be equal to 'n' unless an error occurs.
*/
static GL_WRITE_FN(gl_write_fn)
{
GetLine *gl = (GetLine *) data;
int ndone = _glq_append_chars(gl->cq, s, n, gl->flush_fn, gl);
if(ndone != n)
_err_record_msg(gl->err, _glq_last_error(gl->cq), END_ERR_MSG);
return ndone;
}
/*.......................................................................
* Ask gl_get_line() what caused it to return.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return GlReturnStatus The return status of the last call to
* gl_get_line().
*/
GlReturnStatus gl_return_status(GetLine *gl)
{
GlReturnStatus rtn_status = GLR_ERROR; /* The requested status */
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Access gl while signals are blocked.
*/
rtn_status = gl->rtn_status;
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
return rtn_status;
}
/*.......................................................................
* In non-blocking server-I/O mode, this function should be called
* from the application's external event loop to see what type of
* terminal I/O is being waited for by gl_get_line(), and thus what
* direction of I/O to wait for with select() or poll().
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return GlPendingIO The type of pending I/O being waited for.
*/
GlPendingIO gl_pending_io(GetLine *gl)
{
GlPendingIO pending_io = GLP_WRITE; /* The requested information */
if(gl) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Access gl while signals are blocked.
*/
pending_io = gl->pending_io;
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
};
return pending_io;
}
/*.......................................................................
* In server mode, this function configures the terminal for non-blocking
* raw terminal I/O. In normal I/O mode it does nothing.
*
* Callers of this function must be careful to trap all signals that
* terminate or suspend the program, and call gl_normal_io()
* from the corresponding signal handlers in order to restore the
* terminal to its original settings before the program is terminated
* or suspended. They should also trap the SIGCONT signal to detect
* when the program resumes, and ensure that its signal handler
* call gl_raw_io() to redisplay the line and resume editing.
*
* This function is async signal safe.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_raw_io(GetLine *gl)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_raw_io() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Don't allow applications to switch into raw mode unless in server mode.
*/
if(gl->io_mode != GL_SERVER_MODE) {
_err_record_msg(gl->err, "Can't switch to raw I/O unless in server mode",
END_ERR_MSG);
errno = EPERM;
status = 1;
} else {
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_raw_io(gl, 1);
};
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_raw_io().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*
* This function is async signal safe.
*/
static int _gl_raw_io(GetLine *gl, int redisplay)
{
/*
* If we are already in the correct mode, do nothing.
*/
if(gl->raw_mode)
return 0;
/*
* Switch the terminal to raw mode.
*/
if(gl->is_term && gl_raw_terminal_mode(gl))
return 1;
/*
* Switch to non-blocking I/O mode?
*/
if(gl->io_mode==GL_SERVER_MODE &&
(gl_nonblocking_io(gl, gl->input_fd) ||
gl_nonblocking_io(gl, gl->output_fd) ||
(gl->file_fp && gl_nonblocking_io(gl, fileno(gl->file_fp))))) {
if(gl->is_term)
gl_restore_terminal_attributes(gl);
return 1;
};
/*
* If an input line is being entered, arrange for it to be
* displayed.
*/
if(redisplay) {
gl->postpone = 0;
gl_queue_redisplay(gl);
};
return 0;
}
/*.......................................................................
* Restore the terminal to the state that it had when
* gl_raw_io() was last called. After calling
* gl_raw_io(), this function must be called before
* terminating or suspending the program, and before attempting other
* uses of the terminal from within the program. See gl_raw_io()
* for more details.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_normal_io(GetLine *gl)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_normal_io() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_normal_io(gl);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_normal_io().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_normal_io(GetLine *gl)
{
/*
* If we are already in normal mode, do nothing.
*/
if(!gl->raw_mode)
return 0;
/*
* Postpone subsequent redisplays until after _gl_raw_io(gl, 1)
* is next called.
*/
gl->postpone = 1;
/*
* Switch back to blocking I/O. Note that this is essential to do
* here, because when using non-blocking I/O, the terminal output
* buffering code can't always make room for new output without calling
* malloc(), and a call to malloc() would mean that this function
* couldn't safely be called from signal handlers.
*/
if(gl->io_mode==GL_SERVER_MODE &&
(gl_blocking_io(gl, gl->input_fd) ||
gl_blocking_io(gl, gl->output_fd) ||
(gl->file_fp && gl_blocking_io(gl, fileno(gl->file_fp)))))
return 1;
/*
* Move the cursor to the next empty terminal line. Note that
* unbuffered I/O is requested, to ensure that gl_start_newline() be
* async-signal-safe.
*/
if(gl->is_term && gl_start_newline(gl, 0))
return 1;
/*
* Switch the terminal to normal mode.
*/
if(gl->is_term && gl_restore_terminal_attributes(gl)) {
/*
* On error, revert to non-blocking I/O if needed, so that on failure
* we remain in raw mode.
*/
if(gl->io_mode==GL_SERVER_MODE) {
gl_nonblocking_io(gl, gl->input_fd);
gl_nonblocking_io(gl, gl->output_fd);
if(gl->file_fp)
gl_nonblocking_io(gl, fileno(gl->file_fp));
};
return 1;
};
return 0;
}
/*.......................................................................
* This function allows you to install an additional completion
* action, or to change the completion function of an existing
* one. This should be called before the first call to gl_get_line()
* so that the name of the action be defined before the user's
* configuration file is read.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * This is passed to match_fn() whenever it is
* called. It could, for example, point to a
* symbol table that match_fn() would look up
* matches in.
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* report matching symbols.
* list_only int If non-zero, install an action that only lists
* possible completions, rather than attempting
* to perform the completion.
* name const char * The name with which users can refer to the
* binding in tecla configuration files.
* keyseq const char * Either NULL, or a key sequence with which
* to invoke the binding. This should be
* specified in the same manner as key-sequences
* in tecla configuration files (eg. "M-^I").
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
int list_only, const char *name, const char *keyseq)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_completion_action() */
/*
* Check the arguments.
*/
if(!gl || !name || !match_fn) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Install the new action while signals are blocked.
*/
status = _gl_completion_action(gl, data, match_fn, list_only, name, keyseq);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_completion_action().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
int list_only, const char *name,
const char *keyseq)
{
KtKeyFn *current_fn; /* An existing action function */
void *current_data; /* The action-function callback data */
/*
* Which action function is desired?
*/
KtKeyFn *action_fn = list_only ? gl_list_completions : gl_complete_word;
/*
* Is there already an action of the specified name?
*/
if(_kt_lookup_action(gl->bindings, name, ¤t_fn, ¤t_data) == 0) {
/*
* If the action has the same type as the one being requested,
* simply change the contents of its GlCplCallback callback data.
*/
if(current_fn == action_fn) {
GlCplCallback *cb = (GlCplCallback *) current_data;
cb->fn = match_fn;
cb->data = data;
} else {
errno = EINVAL;
_err_record_msg(gl->err,
"Illegal attempt to change the type of an existing completion action",
END_ERR_MSG);
return 1;
};
/*
* No existing action has the specified name.
*/
} else {
/*
* Allocate a new GlCplCallback callback object.
*/
GlCplCallback *cb = (GlCplCallback *) _new_FreeListNode(gl->cpl_mem);
if(!cb) {
errno = ENOMEM;
_err_record_msg(gl->err, "Insufficient memory to add completion action",
END_ERR_MSG);
return 1;
};
/*
* Record the completion callback data.
*/
cb->fn = match_fn;
cb->data = data;
/*
* Attempt to register the new action.
*/
if(_kt_set_action(gl->bindings, name, action_fn, cb)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
_del_FreeListNode(gl->cpl_mem, (void *) cb);
return 1;
};
};
/*
* Bind the action to a given key-sequence?
*/
if(keyseq && _kt_set_keybinding(gl->bindings, KTB_NORM, keyseq, name)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Register an application-provided function as an action function.
* This should preferably be called before the first call to gl_get_line()
* so that the name of the action becomes defined before the user's
* configuration file is read.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * Arbitrary application-specific callback
* data to be passed to the callback
* function, fn().
* fn GlActionFn * The application-specific function that
* implements the action. This will be invoked
* whenever the user presses any
* key-sequence which is bound to this action.
* name const char * The name with which users can refer to the
* binding in tecla configuration files.
* keyseq const char * The key sequence with which to invoke
* the binding. This should be specified in the
* same manner as key-sequences in tecla
* configuration files (eg. "M-^I").
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
const char *name, const char *keyseq)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_register_action() */
/*
* Check the arguments.
*/
if(!gl || !name || !fn) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Install the new action while signals are blocked.
*/
status = _gl_register_action(gl, data, fn, name, keyseq);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_register_action().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
const char *name, const char *keyseq)
{
KtKeyFn *current_fn; /* An existing action function */
void *current_data; /* The action-function callback data */
/*
* Get the action function which actually runs the application-provided
* function.
*/
KtKeyFn *action_fn = gl_run_external_action;
/*
* Is there already an action of the specified name?
*/
if(_kt_lookup_action(gl->bindings, name, ¤t_fn, ¤t_data) == 0) {
/*
* If the action has the same type as the one being requested,
* simply change the contents of its GlCplCallback callback data.
*/
if(current_fn == action_fn) {
GlExternalAction *a = (GlExternalAction *) current_data;
a->fn = fn;
a->data = data;
} else {
errno = EINVAL;
_err_record_msg(gl->err,
"Illegal attempt to change the type of an existing action",
END_ERR_MSG);
return 1;
};
/*
* No existing action has the specified name.
*/
} else {
/*
* Allocate a new GlCplCallback callback object.
*/
GlExternalAction *a =
(GlExternalAction *) _new_FreeListNode(gl->ext_act_mem);
if(!a) {
errno = ENOMEM;
_err_record_msg(gl->err, "Insufficient memory to add completion action",
END_ERR_MSG);
return 1;
};
/*
* Record the completion callback data.
*/
a->fn = fn;
a->data = data;
/*
* Attempt to register the new action.
*/
if(_kt_set_action(gl->bindings, name, action_fn, a)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
_del_FreeListNode(gl->cpl_mem, (void *) a);
return 1;
};
};
/*
* Bind the action to a given key-sequence?
*/
if(keyseq && _kt_set_keybinding(gl->bindings, KTB_NORM, keyseq, name)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Invoke an action function previously registered by a call to
* gl_register_action().
*/
static KT_KEY_FN(gl_run_external_action)
{
GlAfterAction status; /* The return value of the action function */
/*
* Get the container of the action function and associated callback data.
*/
GlExternalAction *a = (GlExternalAction *) data;
/*
* Invoke the action function.
*/
status = a->fn(gl, a->data, count, gl->buff_curpos, gl->line);
/*
* If the callback took us out of raw (possibly non-blocking) input
* mode, restore this mode, and queue a redisplay of the input line.
*/
if(_gl_raw_io(gl, 1))
return 1;
/*
* Finally, check to see what the action function wants us to do next.
*/
switch(status) {
default:
case GLA_ABORT:
gl_record_status(gl, GLR_ERROR, errno);
return 1;
break;
case GLA_RETURN:
return gl_newline(gl, 1, NULL);
break;
case GLA_CONTINUE:
break;
};
return 0;
}
/*.......................................................................
* In server-I/O mode the terminal is left in raw mode between calls
* to gl_get_line(), so it is necessary for the application to install
* terminal restoring signal handlers for signals that could terminate
* or suspend the process, plus a terminal reconfiguration handler to
* be called when a process resumption signal is received, and finally
* a handler to be called when a terminal-resize signal is received.
*
* Since there are many signals that by default terminate or suspend
* processes, and different systems support different sub-sets of
* these signals, this function provides a convenient wrapper around
* sigaction() for assigning the specified handlers to all appropriate
* signals. It also arranges that when any one of these signals is
* being handled, all other catchable signals are blocked. This is
* necessary so that the specified signal handlers can safely call
* gl_raw_io(), gl_normal_io() and gl_update_size() without
* reentrancy issues.
*
* Input:
* term_handler void (*)(int) The signal handler to invoke when
* a process terminating signal is
* received.
* susp_handler void (*)(int) The signal handler to invoke when
* a process suspending signal is
* received.
* cont_handler void (*)(int) The signal handler to invoke when
* a process resumption signal is
* received (ie. SIGCONT).
* size_handler void (*)(int) The signal handler to invoke when
* a terminal-resize signal (ie. SIGWINCH)
* is received.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_tty_signals(void (*term_handler)(int), void (*susp_handler)(int),
void (*cont_handler)(int), void (*size_handler)(int))
{
int i;
/*
* Search for signals of the specified classes, and assign the
* associated signal handler to them.
*/
for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
const struct GlDefSignal *sig = gl_signal_list + i;
if(sig->attr & GLSA_SUSP) {
if(gl_set_tty_signal(sig->signo, term_handler))
return 1;
} else if(sig->attr & GLSA_TERM) {
if(gl_set_tty_signal(sig->signo, susp_handler))
return 1;
} else if(sig->attr & GLSA_CONT) {
if(gl_set_tty_signal(sig->signo, cont_handler))
return 1;
} else if(sig->attr & GLSA_SIZE) {
if(gl_set_tty_signal(sig->signo, size_handler))
return 1;
};
};
return 0;
}
/*.......................................................................
* This is a private function of gl_tty_signals(). It installs a given
* signal handler, and arranges that when that signal handler is being
* invoked other signals are blocked. The latter is important to allow
* functions like gl_normal_io(), gl_raw_io() and gl_update_size()
* to be called from signal handlers.
*
* Input:
* signo int The signal to be trapped.
* handler void (*)(int) The signal handler to assign to the signal.
*/
static int gl_set_tty_signal(int signo, void (*handler)(int))
{
SigAction act; /* The signal handler configuation */
/*
* Arrange to block all trappable signals except the one that is being
* assigned (the trapped signal will be blocked automatically by the
* system).
*/
gl_list_trappable_signals(&act.sa_mask);
sigdelset(&act.sa_mask, signo);
/*
* Assign the signal handler.
*/
act.sa_handler = handler;
/*
* There is only one portable signal handling flag, and it isn't
* relevant to us, so don't specify any flags.
*/
act.sa_flags = 0;
/*
* Register the signal handler.
*/
if(sigaction(signo, &act, NULL))
return 1;
return 0;
}
/*.......................................................................
* Display a left-justified string over multiple terminal lines,
* taking account of the current width of the terminal. Optional
* indentation and an optional prefix string can be specified to be
* displayed at the start of each new terminal line used. Similarly,
* an optional suffix can be specified to be displayed at the end of
* each terminal line. If needed, a single paragraph can be broken
* across multiple calls. Note that literal newlines in the input
* string can be used to force a newline at any point and that you
* should use this feature to explicitly end all paragraphs, including
* at the end of the last string that you write. Note that when a new
* line is started between two words that are separated by spaces,
* those spaces are not output, whereas when a new line is started
* because a newline character was found in the string, only the
* spaces before the newline character are discarded.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* indentation int The number of spaces of indentation to write
* at the beginning of each new terminal line.
* prefix const char * An optional prefix string to write after the
* indentation margin at the start of each new
* terminal line. You can specify NULL if no
* prefix is required.
* suffix const char * An optional suffix string to draw at the end
* of the terminal line. Spaces will be added
* where necessary to ensure that the suffix ends
* in the last column of the terminal line. If
* no suffix is desired, specify NULL.
* fill_char int The padding character to use when indenting
* the line or padding up to the suffix.
* def_width int If the terminal width isn't known, such as when
* writing to a pipe or redirecting to a file,
* this number specifies what width to assume.
* start int The number of characters already written to
* the start of the current terminal line. This
* is primarily used to allow individual
* paragraphs to be written over multiple calls
* to this function, but can also be used to
* allow you to start the first line of a
* paragraph with a different prefix or
* indentation than those specified above.
* string const char * The string to be written.
* Output:
* return int On error -1 is returned. Otherwise the
* return value is the terminal column index at
* which the cursor was left after writing the
* final word in the string. Successful return
* values can thus be passed verbatim to the
* 'start' arguments of subsequent calls to
* gl_display_text() to allow the printing of a
* paragraph to be broken across multiple calls
* to gl_display_text().
*/
int gl_display_text(GetLine *gl, int indentation, const char *prefix,
const char *suffix, int fill_char,
int def_width, int start, const char *string)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_completion_action() */
/*
* Check the arguments?
*/
if(!gl || !string) {
errno = EINVAL;
return -1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return -1;
/*
* Display the text while signals are blocked.
*/
status = _io_display_text(_io_write_stdio, gl->output_fp, indentation,
prefix, suffix, fill_char,
gl->ncolumn > 0 ? gl->ncolumn : def_width,
start, string);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* Block all of the signals that we are currently trapping.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* oldset sigset_t * The superseded process signal mask
* will be return in *oldset unless oldset is
* NULL.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_mask_signals(GetLine *gl, sigset_t *oldset)
{
/*
* Block all signals in all_signal_set, along with any others that are
* already blocked by the application.
*/
if(sigprocmask(SIG_BLOCK, &gl->all_signal_set, oldset) >= 0) {
gl->signals_masked = 1;
return 0;
};
/*
* On error attempt to query the current process signal mask, so
* that oldset be the correct process signal mask to restore later
* if the caller of this function ignores the error return value.
*/
if(oldset)
(void) sigprocmask(SIG_SETMASK, NULL, oldset);
gl->signals_masked = 0;
return 1;
}
/*.......................................................................
* Restore a process signal mask that was previously returned via the
* oldset argument of gl_mask_signals().
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* oldset sigset_t * The process signal mask to be restored.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_unmask_signals(GetLine *gl, sigset_t *oldset)
{
gl->signals_masked = 0;
return sigprocmask(SIG_SETMASK, oldset, NULL) < 0;
}
/*.......................................................................
* Arrange to temporarily catch the signals marked in gl->use_signal_set.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_catch_signals(GetLine *gl)
{
return sigprocmask(SIG_UNBLOCK, &gl->use_signal_set, NULL) < 0;
}
/*.......................................................................
* Select the I/O mode to be used by gl_get_line().
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* mode GlIOMode The I/O mode to establish.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_io_mode(GetLine *gl, GlIOMode mode)
{
sigset_t oldset; /* The signals that were blocked on entry to this function */
int status; /* The return status of _gl_io_mode() */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Check that the requested mode is known.
*/
switch(mode) {
case GL_NORMAL_MODE:
case GL_SERVER_MODE:
break;
default:
errno = EINVAL;
_err_record_msg(gl->err, "Unknown gl_get_line() I/O mode requested.",
END_ERR_MSG);
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Invoke the private body of this function.
*/
status = _gl_io_mode(gl, mode);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_io_mode().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_io_mode(GetLine *gl, GlIOMode mode)
{
/*
* Are we already in the specified mode?
*/
if(mode == gl->io_mode)
return 0;
/*
* First revert to normal I/O in the current I/O mode.
*/
_gl_normal_io(gl);
/*
* Record the new mode.
*/
gl->io_mode = mode;
/*
* Perform any actions needed by the new mode.
*/
if(mode==GL_SERVER_MODE) {
if(_gl_raw_io(gl, 1))
return 1;
};
return 0;
}
/*.......................................................................
* Return extra information (ie. in addition to that provided by errno)
* about the last error to occur in either gl_get_line() or its
* associated public functions.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* buff char * An optional output buffer. Note that if the
* calling application calls any gl_*()
* functions from signal handlers, it should
* provide a buffer here, so that a copy of
* the latest error message can safely be made
* while signals are blocked.
* n size_t The allocated size of buff[].
* Output:
* return const char * A pointer to the error message. This will
* be the buff argument, unless buff==NULL, in
* which case it will be a pointer to an
* internal error buffer. In the latter case,
* note that the contents of the returned buffer
* will change on subsequent calls to any gl_*()
* functions.
*/
const char *gl_error_message(GetLine *gl, char *buff, size_t n)
{
if(!gl) {
static const char *msg = "NULL GetLine argument";
if(buff) {
strncpy(buff, msg, n);
buff[n-1] = '\0';
} else {
return msg;
};
} else if(buff) {
sigset_t oldset; /* The signals that were blocked on entry to this block */
/*
* Temporarily block all signals.
*/
gl_mask_signals(gl, &oldset);
/*
* Copy the error message into the specified buffer.
*/
if(buff && n > 0) {
strncpy(buff, _err_get_msg(gl->err), n);
buff[n-1] = '\0';
};
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
} else {
return _err_get_msg(gl->err);
};
return buff;
}
/*.......................................................................
* Return the signal mask used by gl_get_line(). This is the set of
* signals that gl_get_line() is currently configured to trap.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* set sigset_t * The set of signals will be returned in *set,
* in the form of a signal process mask, as
* used by sigaction(), sigprocmask(),
* sigpending(), sigsuspend(), sigsetjmp() and
* other standard POSIX signal-aware
* functions.
* Output:
* return int 0 - OK.
* 1 - Error (examine errno for reason).
*/
int gl_list_signals(GetLine *gl, sigset_t *set)
{
/*
* Check the arguments.
*/
if(!gl || !set) {
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Copy the signal mask into *set.
*/
memcpy(set, &gl->all_signal_set, sizeof(*set));
return 0;
}
/*.......................................................................
* By default, gl_get_line() doesn't trap signals that are blocked
* when it is called. This default can be changed either on a
* per-signal basis by calling gl_trap_signal(), or on a global basis
* by calling this function. What this function does is add the
* GLS_UNBLOCK_SIG flag to all signals that are currently configured
* to be trapped by gl_get_line(), such that when subsequent calls to
* gl_get_line() wait for I/O, these signals are temporarily
* unblocked. This behavior is useful in non-blocking server-I/O mode,
* where it is used to avoid race conditions related to handling these
* signals externally to gl_get_line(). See the demonstration code in
* demo3.c, or the gl_handle_signal() man page for further
* information.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
*/
void gl_catch_blocked(GetLine *gl)
{
sigset_t oldset; /* The process signal mask to restore */
GlSignalNode *sig; /* A signal node in gl->sigs */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return;
};
/*
* Temporarily block all signals while we modify the contents of gl.
*/
gl_mask_signals(gl, &oldset);
/*
* Add the GLS_UNBLOCK_SIG flag to all configured signals.
*/
for(sig=gl->sigs; sig; sig=sig->next)
sig->flags |= GLS_UNBLOCK_SIG;
/*
* Restore the process signal mask that was superseded by the call
* to gl_mask_signals().
*/
gl_unmask_signals(gl, &oldset);
return;
}
/*.......................................................................
* Respond to signals who's default effects have important
* consequences to gl_get_line(). This is intended for use in
* non-blocking server mode, where the external event loop is
* responsible for catching signals. Signals that are handled include
* those that by default terminate or suspend the process, and the
* signal that indicates that the terminal size has changed. Note that
* this function is not signal safe and should thus not be called from
* a signal handler itself. See the gl_io_mode() man page for how it
* should be used.
*
* In the case of signals that by default terminate or suspend
* processes, command-line editing will be suspended, the terminal
* returned to a usable state, then the default disposition of the
* signal restored and the signal resent, in order to suspend or
* terminate the process. If the process subsequently resumes,
* command-line editing is resumed.
*
* In the case of signals that indicate that the terminal has been
* resized, the new size will be queried, and any input line that is
* being edited will be redrawn to fit the new dimensions of the
* terminal.
*
* Input:
* signo int The number of the signal to respond to.
* gl GetLine * The first element of an array of 'ngl' GetLine
* objects.
* ngl int The number of elements in the gl[] array. Normally
* this will be one.
*/
void gl_handle_signal(int signo, GetLine *gl, int ngl)
{
int attr; /* The attributes of the specified signal */
sigset_t all_signals; /* The set of trappable signals */
sigset_t oldset; /* The process signal mask to restore */
int i;
/*
* NULL operation?
*/
if(ngl < 1 || !gl)
return;
/*
* Look up the default attributes of the specified signal.
*/
attr = gl_classify_signal(signo);
/*
* If the signal isn't known, we are done.
*/
if(!attr)
return;
/*
* Temporarily block all signals while we modify the gl objects.
*/
gl_list_trappable_signals(&all_signals);
sigprocmask(SIG_BLOCK, &all_signals, &oldset);
/*
* Suspend or terminate the process?
*/
if(attr & (GLSA_SUSP | GLSA_TERM)) {
gl_suspend_process(signo, gl, ngl);
/*
* Resize the terminal? Note that ioctl() isn't defined as being
* signal safe, so we can't call gl_update_size() here. However,
* gl_get_line() checks for resizes on each call, so simply arrange
* for the application's event loop to call gl_get_line() as soon as
* it becomes possible to write to the terminal. Note that if the
* caller is calling select() or poll when this happens, these functions
* get interrupted, since a signal has been caught.
*/
} else if(attr & GLSA_SIZE) {
for(i=0; i<ngl; i++)
gl[i].pending_io = GLP_WRITE;
};
/*
* Restore the process signal mask that was superseded by the call
* to gl_mask_signals().
*/
sigprocmask(SIG_SETMASK, &oldset, NULL);
return;
}
/*.......................................................................
* Respond to an externally caught process suspension or
* termination signal.
*
* After restoring the terminal to a usable state, suspend or
* terminate the calling process, using the original signal with its
* default disposition restored to do so. If the process subsequently
* resumes, resume editing any input lines that were being entered.
*
* Input:
* signo int The signal number to suspend the process with. Note
* that the default disposition of this signal will be
* restored before the signal is sent, so provided
* that the default disposition of this signal is to
* either suspend or terminate the application,
* that is what wil happen, regardless of what signal
* handler is currently assigned to this signal.
* gl GetLine * The first element of an array of 'ngl' GetLine objects
* whose terminals should be restored to a sane state
* while the application is suspended.
* ngl int The number of elements in the gl[] array.
*/
static void gl_suspend_process(int signo, GetLine *gl, int ngl)
{
sigset_t only_signo; /* A signal set containing just signo */
sigset_t oldset; /* The signal mask on entry to this function */
sigset_t all_signals; /* A signal set containing all signals */
struct sigaction old_action; /* The current signal handler */
struct sigaction def_action; /* The default signal handler */
int i;
/*
* Create a signal mask containing the signal that was trapped.
*/
sigemptyset(&only_signo);
sigaddset(&only_signo, signo);
/*
* Temporarily block all signals.
*/
gl_list_trappable_signals(&all_signals);
sigprocmask(SIG_BLOCK, &all_signals, &oldset);
/*
* Restore the terminal to a usable state.
*/
for(i=0; i<ngl; i++) {
GetLine *obj = gl + i;
if(obj->raw_mode) {
_gl_normal_io(obj);
if(!obj->raw_mode) /* Check that gl_normal_io() succeded */
obj->raw_mode = -1; /* Flag raw mode as needing to be restored */
};
};
/*
* Restore the system default disposition of the signal that we
* caught. Note that this signal is currently blocked. Note that we
* don't use memcpy() to copy signal sets here, because the signal safety
* of memcpy() is undefined.
*/
def_action.sa_handler = SIG_DFL;
{
char *orig = (char *) &all_signals;
char *dest = (char *) &def_action.sa_mask;
for(i=0; i<sizeof(sigset_t); i++)
*dest++ = *orig++;
};
sigaction(signo, &def_action, &old_action);
/*
* Resend the signal, and unblock it so that it gets delivered to
* the application. This will invoke the default action of this signal.
*/
raise(signo);
sigprocmask(SIG_UNBLOCK, &only_signo, NULL);
/*
* If the process resumes again, it will resume here.
* Block the signal again, then restore our signal handler.
*/
sigprocmask(SIG_BLOCK, &only_signo, NULL);
sigaction(signo, &old_action, NULL);
/*
* Resume command-line editing.
*/
for(i=0; i<ngl; i++) {
GetLine *obj = gl + i;
if(obj->raw_mode == -1) { /* Did we flag the need to restore raw mode? */
obj->raw_mode = 0; /* gl_raw_io() does nothing unless raw_mode==0 */
_gl_raw_io(obj, 1);
};
};
/*
* Restore the process signal mask to the way it was when this function
* was called.
*/
sigprocmask(SIG_SETMASK, &oldset, NULL);
return;
}
/*.......................................................................
* Return the information about the default attributes of a given signal.
* The attributes that are returned are as defined by the standards that
* created them, including POSIX, SVR4 and 4.3+BSD, and are taken from a
* table in Richard Steven's book, "Advanced programming in the UNIX
* environment".
*
* Input:
* signo int The signal to be characterized.
* Output:
* return int A bitwise union of GlSigAttr enumerators, or 0
* if the signal isn't known.
*/
static int gl_classify_signal(int signo)
{
int i;
/*
* Search for the specified signal in the gl_signal_list[] table.
*/
for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
const struct GlDefSignal *sig = gl_signal_list + i;
if(sig->signo == signo)
return sig->attr;
};
/*
* Signal not known.
*/
return 0;
}
/*.......................................................................
* When in non-blocking server mode, this function can be used to abandon
* the current incompletely entered input line, and prepare to start
* editing a new line on the next call to gl_get_line().
*
* Input:
* gl GetLine * The line editor resource object.
*/
void gl_abandon_line(GetLine *gl)
{
sigset_t oldset; /* The process signal mask to restore */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return;
};
/*
* Temporarily block all signals while we modify the contents of gl.
*/
gl_mask_signals(gl, &oldset);
/*
* Mark the input line as discarded.
*/
_gl_abandon_line(gl);
/*
* Restore the process signal mask that was superseded by the call
* to gl_mask_signals().
*/
gl_unmask_signals(gl, &oldset);
return;
}
/*.......................................................................
* This is the private body of the gl_abandon_line() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
void _gl_abandon_line(GetLine *gl)
{
gl->endline = 1;
gl->pending_io = GLP_WRITE;
}
/*.......................................................................
* How many characters are needed to write a number as an octal string?
*
* Input:
* num unsigned The to be measured.
* Output:
* return int The number of characters needed.
*/
static int gl_octal_width(unsigned num)
{
int n; /* The number of characters needed to render the number */
for(n=1; num /= 8; n++)
;
return n;
}
/*.......................................................................
* Tell gl_get_line() the current terminal size. Note that this is only
* necessary on systems where changes in terminal size aren't reported
* via SIGWINCH.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* ncolumn int The number of columns in the terminal.
* nline int The number of lines in the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_set_term_size(GetLine *gl, int ncolumn, int nline)
{
sigset_t oldset; /* The signals that were blocked on entry */
/* to this function */
int status; /* The return status */
/*
* Block all signals while accessing gl.
*/
gl_mask_signals(gl, &oldset);
/*
* Install the new terminal size.
*/
status = _gl_set_term_size(gl, ncolumn, nline);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the gl_set_term_size() function. It
* assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_set_term_size(GetLine *gl, int ncolumn, int nline)
{
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Reject non-sensical dimensions.
*/
if(ncolumn <= 0 || nline <= 0) {
_err_record_msg(gl->err, "Invalid terminal size", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Install the new dimensions in the terminal driver if possible, so
* that future calls to gl_query_size() get the new value.
*/
#ifdef TIOCSWINSZ
if(gl->is_term) {
struct winsize size;
size.ws_row = nline;
size.ws_col = ncolumn;
size.ws_xpixel = 0;
size.ws_ypixel = 0;
if(ioctl(gl->output_fd, TIOCSWINSZ, &size) == -1) {
_err_record_msg(gl->err, "Can't change terminal size", END_ERR_MSG);
return 1;
};
};
#endif
/*
* If an input line is in the process of being edited, redisplay it to
* accomodate the new dimensions, and record the new dimensions in
* gl->nline and gl->ncolumn.
*/
return gl_handle_tty_resize(gl, ncolumn, nline);
}
/*.......................................................................
* Record a character in the input line buffer at a given position.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* c char The character to be recorded.
* bufpos int The index in the buffer at which to record the
* character.
* Output:
* return int 0 - OK.
* 1 - Insufficient room.
*/
static int gl_buffer_char(GetLine *gl, char c, int bufpos)
{
/*
* Guard against buffer overruns.
*/
if(bufpos >= gl->linelen)
return 1;
/*
* Record the new character.
*/
gl->line[bufpos] = c;
/*
* If the new character was placed beyond the end of the current input
* line, update gl->ntotal to reflect the increased number of characters
* that are in gl->line, and terminate the string.
*/
if(bufpos >= gl->ntotal) {
gl->ntotal = bufpos+1;
gl->line[gl->ntotal] = '\0';
};
return 0;
}
/*.......................................................................
* Copy a given string into the input buffer, overwriting the current
* contents.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* s const char * The string to be recorded.
* n int The number of characters to be copied from the
* string.
* bufpos int The index in the buffer at which to place the
* the first character of the string.
* Output:
* return int 0 - OK.
* 1 - String truncated to fit.
*/
static int gl_buffer_string(GetLine *gl, const char *s, int n, int bufpos)
{
int nnew; /* The number of characters actually recorded */
int i;
/*
* How many of the characters will fit within the buffer?
*/
nnew = bufpos + n <= gl->linelen ? n : (gl->linelen - bufpos);
/*
* Record the first nnew characters of s[] in the buffer.
*/
for(i=0; i<nnew; i++)
gl_buffer_char(gl, s[i], bufpos + i);
/*
* Was the string truncated?
*/
return nnew < n;
}
/*.......................................................................
* Make room in the input buffer for a string to be inserted. This
* involves moving the characters that follow a specified point, towards
* the end of the buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* start int The index of the first character to be moved.
* n int The width of the gap.
* Output:
* return int 0 - OK.
* 1 - Insufficient room.
*/
static int gl_make_gap_in_buffer(GetLine *gl, int start, int n)
{
/*
* Ensure that the buffer has sufficient space.
*/
if(gl->ntotal + n > gl->linelen)
return 1;
/*
* Move everything including and beyond the character at 'start'
* towards the end of the string.
*/
memmove(gl->line + start + n, gl->line + start, gl->ntotal - start + 1);
/*
* Update the recorded size of the line.
*/
gl->ntotal += n;
return 1;
}
/*.......................................................................
* Remove a given number of characters from the input buffer. This
* involves moving the characters that follow the removed characters to
* where the removed sub-string started in the input buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* start int The first character to be removed.
* n int The number of characters to remove.
*/
static void gl_remove_from_buffer(GetLine *gl, int start, int n)
{
memmove(gl->line + start, gl->line + start + n, gl->ntotal - start - n + 1);
/*
* Update the recorded size of the line.
*/
gl->ntotal -= n;
}
/*.......................................................................
* Truncate the string in the input line buffer after a given number of
* characters.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* n int The new length of the line.
* Output:
* return int 0 - OK.
* 1 - n > gl->linelen.
*/
static int gl_truncate_buffer(GetLine *gl, int n)
{
if(n > gl->linelen)
return 1;
gl->line[n] = '\0';
gl->ntotal = n;
return 0;
}
/*.......................................................................
* When the contents of gl->line[] are changed without calling any of the
* gl_ buffer manipulation functions, this function must be called to
* compute the length of this string, and ancillary information.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
*/
static void gl_update_buffer(GetLine *gl)
{
int len; /* The length of the line */
/*
* Measure the length of the input line.
*/
for(len=0; len <= gl->linelen && gl->line[len]; len++)
;
/*
* Just in case the string wasn't correctly terminated, do so here.
*/
gl->line[len] = '\0';
/*
* Record the number of characters that are now in gl->line[].
*/
gl->ntotal = len;
/*
* Ensure that the cursor stays within the bounds of the modified
* input line.
*/
if(gl->buff_curpos > gl->ntotal)
gl->buff_curpos = gl->ntotal;
/*
* Arrange for the input line to be redrawn.
*/
gl_queue_redisplay(gl);
return;
}
/*.......................................................................
* Erase the displayed input line, including its prompt, and leave the
* cursor where the erased line started. Note that to allow this
* function to be used when responding to a terminal resize, this
* function is designed to work even if the horizontal cursor position
* doesn't match the internally recorded position.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_erase_line(GetLine *gl)
{
/*
* Is a line currently displayed?
*/
if(gl->displayed) {
/*
* Relative the the start of the input line, which terminal line of
* the current input line is the cursor currently on?
*/
int cursor_line = gl->term_curpos / gl->ncolumn;
/*
* Move the cursor to the start of the line.
*/
for( ; cursor_line > 0; cursor_line--) {
if(gl_print_control_sequence(gl, 1, gl->up))
return 1;
};
if(gl_print_control_sequence(gl, 1, gl->bol))
return 1;
/*
* Clear from the start of the line to the end of the terminal.
*/
if(gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
return 1;
/*
* Mark the line as no longer displayed.
*/
gl_line_erased(gl);
};
return 0;
}
/*.......................................................................
* Arrange for the input line to be redisplayed by gl_flush_output(),
* as soon as the output queue becomes empty.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
*/
static void gl_queue_redisplay(GetLine *gl)
{
gl->redisplay = 1;
gl->pending_io = GLP_WRITE;
}
/*.......................................................................
* Truncate the displayed input line starting from the current
* terminal cursor position, and leave the cursor at the end of the
* truncated line. The input-line buffer is not affected.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int gl_truncate_display(GetLine *gl)
{
/*
* Keep a record of the current terminal cursor position.
*/
int term_curpos = gl->term_curpos;
/*
* First clear from the cursor to the end of the current input line.
*/
if(gl_print_control_sequence(gl, 1, gl->clear_eol))
return 1;
/*
* If there is more than one line displayed, go to the start of the
* next line and clear from there to the end of the display. Note that
* we can't use clear_eod to do the whole job of clearing from the
* current cursor position to the end of the terminal because
* clear_eod is only defined when used at the start of a terminal line
* (eg. with gnome terminals, clear_eod clears from the start of the
* current terminal line, rather than from the current cursor
* position).
*/
if(gl->term_len / gl->ncolumn > gl->term_curpos / gl->ncolumn) {
if(gl_print_control_sequence(gl, 1, gl->down) ||
gl_print_control_sequence(gl, 1, gl->bol) ||
gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
return 1;
/*
* Where is the cursor now?
*/
gl->term_curpos = gl->ncolumn * (term_curpos / gl->ncolumn + 1);
/*
* Restore the cursor position.
*/
gl_set_term_curpos(gl, term_curpos);
};
/*
* Update the recorded position of the final character.
*/
gl->term_len = gl->term_curpos;
return 0;
}
/*.......................................................................
* Return the set of all trappable signals.
*
* Input:
* signals sigset_t * The set of signals will be recorded in
* *signals.
*/
static void gl_list_trappable_signals(sigset_t *signals)
{
/*
* Start with the set of all signals.
*/
sigfillset(signals);
/*
* Remove un-trappable signals from this set.
*/
#ifdef SIGKILL
sigdelset(signals, SIGKILL);
#endif
#ifdef SIGSTOP
sigdelset(signals, SIGSTOP);
#endif
}
/*.......................................................................
* Read an input line from a non-interactive input stream.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK
* 1 - Error.
*/
static int gl_read_stream_line(GetLine *gl)
{
char c = '\0'; /* The latest character read from fp */
/*
* Record the fact that we are about to read input.
*/
gl->pending_io = GLP_READ;
/*
* If we are starting a new line, reset the line-input parameters.
*/
if(gl->endline)
gl_reset_input_line(gl);
/*
* Read one character at a time.
*/
while(gl->ntotal < gl->linelen && c != '\n') {
/*
* Attempt to read one more character.
*/
switch(gl_read_input(gl, &c)) {
case GL_READ_OK:
break;
case GL_READ_EOF: /* Reached end-of-file? */
/*
* If any characters were read before the end-of-file condition,
* interpolate a newline character, so that the caller sees a
* properly terminated line. Otherwise return an end-of-file
* condition.
*/
if(gl->ntotal > 0) {
c = '\n';
} else {
gl_record_status(gl, GLR_EOF, 0);
return 1;
};
break;
case GL_READ_BLOCKED: /* Input blocked? */
gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
return 1;
break;
case GL_READ_ERROR: /* I/O error? */
return 1;
break;
};
/*
* Append the character to the line buffer.
*/
if(gl_buffer_char(gl, c, gl->ntotal))
return 1;
};
/*
* Was the end of the input line reached before running out of buffer space?
*/
gl->endline = (c == '\n');
return 0;
}
/*.......................................................................
* Read a single character from a non-interactive input stream.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int The character, or EOF on error.
*/
static int gl_read_stream_char(GetLine *gl)
{
char c = '\0'; /* The latest character read from fp */
int retval = EOF; /* The return value of this function */
/*
* Arrange to discard any incomplete input line.
*/
_gl_abandon_line(gl);
/*
* Record the fact that we are about to read input.
*/
gl->pending_io = GLP_READ;
/*
* Attempt to read one more character.
*/
switch(gl_read_input(gl, &c)) {
case GL_READ_OK: /* Success */
retval = c;
break;
case GL_READ_BLOCKED: /* The read blocked */
gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
retval = EOF; /* Failure */
break;
case GL_READ_EOF: /* End of file reached */
gl_record_status(gl, GLR_EOF, 0);
retval = EOF; /* Failure */
break;
case GL_READ_ERROR:
retval = EOF; /* Failure */
break;
};
return retval;
}
/*.......................................................................
* Bind a key sequence to a given action.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* origin GlKeyOrigin The originator of the key binding.
* key const char * The key-sequence to be bound (or unbound).
* action const char * The name of the action to bind the key to,
* or either NULL or "" to unbind the
* key-sequence.
* Output:
* return int 0 - OK
* 1 - Error.
*/
int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin, const char *keyseq,
const char *action)
{
KtBinder binder; /* The private internal equivalent of 'origin' */
/*
* Check the arguments.
*/
if(!gl || !keyseq) {
errno = EINVAL;
if(gl)
_err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* An empty action string requests that the key-sequence be unbound.
* This is indicated to _kt_set_keybinding() by passing a NULL action
* string, so convert an empty string to a NULL action pointer.
*/
if(action && *action=='\0')
action = NULL;
/*
* Translate the public originator enumeration to the private equivalent.
*/
binder = origin==GL_USER_KEY ? KTB_USER : KTB_NORM;
/*
* Bind the action to a given key-sequence?
*/
if(keyseq && _kt_set_keybinding(gl->bindings, binder, keyseq, action)) {
_err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* This is the public wrapper around the gl_clear_termina() function.
* It clears the terminal and leaves the cursor at the home position.
* In server I/O mode, the next call to gl_get_line() will also
* redisplay the current input line.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_erase_terminal(GetLine *gl)
{
sigset_t oldset; /* The signals that were blocked on entry */
/* to this function */
int status; /* The return status */
/*
* Block all signals while accessing gl.
*/
gl_mask_signals(gl, &oldset);
/*
* Clear the terminal.
*/
status = gl_clear_screen(gl, 1, NULL);
/*
* Attempt to flush the clear-screen control codes to the terminal.
* If this doesn't complete the job, the next call to gl_get_line()
* will.
*/
(void) gl_flush_output(gl);
/*
* Restore the process signal mask before returning.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This function must be called by any function that erases the input
* line.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
*/
static void gl_line_erased(GetLine *gl)
{
gl->displayed = 0;
gl->term_curpos = 0;
gl->term_len = 0;
}
/*.......................................................................
* Append a specified line to the history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* line const char * The line to be added.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_append_history(GetLine *gl, const char *line)
{
sigset_t oldset; /* The signals that were blocked on entry */
/* to this function */
int status; /* The return status */
/*
* Check the arguments.
*/
if(!gl || !line) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
status = _gl_append_history(gl, line);
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return status;
}
/*.......................................................................
* This is the private body of the public function, gl_append_history().
* It assumes that the caller has checked its arguments and blocked the
* delivery of signals.
*/
static int _gl_append_history(GetLine *gl, const char *line)
{
int status =_glh_add_history(gl->glh, line, 0);
if(status)
_err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
return status;
}
/*.......................................................................
* Enable or disable the automatic addition of newly entered lines to the
* history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* enable int If true, subsequently entered lines will
* automatically be added to the history list
* before they are returned to the caller of
* gl_get_line(). If 0, the choice of how and
* when to archive lines in the history list,
* is left up to the calling application, which
* can do so via calls to gl_append_history().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_automatic_history(GetLine *gl, int enable)
{
sigset_t oldset; /* The signals that were blocked on entry */
/* to this function */
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return 1;
};
/*
* Block all signals.
*/
if(gl_mask_signals(gl, &oldset))
return 1;
/*
* Execute the private body of the function while signals are blocked.
*/
gl->automatic_history = enable;
/*
* Restore the process signal mask.
*/
gl_unmask_signals(gl, &oldset);
return 0;
}
/*.......................................................................
* This is a public function that reads a single uninterpretted
* character from the user, without displaying anything.
*
* Input:
* gl GetLine * A resource object previously returned by
* new_GetLine().
* Output:
* return int The character that was read, or EOF if the read
* had to be aborted (in which case you can call
* gl_return_status() to find out why).
*/
int gl_read_char(GetLine *gl)
{
int retval; /* The return value of _gl_read_char() */
/*
* This function can be called from application callback functions,
* so check whether signals have already been masked, so that we don't
* do it again, and overwrite gl->old_signal_set.
*/
int was_masked = gl->signals_masked;
/*
* Check the arguments.
*/
if(!gl) {
errno = EINVAL;
return EOF;
};
/*
* Temporarily block all of the signals that we have been asked to trap.
*/
if(!was_masked && gl_mask_signals(gl, &gl->old_signal_set))
return EOF;
/*
* Perform the character reading task.
*/
retval = _gl_read_char(gl);
/*
* Restore the process signal mask to how it was when this function was
* first called.
*/
if(!was_masked)
gl_unmask_signals(gl, &gl->old_signal_set);
return retval;
}
/*.......................................................................
* This is the main body of the public function gl_read_char().
*/
static int _gl_read_char(GetLine *gl)
{
int retval = EOF; /* The return value */
int waserr = 0; /* True if an error occurs */
char c; /* The character read */
/*
* This function can be called from application callback functions,
* so check whether signals have already been overriden, so that we don't
* overwrite the preserved signal handlers with gl_get_line()s. Also
* record whether we are currently in raw I/O mode or not, so that this
* can be left in the same state on leaving this function.
*/
int was_overriden = gl->signals_overriden;
int was_raw = gl->raw_mode;
/*
* Also keep a record of the direction of any I/O that gl_get_line()
* is awaiting, so that we can restore this status on return.
*/
GlPendingIO old_pending_io = gl->pending_io;
/*
* Assume that this call will successfully complete the input operation
* until proven otherwise.
*/
gl_clear_status(gl);
/*
* If this is the first call to this function or gl_get_line(),
* since new_GetLine(), complete any postponed configuration.
*/
if(!gl->configured) {
(void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
gl->configured = 1;
};
/*
* Before installing our signal handler functions, record the fact
* that there are no pending signals.
*/
gl_pending_signal = -1;
/*
* Temporarily override the signal handlers of the calling program,
* so that we can intercept signals that would leave the terminal
* in a bad state.
*/
if(!was_overriden)
waserr = gl_override_signal_handlers(gl);
/*
* After recording the current terminal settings, switch the terminal
* into raw input mode, without redisplaying any partially entered input
* line.
*/
if(!was_raw)
waserr = waserr || _gl_raw_io(gl, 0);
/*
* Attempt to read the line. This will require more than one attempt if
* either a current temporary input file is opened by gl_get_input_line()
* or the end of a temporary input file is reached by gl_read_stream_line().
*/
while(!waserr) {
/*
* Read a line from a non-interactive stream?
*/
if(gl->file_fp || !gl->is_term) {
retval = gl_read_stream_char(gl);
if(retval != EOF) { /* Success? */
break;
} else if(gl->file_fp) { /* End of temporary input file? */
gl_revert_input(gl);
gl_record_status(gl, GLR_NEWLINE, 0);
} else { /* An error? */
waserr = 1;
break;
};
};
/*
* Read from the terminal? Note that the above if() block may have
* changed gl->file_fp, so it is necessary to retest it here, rather
* than using an else statement.
*/
if(!gl->file_fp && gl->is_term) {
/*
* Flush any pending output to the terminal before waiting
* for the user to type a character.
*/
if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl)) {
retval = EOF;
/*
* Read one character. Don't append it to the key buffer, since
* this would subseuqnely appear as bogus input to the line editor.
*/
} else if(gl_read_terminal(gl, 0, &c) == 0) {
/*
* Record the character for return.
*/
retval = c;
/*
* In this mode, count each character as being a new key-sequence.
*/
gl->keyseq_count++;
/*
* Delete the character that was read, from the key-press buffer.
*/
gl_discard_chars(gl, 1);
};
if(retval==EOF)
waserr = 1;
else
break;
};
};
/*
* If an error occurred, but gl->rtn_status is still set to
* GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
* leave it at whatever specific value was assigned by the function
* that aborted input. This means that only functions that trap
* non-generic errors have to remember to update gl->rtn_status
* themselves.
*/
if(waserr && gl->rtn_status == GLR_NEWLINE)
gl_record_status(gl, GLR_ERROR, errno);
/*
* Restore terminal settings, if they were changed by this function.
*/
if(!was_raw && gl->io_mode != GL_SERVER_MODE)
_gl_normal_io(gl);
/*
* Restore the signal handlers, if they were overriden by this function.
*/
if(!was_overriden)
gl_restore_signal_handlers(gl);
/*
* If this function gets aborted early, the errno value associated
* with the event that caused this to happen is recorded in
* gl->rtn_errno. Since errno may have been overwritten by cleanup
* functions after this, restore its value to the value that it had
* when the error condition occured, so that the caller can examine it
* to find out what happened.
*/
errno = gl->rtn_errno;
/*
* Error conditions are signalled to the caller, by setting the returned
* character to EOF.
*/
if(gl->rtn_status != GLR_NEWLINE)
retval = EOF;
/*
* Restore the indication of what direction of I/O gl_get_line()
* was awaiting before this call.
*/
gl->pending_io = old_pending_io;
/*
* Return the acquired character.
*/
return retval;
}
/*.......................................................................
* Reset the GetLine completion status. This function should be called
* at the start of gl_get_line(), gl_read_char() and gl_query_char()
* to discard the completion status and non-zero errno value of any
* preceding calls to these functions.
*
* Input:
* gl GetLine * The resource object of this module.
*/
static void gl_clear_status(GetLine *gl)
{
gl_record_status(gl, GLR_NEWLINE, 0);
}
/*.......................................................................
* When an error or other event causes gl_get_line() to return, this
* function should be called to record information about what
* happened, including the value of errno and the value that
* gl_return_status() should return.
*
* Input:
* gl GetLine * The resource object of this module.
* rtn_status GlReturnStatus The completion status. To clear a
* previous abnormal completion status,
* specify GLR_NEWLINE (this is what
* gl_clear_status() does).
* rtn_errno int The associated value of errno.
*/
static void gl_record_status(GetLine *gl, GlReturnStatus rtn_status,
int rtn_errno)
{
/*
* If rtn_status==GLR_NEWLINE, then this resets the completion status, so we
* should always heed this. Otherwise, only record the first abnormal
* condition that occurs after such a reset.
*/
if(rtn_status == GLR_NEWLINE || gl->rtn_status == GLR_NEWLINE) {
gl->rtn_status = rtn_status;
gl->rtn_errno = rtn_errno;
};
}
#ifndef getline_h
#define getline_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Set the name of the getline configuration file.
*/
#define TECLA_CONFIG_FILE "~/.teclarc"
/*
* The following macro returns non-zero if a character is
* a control character.
*/
#define IS_CTRL_CHAR(c) ((unsigned char)(c) < ' ' || (unsigned char)(c)=='\177')
/*
* The following macro returns non-zero if a character is
* a meta character.
*/
#define IS_META_CHAR(c) (((unsigned char)(c) & 0x80) && !isprint((int)(unsigned char)(c)))
/*
* Return the character that would be produced by pressing the
* specified key plus the control key.
*/
#define MAKE_CTRL(c) ((c)=='?' ? '\177' : ((unsigned char)toupper(c) & ~0x40))
/*
* Return the character that would be produced by pressing the
* specified key plus the meta key.
*/
#define MAKE_META(c) ((unsigned char)(c) | 0x80)
/*
* Given a binary control character, return the character that
* had to be pressed at the same time as the control key.
*/
#define CTRL_TO_CHAR(c) (toupper((unsigned char)(c) | 0x40))
/*
* Given a meta character, return the character that was pressed
* at the same time as the meta key.
*/
#define META_TO_CHAR(c) ((unsigned char)(c) & ~0x80)
/*
* Specify the string of characters other than the alphanumeric characters,
* that are to be considered parts of words.
*/
#define GL_WORD_CHARS "_*\?\\[]"
/*
* Define the escape character, both as a string and as a character.
*/
#define GL_ESC_STR "\033"
#define GL_ESC_CHAR '\033'
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "hash.h"
#include "strngmem.h"
#include "freelist.h"
/*
* The following container object contains free-lists to be used
* for allocation of HashTable containers and nodes.
*/
struct HashMemory {
FreeList *hash_memory; /* HashTable free-list */
FreeList *node_memory; /* HashNode free-list */
StringMem *string_memory; /* Memory used to allocate hash strings */
};
/*
* Define a hash symbol-table entry.
* See symbol.h for the definition of the Symbol container type.
*/
typedef struct HashNode HashNode;
struct HashNode {
Symbol symbol; /* The symbol stored in the hash-entry */
HashNode *next; /* The next hash-table entry in a bucket list */
};
/*
* Each hash-table bucket contains a linked list of entries that
* hash to the same bucket.
*/
typedef struct {
HashNode *head; /* The head of the bucket hash-node list */
int count; /* The number of entries in the list */
} HashBucket;
/*
* A hash-table consists of 'size' hash buckets.
* Note that the HashTable typedef for this struct is contained in hash.h.
*/
struct HashTable {
HashMemory *mem; /* HashTable free-list */
int internal_mem; /* True if 'mem' was allocated by _new_HashTable() */
int case_sensitive; /* True if case is significant in lookup keys */
int size; /* The number of hash buckets */
HashBucket *bucket; /* An array of 'size' hash buckets */
int (*keycmp)(const char *, const char *); /* Key comparison function */
void *app_data; /* Application-provided data */
HASH_DEL_FN(*del_fn); /* Application-provided 'app_data' destructor */
};
static HashNode *_del_HashNode(HashTable *hash, HashNode *node);
static HashNode *_new_HashNode(HashTable *hash, const char *name, int code,
void (*fn)(void), void *data, SYM_DEL_FN(*del_fn));
static HashNode *_find_HashNode(HashTable *hash, HashBucket *bucket,
const char *name, HashNode **prev);
static HashBucket *_find_HashBucket(HashTable *hash, const char *name);
static int _ht_lower_strcmp(const char *node_key, const char *look_key);
static int _ht_strcmp(const char *node_key, const char *look_key);
/*.......................................................................
* Allocate a free-list for use in allocating hash tables and their nodes.
*
* Input:
* list_count int The number of HashTable containers per free-list
* block.
* node_count int The number of HashTable nodes per free-list block.
* Output:
* return HashMemory * The new free-list for use in allocating hash tables
* and their nodes.
*/
HashMemory *_new_HashMemory(int hash_count, int node_count)
{
HashMemory *mem;
/*
* Allocate the free-list container.
*/
mem = (HashMemory *) malloc(sizeof(HashMemory));
if(!mem) {
errno = ENOMEM;
return NULL;
};
/*
* Initialize the container at least up to the point at which it can
* safely be passed to _del_HashMemory().
*/
mem->hash_memory = NULL;
mem->node_memory = NULL;
mem->string_memory = NULL;
/*
* Allocate the two free-lists.
*/
mem->hash_memory = _new_FreeList(sizeof(HashTable), hash_count);
if(!mem->hash_memory)
return _del_HashMemory(mem, 1);
mem->node_memory = _new_FreeList(sizeof(HashNode), node_count);
if(!mem->node_memory)
return _del_HashMemory(mem, 1);
mem->string_memory = _new_StringMem(64);
if(!mem->string_memory)
return _del_HashMemory(mem, 1);
/*
* Return the free-list container.
*/
return mem;
}
/*.......................................................................
* Delete a HashTable free-list. An error will be displayed if the list is
* still in use and the deletion will be aborted.
*
* Input:
* mem HashMemory * The free-list container to be deleted.
* force int If force==0 then _del_HashMemory() will complain
* and refuse to delete the free-list if any
* of nodes have not been returned to the free-list.
* If force!=0 then _del_HashMemory() will not check
* whether any nodes are still in use and will
* always delete the list.
* Output:
* return HashMemory * Always NULL (even if the memory could not be
* deleted).
*/
HashMemory *_del_HashMemory(HashMemory *mem, int force)
{
if(mem) {
if(!force && (_busy_FreeListNodes(mem->hash_memory) > 0 ||
_busy_FreeListNodes(mem->node_memory) > 0)) {
errno = EBUSY;
return NULL;
};
mem->hash_memory = _del_FreeList(mem->hash_memory, force);
mem->node_memory = _del_FreeList(mem->node_memory, force);
mem->string_memory = _del_StringMem(mem->string_memory, force);
free(mem);
};
return NULL;
}
/*.......................................................................
* Create a new hash table.
*
* Input:
* mem HashMemory * An optional free-list for use in allocating
* HashTable containers and nodes. See explanation
* in hash.h. If you are going to allocate more
* than one hash table, then it will be more
* efficient to allocate a single free-list for
* all of them than to force each hash table
* to allocate its own private free-list.
* size int The size of the hash table. Best performance
* will be acheived if this is a prime number.
* hcase HashCase Specify how symbol case is considered when
* looking up symbols, from:
* IGNORE_CASE - Upper and lower case versions
* of a letter are treated as
* being identical.
* HONOUR_CASE - Upper and lower case versions
* of a letter are treated as
* being distinct.
* characters in a lookup name is significant.
* app_data void * Optional application data to be registered
* to the table. This is presented to user
* provided SYM_DEL_FN() symbol destructors along
* with the symbol data.
* del_fn() HASH_DEL_FN(*) If you want app_data to be free'd when the
* hash-table is destroyed, register a suitable
* destructor function here.
* Output:
* return HashTable * The new hash table, or NULL on error.
*/
HashTable *_new_HashTable(HashMemory *mem, int size, HashCase hcase,
void *app_data, HASH_DEL_FN(*del_fn))
{
HashTable *hash; /* The table to be returned */
int allocate_mem = !mem; /* True if mem should be internally allocated */
int i;
/*
* Check arguments.
*/
if(size <= 0) {
errno = EINVAL;
return NULL;
};
/*
* Allocate an internal free-list?
*/
if(allocate_mem) {
mem = _new_HashMemory(1, 100);
if(!mem)
return NULL;
};
/*
* Allocate the container.
*/
hash = (HashTable *) _new_FreeListNode(mem->hash_memory);
if(!hash) {
errno = ENOMEM;
if(allocate_mem)
mem = _del_HashMemory(mem, 1);
return NULL;
};
/*
* Before attempting any operation that might fail, initialize
* the container at least up to the point at which it can safely
* be passed to _del_HashTable().
*/
hash->mem = mem;
hash->internal_mem = allocate_mem;
hash->case_sensitive = hcase==HONOUR_CASE;
hash->size = size;
hash->bucket = NULL;
hash->keycmp = hash->case_sensitive ? _ht_strcmp : _ht_lower_strcmp;
hash->app_data = app_data;
hash->del_fn = del_fn;
/*
* Allocate the array of 'size' hash buckets.
*/
hash->bucket = (HashBucket *) malloc(sizeof(HashBucket) * size);
if(!hash->bucket) {
errno = ENOMEM;
return _del_HashTable(hash);
};
/*
* Initialize the bucket array.
*/
for(i=0; i<size; i++) {
HashBucket *b = hash->bucket + i;
b->head = NULL;
b->count = 0;
};
/*
* The table is ready for use - albeit currently empty.
*/
return hash;
}
/*.......................................................................
* Delete a hash-table.
*
* Input:
* hash HashTable * The hash table to be deleted.
* Output:
* return HashTable * The deleted hash table (always NULL).
*/
HashTable *_del_HashTable(HashTable *hash)
{
if(hash) {
/*
* Clear and delete the bucket array.
*/
if(hash->bucket) {
_clear_HashTable(hash);
free(hash->bucket);
hash->bucket = NULL;
};
/*
* Delete application data.
*/
if(hash->del_fn)
hash->del_fn(hash->app_data);
/*
* If the hash table was allocated from an internal free-list, delete
* it and the hash table by deleting the free-list. Otherwise just
* return the hash-table to the external free-list.
*/
if(hash->internal_mem)
_del_HashMemory(hash->mem, 1);
else
hash = (HashTable *) _del_FreeListNode(hash->mem->hash_memory, hash);
};
return NULL;
}
/*.......................................................................
* Create and install a new entry in a hash table. If an entry with the
* same name already exists, replace its contents with the new data.
*
* Input:
* hash HashTable * The hash table to insert the symbol into.
* name const char * The name to tag the entry with.
* code int An application-specific code to be stored in
* the entry.
* fn void (*)(void) An application-specific function to be stored
* in the entry.
* data void * An application-specific pointer to data to be
* associated with the entry, or NULL if not
* relevant.
* del_fn SYM_DEL_FN(*) An optional destructor function. When the
* symbol is deleted this function will be called
* with the 'code' and 'data' arguments given
* above. Any application data that was registered
* to the table via the app_data argument of
* _new_HashTable() will also be passed.
* Output:
* return HashNode * The new entry, or NULL if there was insufficient
* memory or the arguments were invalid.
*/
Symbol *_new_HashSymbol(HashTable *hash, const char *name, int code,
void (*fn)(void), void *data, SYM_DEL_FN(*del_fn))
{
HashBucket *bucket; /* The hash-bucket associated with the name */
HashNode *node; /* The new node */
/*
* Check arguments.
*/
if(!hash || !name) {
errno = EINVAL;
return NULL;
};
/*
* Get the hash bucket of the specified name.
*/
bucket = _find_HashBucket(hash, name);
/*
* See if a node with the same name already exists.
*/
node = _find_HashNode(hash, bucket, name, NULL);
/*
* If found, delete its contents by calling the user-supplied
* destructor function, if provided.
*/
if(node) {
if(node->symbol.data && node->symbol.del_fn) {
node->symbol.data = node->symbol.del_fn(hash->app_data, node->symbol.code,
node->symbol.data);
};
/*
* Allocate a new node if necessary.
*/
} else {
node = _new_HashNode(hash, name, code, fn, data, del_fn);
if(!node)
return NULL;
};
/*
* Install the node at the head of the hash-bucket list.
*/
node->next = bucket->head;
bucket->head = node;
bucket->count++;
return &node->symbol;
}
/*.......................................................................
* Remove and delete a given hash-table entry.
*
* Input:
* hash HashTable * The hash table to find the symbol in.
* name const char * The name of the entry.
* Output:
* return HashNode * The deleted hash node (always NULL).
*/
Symbol *_del_HashSymbol(HashTable *hash, const char *name)
{
if(hash && name) {
HashBucket *bucket = _find_HashBucket(hash, name);
HashNode *prev; /* The node preceding the located node */
HashNode *node = _find_HashNode(hash, bucket, name, &prev);
/*
* Node found?
*/
if(node) {
/*
* Remove the node from the bucket list.
*/
if(prev) {
prev->next = node->next;
} else {
bucket->head = node->next;
};
/*
* Record the loss of a node.
*/
bucket->count--;
/*
* Delete the node.
*/
(void) _del_HashNode(hash, node);
};
};
return NULL;
}
/*.......................................................................
* Look up a symbol in the hash table.
*
* Input:
* hash HashTable * The table to look up the string in.
* name const char * The name of the symbol to look up.
* Output:
* return Symbol * The located hash-table symbol, or NULL if not
* found.
*/
Symbol *_find_HashSymbol(HashTable *hash, const char *name)
{
HashBucket *bucket; /* The hash-table bucket associated with name[] */
HashNode *node; /* The hash-table node of the requested symbol */
/*
* Check arguments.
*/
if(!hash)
return NULL;
/*
* Nothing to lookup?
*/
if(!name)
return NULL;
/*
* Hash the name to a hash-table bucket.
*/
bucket = _find_HashBucket(hash, name);
/*
* Find the bucket entry that exactly matches the name.
*/
node = _find_HashNode(hash, bucket, name, NULL);
if(!node)
return NULL;
return &node->symbol;
}
/*.......................................................................
* Private function used to allocate a hash-table node.
* The caller is responsible for checking that the specified symbol
* is unique and for installing the returned entry in the table.
*
* Input:
* hash HashTable * The table to allocate the node for.
* name const char * The name of the new entry.
* code int A user-supplied context code.
* fn void (*)(void) A user-supplied function pointer.
* data void * A user-supplied data pointer.
* del_fn SYM_DEL_FN(*) An optional 'data' destructor function.
* Output:
* return HashNode * The new node, or NULL on error.
*/
static HashNode *_new_HashNode(HashTable *hash, const char *name, int code,
void (*fn)(void), void *data, SYM_DEL_FN(*del_fn))
{
HashNode *node; /* The new node */
size_t len;
/*
* Allocate the new node from the free list.
*/
node = (HashNode *) _new_FreeListNode(hash->mem->node_memory);
if(!node)
return NULL;
/*
* Before attempting any operation that might fail, initialize the
* contents of 'node' at least up to the point at which it can be
* safely passed to _del_HashNode().
*/
node->symbol.name = NULL;
node->symbol.code = code;
node->symbol.fn = fn;
node->symbol.data = data;
node->symbol.del_fn = del_fn;
node->next = NULL;
/*
* Allocate a copy of 'name'.
*/
len = strlen(name) + 1;
node->symbol.name = _new_StringMemString(hash->mem->string_memory, len);
if(!node->symbol.name)
return _del_HashNode(hash, node);
/*
* If character-case is insignificant in the current table, convert the
* name to lower case while copying it.
*/
if(hash->case_sensitive) {
strlcpy(node->symbol.name, name, len);
} else {
const char *src = name;
char *dst = node->symbol.name;
for( ; *src; src++,dst++)
*dst = tolower(*src);
*dst = '\0';
};
return node;
}
/*.......................................................................
* Private function used to delete a hash-table node.
* The node must have been removed from its list before calling this
* function.
*
* Input:
* hash HashTable * The table for which the node was originally
* allocated.
* node HashNode * The node to be deleted.
* Output:
* return HashNode * The deleted node (always NULL).
*/
static HashNode *_del_HashNode(HashTable *hash, HashNode *node)
{
if(node) {
node->symbol.name = _del_StringMemString(hash->mem->string_memory,
node->symbol.name);
/*
* Call the user-supplied data-destructor if provided.
*/
if(node->symbol.data && node->symbol.del_fn)
node->symbol.data = node->symbol.del_fn(hash->app_data,
node->symbol.code,
node->symbol.data);
/*
* Return the node to the free-list.
*/
node->next = NULL;
node = (HashNode *) _del_FreeListNode(hash->mem->node_memory, node);
};
return NULL;
}
/*.......................................................................
* Private function to locate the hash bucket associated with a given
* name.
*
* This uses a hash-function described in the dragon-book
* ("Compilers - Principles, Techniques and Tools", by Aho, Sethi and
* Ullman; pub. Adison Wesley) page 435.
*
* Input:
* hash HashTable * The table to look up the string in.
* name const char * The name of the symbol to look up.
* Output:
* return HashBucket * The located hash-bucket.
*/
static HashBucket *_find_HashBucket(HashTable *hash, const char *name)
{
unsigned const char *kp;
unsigned long h = 0L;
if(hash->case_sensitive) {
for(kp=(unsigned const char *) name; *kp; kp++)
h = 65599UL * h + *kp; /* 65599 is a prime close to 2^16 */
} else {
for(kp=(unsigned const char *) name; *kp; kp++)
h = 65599UL * h + tolower((int)*kp); /* 65599 is a prime close to 2^16 */
};
return hash->bucket + (h % hash->size);
}
/*.......................................................................
* Search for a given name in the entries of a given bucket.
*
* Input:
* hash HashTable * The hash-table being searched.
* bucket HashBucket * The bucket to search (use _find_HashBucket()).
* name const char * The name to search for.
* Output:
* prev HashNode ** If prev!=NULL then the pointer to the node
* preceding the located node in the list will
* be recorded in *prev. This will be NULL either
* if the name is not found or the located node is
* at the head of the list of entries.
* return HashNode * The located hash-table node, or NULL if not
* found.
*/
static HashNode *_find_HashNode(HashTable *hash, HashBucket *bucket,
const char *name, HashNode **prev)
{
HashNode *last; /* The previously searched node */
HashNode *node; /* The node that is being searched */
/*
* Search the list for a node containing the specified name.
*/
for(last=NULL, node=bucket->head;
node && hash->keycmp(node->symbol.name, name)!=0;
last = node, node=node->next)
;
if(prev)
*prev = node ? last : NULL;
return node;
}
/*.......................................................................
* When hash->case_sensitive is zero this function is called
* in place of strcmp(). In such cases the hash-table names are stored
* as lower-case versions of the original strings so this function
* performs the comparison against lower-case copies of the characters
* of the string being compared.
*
* Input:
* node_key const char * The lower-case hash-node key being compared
* against.
* look_key const char * The lookup key.
* Output:
* return int <0 if node_key < look_key.
* 0 if node_key == look_key.
* >0 if node_key > look_key.
*/
static int _ht_lower_strcmp(const char *node_key, const char *look_key)
{
int cn; /* The latest character from node_key[] */
int cl; /* The latest character from look_key[] */
do {
cn = *node_key++;
cl = *look_key++;
} while(cn && cn==tolower(cl));
return cn - tolower(cl);
}
/*.......................................................................
* This is a wrapper around strcmp for comparing hash-keys in a case
* sensitive manner. The reason for having this wrapper, instead of using
* strcmp() directly, is to make some C++ compilers happy. The problem
* is that when the library is compiled with a C++ compiler, the
* declaration of the comparison function is a C++ declaration, whereas
* strcmp() is a pure C function and thus although it appears to have the
* same declaration, the compiler disagrees.
*
* Input:
* node_key char * The lower-case hash-node key being compared against.
* look_key char * The lookup key.
* Output:
* return int <0 if node_key < look_key.
* 0 if node_key == look_key.
* >0 if node_key > look_key.
*/
static int _ht_strcmp(const char *node_key, const char *look_key)
{
return strcmp(node_key, look_key);
}
/*.......................................................................
* Empty a hash-table by deleting all of its entries.
*
* Input:
* hash HashTable * The hash table to clear.
* Output:
* return int 0 - OK.
* 1 - Invalid arguments.
*/
int _clear_HashTable(HashTable *hash)
{
int i;
/*
* Check the arguments.
*/
if(!hash)
return 1;
/*
* Clear the contents of the bucket array.
*/
for(i=0; i<hash->size; i++) {
HashBucket *bucket = hash->bucket + i;
/*
* Delete the list of active hash nodes from the bucket.
*/
HashNode *node = bucket->head;
while(node) {
HashNode *next = node->next;
(void) _del_HashNode(hash, node);
node = next;
};
/*
* Mark the bucket as empty.
*/
bucket->head = NULL;
bucket->count = 0;
};
return 0;
}
/*.......................................................................
* Execute a given function on each entry of a hash table, returning
* before completion if the the specified function returns non-zero.
*
* Input:
* hash HashTable * The table to traverse.
* scan_fn HASH_SCAN_FN(*) The function to call.
* context void * Optional caller-specific context data
* to be passed to scan_fn().
* Output:
* return int 0 - OK.
* 1 - Either the arguments were invalid, or
* scan_fn() returned non-zero at some
* point.
*/
int _scan_HashTable(HashTable *hash, HASH_SCAN_FN(*scan_fn), void *context)
{
int i;
/*
* Check the arguments.
*/
if(!hash || !scan_fn)
return 1;
/*
* Iterate through the buckets of the table.
*/
for(i=0; i<hash->size; i++) {
HashBucket *bucket = hash->bucket + i;
HashNode *node;
/*
* Iterate through the list of symbols that fall into bucket i,
* passing each one to the caller-specified function.
*/
for(node=bucket->head; node; node=node->next) {
if(scan_fn(&node->symbol, context))
return 1;
};
};
return 0;
}
#ifndef hash_h
#define hash_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* The following macro can be used to prototype or define a
* function that deletes the data of a symbol-table entry.
*
* Input:
* app_data void * The _new_HashTable() app_data argument.
* code int The Symbol::code argument.
* sym_data void * The Symbol::data argument to be deleted.
* Output:
* return void * The deleted data (always return NULL).
*/
#define SYM_DEL_FN(fn) void *(fn)(void *app_data, int code, void *sym_data)
/*
* The following macro can be used to prototype or define a
* function that deletes the application-data of a hash-table.
*
* Input:
* data void * The _new_HashTable() 'app_data' argument to be
* deleted.
* Output:
* return void * The deleted data (always return NULL).
*/
#define HASH_DEL_FN(fn) void *(fn)(void *app_data)
/*
* The following is a container for recording the context
* of a symbol in a manner that is independant of the particular
* symbol-table implementation. Each hash-table entry contains
* the following user supplied parameters:
*
* 1. An optional integral parameter 'code'. This is useful for
* enumerating a symbol or for describing what type of data
* or function is stored in the symbol.
*
* 2. An optional generic function pointer. This is useful for
* associating functions with names. The user is responsible
* for casting between the generic function type and the
* actual function type. The code field could be used to
* enumerate what type of function to cast to.
*
* 3. An optional generic pointer to a static or heap-allocated
* object. It is up to the user to cast this back to the
* appropriate object type. Again, the code field could be used
* to describe what type of object is stored there.
* If the object is dynamically allocated and should be discarded
* when the symbol is deleted from the symbol table, send a
* destructor function to have it deleted automatically.
*/
typedef struct {
char *name; /* The name of the symbol */
int code; /* Application supplied integral code */
void (*fn)(void); /* Application supplied generic function */
void *data; /* Application supplied context data */
SYM_DEL_FN(*del_fn); /* Data destructor function */
} Symbol;
/*
* HashNode's and HashTable's are small objects. Separately allocating
* many such objects would normally cause memory fragmentation. To
* counter this, HashMemory objects are used. These contain
* dedicated free-lists formed from large dynamically allocated arrays
* of objects. One HashMemory object can be shared between multiple hash
* tables (within a single thread).
*/
typedef struct HashMemory HashMemory;
/* Create a free-list for allocation of hash tables and their nodes */
HashMemory *_new_HashMemory(int hash_count, int node_count);
/* Delete a redundant free-list if not being used */
HashMemory *_del_HashMemory(HashMemory *mem, int force);
/*
* Declare an alias for the private HashTable structure defined in
* hash.c.
*/
typedef struct HashTable HashTable;
/*
* Enumerate case-sensitivity options.
*/
typedef enum {
IGNORE_CASE, /* Ignore case when looking up symbols */
HONOUR_CASE /* Honor case when looking up symbols */
} HashCase;
/* Create a new hash-table */
HashTable *_new_HashTable(HashMemory *mem, int size, HashCase hcase,
void *app_data, HASH_DEL_FN(*del_fn));
/* Delete a reference to a hash-table */
HashTable *_del_HashTable(HashTable *hash);
/* Add an entry to a hash table */
Symbol *_new_HashSymbol(HashTable *hash, const char *key, int code,
void (*fn)(void), void *data, SYM_DEL_FN(*del_fn));
/* Remove and delete all the entries in a given hash table */
int _clear_HashTable(HashTable *hash);
/* Remove and delete a given hash-table entry */
Symbol *_del_HashSymbol(HashTable *hash, const char *key);
/* Lookup a given hash-table entry */
Symbol *_find_HashSymbol(HashTable *hash, const char *key);
/* Execute a given function on each entry of a hash table, returning */
/* before completion if the specified function returns non-zero. */
#define HASH_SCAN_FN(fn) int (fn)(Symbol *sym, void *context)
int _scan_HashTable(HashTable *hash, HASH_SCAN_FN(*scan_fn), void *context);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>
#include "ioutil.h"
#include "history.h"
#include "freelist.h"
#include "errmsg.h"
/*
* History lines are split into sub-strings of GLH_SEG_SIZE
* characters. To avoid wasting space in the GlhLineSeg structure,
* this should be a multiple of the size of a pointer.
*/
#define GLH_SEG_SIZE 16
/*
* GlhLineSeg structures contain fixed sized segments of a larger
* string. These are linked into lists to record strings, with all but
* the last segment having GLH_SEG_SIZE characters. The last segment
* of a string is terminated within the GLH_SEG_SIZE characters with a
* '\0'.
*/
typedef struct GlhLineSeg GlhLineSeg;
struct GlhLineSeg {
GlhLineSeg *next; /* The next sub-string of the history line */
char s[GLH_SEG_SIZE]; /* The sub-string. Beware that only the final */
/* substring of a line, as indicated by 'next' */
/* being NULL, is '\0' terminated. */
};
/*
* History lines are recorded in a hash table, such that repeated
* lines are stored just once.
*
* Start by defining the size of the hash table. This should be a
* prime number.
*/
#define GLH_HASH_SIZE 113
typedef struct GlhHashBucket GlhHashBucket;
/*
* Each history line will be represented in the hash table by a
* structure of the following type.
*/
typedef struct GlhHashNode GlhHashNode;
struct GlhHashNode {
GlhHashBucket *bucket; /* The parent hash-table bucket of this node */
GlhHashNode *next; /* The next in the list of nodes within the */
/* parent hash-table bucket. */
GlhLineSeg *head; /* The list of sub-strings which make up a line */
int len; /* The length of the line, excluding any '\0' */
int used; /* The number of times this string is pointed to by */
/* the time-ordered list of history lines. */
int reported; /* A flag that is used when searching to ensure that */
/* a line isn't reported redundantly. */
};
/*
* How many new GlhHashNode elements should be allocated at a time?
*/
#define GLH_HASH_INCR 50
static int _glh_is_line(GlhHashNode *hash, const char *line, size_t n);
static int _glh_line_matches_prefix(GlhHashNode *line, GlhHashNode *prefix);
static void _glh_return_line(GlhHashNode *hash, char *line, size_t dim);
/*
* All history lines which hash to a given bucket in the hash table, are
* recorded in a structure of the following type.
*/
struct GlhHashBucket {
GlhHashNode *lines; /* The list of history lines which fall in this bucket */
};
static GlhHashBucket *glh_find_bucket(GlHistory *glh, const char *line,
size_t n);
static GlhHashNode *glh_find_hash_node(GlhHashBucket *bucket, const char *line,
size_t n);
typedef struct {
FreeList *node_mem; /* A free-list of GlhHashNode structures */
GlhHashBucket bucket[GLH_HASH_SIZE]; /* The buckets of the hash table */
} GlhLineHash;
/*
* GlhLineNode's are used to record history lines in time order.
*/
typedef struct GlhLineNode GlhLineNode;
struct GlhLineNode {
long id; /* The unique identifier of this history line */
time_t timestamp; /* The time at which the line was archived */
unsigned group; /* The identifier of the history group to which the */
/* the line belongs. */
GlhLineNode *next; /* The next youngest line in the list */
GlhLineNode *prev; /* The next oldest line in the list */
GlhHashNode *line; /* The hash-table entry of the history line */
};
/*
* The number of GlhLineNode elements per freelist block.
*/
#define GLH_LINE_INCR 100
/*
* Encapsulate the time-ordered list of historical lines.
*/
typedef struct {
FreeList *node_mem; /* A freelist of GlhLineNode objects */
GlhLineNode *head; /* The oldest line in the list */
GlhLineNode *tail; /* The newest line in the list */
} GlhLineList;
/*
* The _glh_lookup_history() returns copies of history lines in a
* dynamically allocated array. This array is initially allocated
* GLH_LOOKUP_SIZE bytes. If subsequently this size turns out to be
* too small, realloc() is used to increase its size to the required
* size plus GLH_LOOKUP_MARGIN. The idea of the later parameter is to
* reduce the number of realloc() operations needed.
*/
#define GLH_LBUF_SIZE 300
#define GLH_LBUF_MARGIN 100
/*
* Encapsulate all of the resources needed to store historical input lines.
*/
struct GlHistory {
ErrMsg *err; /* The error-reporting buffer */
GlhLineSeg *buffer; /* An array of sub-line nodes to be partitioned */
/* into lists of sub-strings recording input lines. */
int nbuff; /* The allocated dimension of buffer[] */
GlhLineSeg *unused; /* The list of free nodes in buffer[] */
GlhLineList list; /* A time ordered list of history lines */
GlhLineNode *recall; /* The last line recalled, or NULL if no recall */
/* session is currently active. */
GlhLineNode *id_node;/* The node at which the last ID search terminated */
GlhLineHash hash; /* A hash-table of reference-counted history lines */
GlhHashNode *prefix; /* A pointer to a line containing the prefix that */
/* is being searched for. Note that if prefix==NULL */
/* and prefix_len>0, this means that no line in */
/* the buffer starts with the requested prefix. */
int prefix_len; /* The length of the prefix being searched for. */
char *lbuf; /* The array in which _glh_lookup_history() returns */
/* history lines */
int lbuf_dim; /* The allocated size of lbuf[] */
int nbusy; /* The number of line segments in buffer[] that are */
/* currently being used to record sub-lines */
int nfree; /* The number of line segments in buffer that are */
/* not currently being used to record sub-lines */
unsigned long seq; /* The next ID to assign to a line node */
unsigned group; /* The identifier of the current history group */
int nline; /* The number of lines currently in the history list */
int max_lines; /* Either -1 or a ceiling on the number of lines */
int enable; /* If false, ignore history additions and lookups */
};
#ifndef WITHOUT_FILE_SYSTEM
static int _glh_cant_load_history(GlHistory *glh, const char *filename,
int lineno, const char *message, FILE *fp);
static int _glh_cant_save_history(GlHistory *glh, const char *message,
const char *filename, FILE *fp);
static int _glh_write_timestamp(FILE *fp, time_t timestamp);
static int _glh_decode_timestamp(char *string, char **endp, time_t *timestamp);
#endif
static void _glh_discard_line(GlHistory *glh, GlhLineNode *node);
static GlhLineNode *_glh_find_id(GlHistory *glh, GlhLineID id);
static GlhHashNode *_glh_acquire_copy(GlHistory *glh, const char *line,
size_t n);
static GlhHashNode *_glh_discard_copy(GlHistory *glh, GlhHashNode *hnode);
static int _glh_prepare_for_recall(GlHistory *glh, char *line);
/*
* The following structure and functions are used to iterate through
* the characters of a segmented history line.
*/
typedef struct {
GlhLineSeg *seg; /* The line segment that the next character will */
/* be returned from. */
int posn; /* The index in the above line segment, containing */
/* the next unread character. */
char c; /* The current character in the input line */
} GlhLineStream;
static void glh_init_stream(GlhLineStream *str, GlhHashNode *line);
static void glh_step_stream(GlhLineStream *str);
/*
* See if search prefix contains any globbing characters.
*/
static int glh_contains_glob(GlhHashNode *prefix);
/*
* Match a line against a search pattern.
*/
static int glh_line_matches_glob(GlhLineStream *lstr, GlhLineStream *pstr);
static int glh_matches_range(char c, GlhLineStream *pstr);
/*.......................................................................
* Create a line history maintenance object.
*
* Input:
* buflen size_t The number of bytes to allocate to the
* buffer that is used to record all of the
* most recent lines of user input that will fit.
* If buflen==0, no buffer will be allocated.
* Output:
* return GlHistory * The new object, or NULL on error.
*/
GlHistory *_new_GlHistory(size_t buflen)
{
GlHistory *glh; /* The object to be returned */
int i;
/*
* Allocate the container.
*/
glh = (GlHistory *) malloc(sizeof(GlHistory));
if(!glh) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_GlHistory().
*/
glh->err = NULL;
glh->buffer = NULL;
glh->nbuff = (buflen+GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
glh->unused = NULL;
glh->list.node_mem = NULL;
glh->list.head = glh->list.tail = NULL;
glh->recall = NULL;
glh->id_node = NULL;
glh->hash.node_mem = NULL;
for(i=0; i<GLH_HASH_SIZE; i++)
glh->hash.bucket[i].lines = NULL;
glh->prefix = NULL;
glh->lbuf = NULL;
glh->lbuf_dim = 0;
glh->nbusy = 0;
glh->nfree = glh->nbuff;
glh->seq = 0;
glh->group = 0;
glh->nline = 0;
glh->max_lines = -1;
glh->enable = 1;
/*
* Allocate a place to record error messages.
*/
glh->err = _new_ErrMsg();
if(!glh->err)
return _del_GlHistory(glh);
/*
* Allocate the buffer, if required.
*/
if(glh->nbuff > 0) {
glh->nbuff = glh->nfree;
glh->buffer = (GlhLineSeg *) malloc(sizeof(GlhLineSeg) * glh->nbuff);
if(!glh->buffer) {
errno = ENOMEM;
return _del_GlHistory(glh);
};
/*
* All nodes of the buffer are currently unused, so link them all into
* a list and make glh->unused point to the head of this list.
*/
glh->unused = glh->buffer;
for(i=0; i<glh->nbuff-1; i++) {
GlhLineSeg *seg = glh->unused + i;
seg->next = seg + 1;
};
glh->unused[i].next = NULL;
};
/*
* Allocate the GlhLineNode freelist.
*/
glh->list.node_mem = _new_FreeList(sizeof(GlhLineNode), GLH_LINE_INCR);
if(!glh->list.node_mem)
return _del_GlHistory(glh);
/*
* Allocate the GlhHashNode freelist.
*/
glh->hash.node_mem = _new_FreeList(sizeof(GlhLineNode), GLH_HASH_INCR);
if(!glh->hash.node_mem)
return _del_GlHistory(glh);
/*
* Allocate the array that _glh_lookup_history() uses to return a
* copy of a given history line. This will be resized when necessary.
*/
glh->lbuf_dim = GLH_LBUF_SIZE;
glh->lbuf = (char *) malloc(glh->lbuf_dim);
if(!glh->lbuf) {
errno = ENOMEM;
return _del_GlHistory(glh);
};
return glh;
}
/*.......................................................................
* Delete a GlHistory object.
*
* Input:
* glh GlHistory * The object to be deleted.
* Output:
* return GlHistory * The deleted object (always NULL).
*/
GlHistory *_del_GlHistory(GlHistory *glh)
{
if(glh) {
/*
* Delete the error-message buffer.
*/
glh->err = _del_ErrMsg(glh->err);
/*
* Delete the buffer.
*/
if(glh->buffer) {
free(glh->buffer);
glh->buffer = NULL;
glh->unused = NULL;
};
/*
* Delete the freelist of GlhLineNode's.
*/
glh->list.node_mem = _del_FreeList(glh->list.node_mem, 1);
/*
* The contents of the list were deleted by deleting the freelist.
*/
glh->list.head = NULL;
glh->list.tail = NULL;
/*
* Delete the freelist of GlhHashNode's.
*/
glh->hash.node_mem = _del_FreeList(glh->hash.node_mem, 1);
/*
* Delete the lookup buffer.
*/
if(glh->lbuf)
free(glh->lbuf);
/*
* Delete the container.
*/
free(glh);
};
return NULL;
}
/*.......................................................................
* Append a new line to the history list, deleting old lines to make
* room, if needed.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The line to be archived.
* force int Unless this flag is non-zero, empty lines aren't
* archived. This flag requests that the line be
* archived regardless.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_add_history(GlHistory *glh, const char *line, int force)
{
int slen; /* The length of the line to be recorded (minus the '\0') */
int empty; /* True if the string is empty */
const char *nlptr; /* A pointer to a newline character in line[] */
GlhHashNode *hnode; /* The hash-table node of the line */
GlhLineNode *lnode; /* A node in the time-ordered list of lines */
int i;
/*
* Check the arguments.
*/
if(!glh || !line) {
errno = EINVAL;
return 1;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return 0;
/*
* Cancel any ongoing search.
*/
if(_glh_cancel_search(glh))
return 1;
/*
* How long is the string to be recorded, being careful not to include
* any terminating '\n' character.
*/
nlptr = strchr(line, '\n');
if(nlptr)
slen = (nlptr - line);
else
slen = strlen(line);
/*
* Is the line empty?
*/
empty = 1;
for(i=0; i<slen && empty; i++)
empty = isspace((int)(unsigned char) line[i]);
/*
* If the line is empty, don't add it to the buffer unless explicitly
* told to.
*/
if(empty && !force)
return 0;
/*
* Has an upper limit to the number of lines in the history list been
* specified?
*/
if(glh->max_lines >= 0) {
/*
* If necessary, remove old lines until there is room to add one new
* line without exceeding the specified line limit.
*/
while(glh->nline > 0 && glh->nline >= glh->max_lines)
_glh_discard_line(glh, glh->list.head);
/*
* We can't archive the line if the maximum number of lines allowed is
* zero.
*/
if(glh->max_lines == 0)
return 0;
};
/*
* Unless already stored, store a copy of the line in the history buffer,
* then return a reference-counted hash-node pointer to this copy.
*/
hnode = _glh_acquire_copy(glh, line, slen);
if(!hnode) {
_err_record_msg(glh->err, "No room to store history line", END_ERR_MSG);
errno = ENOMEM;
return 1;
};
/*
* Allocate a new node in the time-ordered list of lines.
*/
lnode = (GlhLineNode *) _new_FreeListNode(glh->list.node_mem);
/*
* If a new line-node couldn't be allocated, discard our copy of the
* stored line before reporting the error.
*/
if(!lnode) {
hnode = _glh_discard_copy(glh, hnode);
_err_record_msg(glh->err, "No room to store history line", END_ERR_MSG);
errno = ENOMEM;
return 1;
};
/*
* Record a pointer to the hash-table record of the line in the new
* list node.
*/
lnode->id = glh->seq++;
lnode->timestamp = time(NULL);
lnode->group = glh->group;
lnode->line = hnode;
/*
* Append the new node to the end of the time-ordered list.
*/
if(glh->list.head)
glh->list.tail->next = lnode;
else
glh->list.head = lnode;
lnode->next = NULL;
lnode->prev = glh->list.tail;
glh->list.tail = lnode;
/*
* Record the addition of a line to the list.
*/
glh->nline++;
return 0;
}
/*.......................................................................
* Recall the next oldest line that has the search prefix last recorded
* by _glh_search_prefix().
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The input line buffer. On input this should contain
* the current input line, and on output, if anything
* was found, its contents will have been replaced
* with the matching line.
* dim size_t The allocated dimension of the line buffer.
* Output:
* return char * A pointer to line[0], or NULL if not found.
*/
char *_glh_find_backwards(GlHistory *glh, char *line, size_t dim)
{
GlhLineNode *node; /* The line location node being checked */
GlhHashNode *old_line; /* The previous recalled line */
/*
* Check the arguments.
*/
if(!glh || !line) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return NULL;
/*
* Check the line dimensions.
*/
if(dim < strlen(line) + 1) {
_err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Preserve the input line if needed.
*/
if(_glh_prepare_for_recall(glh, line))
return NULL;
/*
* From where should we start the search?
*/
if(glh->recall) {
node = glh->recall->prev;
old_line = glh->recall->line;
} else {
node = glh->list.tail;
old_line = NULL;
};
/*
* Search backwards through the list for the first match with the
* prefix string that differs from the last line that was recalled.
*/
while(node && (node->group != glh->group || node->line == old_line ||
!_glh_line_matches_prefix(node->line, glh->prefix)))
node = node->prev;
/*
* Was a matching line found?
*/
if(node) {
/*
* Recall the found node as the starting point for subsequent
* searches.
*/
glh->recall = node;
/*
* Copy the matching line into the provided line buffer.
*/
_glh_return_line(node->line, line, dim);
/*
* Return it.
*/
return line;
};
/*
* No match was found.
*/
return NULL;
}
/*.......................................................................
* Recall the next newest line that has the search prefix last recorded
* by _glh_search_prefix().
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The input line buffer. On input this should contain
* the current input line, and on output, if anything
* was found, its contents will have been replaced
* with the matching line.
* dim size_t The allocated dimensions of the line buffer.
* Output:
* return char * The line requested, or NULL if no matching line
* was found.
*/
char *_glh_find_forwards(GlHistory *glh, char *line, size_t dim)
{
GlhLineNode *node; /* The line location node being checked */
GlhHashNode *old_line; /* The previous recalled line */
/*
* Check the arguments.
*/
if(!glh || !line) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return NULL;
/*
* Check the line dimensions.
*/
if(dim < strlen(line) + 1) {
_err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* From where should we start the search?
*/
if(glh->recall) {
node = glh->recall->next;
old_line = glh->recall->line;
} else {
return NULL;
};
/*
* Search forwards through the list for the first match with the
* prefix string.
*/
while(node && (node->group != glh->group || node->line == old_line ||
!_glh_line_matches_prefix(node->line, glh->prefix)))
node = node->next;
/*
* Was a matching line found?
*/
if(node) {
/*
* Copy the matching line into the provided line buffer.
*/
_glh_return_line(node->line, line, dim);
/*
* Record the starting point of the next search.
*/
glh->recall = node;
/*
* If we just returned the line that was being entered when the search
* session first started, cancel the search.
*/
if(node == glh->list.tail)
_glh_cancel_search(glh);
/*
* Return the matching line to the user.
*/
return line;
};
/*
* No match was found.
*/
return NULL;
}
/*.......................................................................
* If a search is in progress, cancel it.
*
* This involves discarding the line that was temporarily saved by
* _glh_find_backwards() when the search was originally started,
* and reseting the search iteration pointer to NULL.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_cancel_search(GlHistory *glh)
{
/*
* Check the arguments.
*/
if(!glh) {
errno = EINVAL;
return 1;
};
/*
* If there wasn't a search in progress, do nothing.
*/
if(!glh->recall)
return 0;
/*
* Reset the search pointers. Note that it is essential to set
* glh->recall to NULL before calling _glh_discard_line(), to avoid an
* infinite recursion.
*/
glh->recall = NULL;
/*
* Delete the node of the preserved line.
*/
_glh_discard_line(glh, glh->list.tail);
return 0;
}
/*.......................................................................
* Set the prefix of subsequent history searches.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line const char * The command line who's prefix is to be used.
* prefix_len int The length of the prefix.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_search_prefix(GlHistory *glh, const char *line, int prefix_len)
{
/*
* Check the arguments.
*/
if(!glh) {
errno = EINVAL;
return 1;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return 0;
/*
* Discard any existing prefix.
*/
glh->prefix = _glh_discard_copy(glh, glh->prefix);
/*
* Only store a copy of the prefix string if it isn't a zero-length string.
*/
if(prefix_len > 0) {
/*
* Get a reference-counted copy of the prefix from the history cache buffer.
*/
glh->prefix = _glh_acquire_copy(glh, line, prefix_len);
/*
* Was there insufficient buffer space?
*/
if(!glh->prefix) {
_err_record_msg(glh->err, "The search prefix is too long to store",
END_ERR_MSG);
errno = ENOMEM;
return 1;
};
};
return 0;
}
/*.......................................................................
* Recall the oldest recorded line.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The input line buffer. On input this should contain
* the current input line, and on output, its contents
* will have been replaced with the oldest line.
* dim size_t The allocated dimensions of the line buffer.
* Output:
* return char * A pointer to line[0], or NULL if not found.
*/
char *_glh_oldest_line(GlHistory *glh, char *line, size_t dim)
{
GlhLineNode *node; /* The line location node being checked */
/*
* Check the arguments.
*/
if(!glh || !line) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return NULL;
/*
* Check the line dimensions.
*/
if(dim < strlen(line) + 1) {
_err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Preserve the input line if needed.
*/
if(_glh_prepare_for_recall(glh, line))
return NULL;
/*
* Locate the oldest line that belongs to the current group.
*/
for(node=glh->list.head; node && node->group != glh->group;
node = node->next)
;
/*
* No line found?
*/
if(!node)
return NULL;
/*
* Record the above node as the starting point for subsequent
* searches.
*/
glh->recall = node;
/*
* Copy the recalled line into the provided line buffer.
*/
_glh_return_line(node->line, line, dim);
/*
* If we just returned the line that was being entered when the search
* session first started, cancel the search.
*/
if(node == glh->list.tail)
_glh_cancel_search(glh);
return line;
}
/*.......................................................................
* Recall the line that was being entered when the search started.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The input line buffer. On input this should contain
* the current input line, and on output, its contents
* will have been replaced with the line that was
* being entered when the search was started.
* dim size_t The allocated dimensions of the line buffer.
* Output:
* return char * A pointer to line[0], or NULL if not found.
*/
char *_glh_current_line(GlHistory *glh, char *line, size_t dim)
{
/*
* Check the arguments.
*/
if(!glh || !line) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* If history isn't enabled, or no history search has yet been started,
* ignore the call.
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0 || !glh->recall)
return NULL;
/*
* Check the line dimensions.
*/
if(dim < strlen(line) + 1) {
_err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
END_ERR_MSG);
errno = EINVAL;
return NULL;
};
/*
* Copy the recalled line into the provided line buffer.
*/
_glh_return_line(glh->list.tail->line, line, dim);
/*
* Since we have returned to the starting point of the search, cancel it.
*/
_glh_cancel_search(glh);
return line;
}
/*.......................................................................
* Query the id of a history line offset by a given number of lines from
* the one that is currently being recalled. If a recall session isn't
* in progress, or the offset points outside the history list, 0 is
* returned.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* offset int The line offset (0 for the current line, < 0
* for an older line, > 0 for a newer line.
* Output:
* return GlhLineID The identifier of the line that is currently
* being recalled, or 0 if no recall session is
* currently in progress.
*/
GlhLineID _glh_line_id(GlHistory *glh, int offset)
{
GlhLineNode *node; /* The line location node being checked */
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return 0;
/*
* Search forward 'offset' lines to find the required line.
*/
if(offset >= 0) {
for(node=glh->recall; node && offset != 0; node=node->next) {
if(node->group == glh->group)
offset--;
};
} else {
for(node=glh->recall; node && offset != 0; node=node->prev) {
if(node->group == glh->group)
offset++;
};
};
return node ? node->id : 0;
}
/*.......................................................................
* Recall a line by its history buffer ID. If the line is no longer
* in the buffer, or the id is zero, NULL is returned.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* id GlhLineID The ID of the line to be returned.
* line char * The input line buffer. On input this should contain
* the current input line, and on output, its contents
* will have been replaced with the saved line.
* dim size_t The allocated dimensions of the line buffer.
* Output:
* return char * A pointer to line[0], or NULL if not found.
*/
char *_glh_recall_line(GlHistory *glh, GlhLineID id, char *line, size_t dim)
{
GlhLineNode *node; /* The line location node being checked */
/*
* Is history enabled?
*/
if(!glh->enable || !glh->buffer || glh->max_lines == 0)
return NULL;
/*
* Preserve the input line if needed.
*/
if(_glh_prepare_for_recall(glh, line))
return NULL;
/*
* Search for the specified line.
*/
node = _glh_find_id(glh, id);
/*
* Not found?
*/
if(!node || node->group != glh->group)
return NULL;
/*
* Record the node of the matching line as the starting point
* for subsequent searches.
*/
glh->recall = node;
/*
* Copy the recalled line into the provided line buffer.
*/
_glh_return_line(node->line, line, dim);
return line;
}
/*.......................................................................
* Save the current history in a specified file.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* filename const char * The name of the new file to record the
* history in.
* comment const char * Extra information such as timestamps will
* be recorded on a line started with this
* string, the idea being that the file can
* double as a command file. Specify "" if
* you don't care.
* max_lines int The maximum number of lines to save, or -1
* to save all of the lines in the history
* list.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_save_history(GlHistory *glh, const char *filename, const char *comment,
int max_lines)
{
#ifdef WITHOUT_FILE_SYSTEM
_err_record_msg(glh->err, "Can't save history without filesystem access",
END_ERR_MSG);
errno = EINVAL;
return 1;
#else
FILE *fp; /* The output file */
GlhLineNode *node; /* The line being saved */
GlhLineNode *head; /* The head of the list of lines to be saved */
GlhLineSeg *seg; /* One segment of a line being saved */
/*
* Check the arguments.
*/
if(!glh || !filename || !comment) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Attempt to open the specified file.
*/
fp = fopen(filename, "w");
if(!fp)
return _glh_cant_save_history(glh, "Can't open", filename, NULL);
/*
* If a ceiling on the number of lines to save was specified, count
* that number of lines backwards, to find the first line to be saved.
*/
head = NULL;
if(max_lines >= 0) {
for(head=glh->list.tail; head && --max_lines > 0; head=head->prev)
;
};
if(!head)
head = glh->list.head;
/*
* Write the contents of the history buffer to the history file, writing
* associated data such as timestamps, to a line starting with the
* specified comment string.
*/
for(node=head; node; node=node->next) {
/*
* Write peripheral information associated with the line, as a comment.
*/
if(fprintf(fp, "%s ", comment) < 0 ||
_glh_write_timestamp(fp, node->timestamp) ||
fprintf(fp, " %u\n", node->group) < 0) {
return _glh_cant_save_history(glh, "Error writing", filename, fp);
};
/*
* Write the history line.
*/
for(seg=node->line->head; seg; seg=seg->next) {
size_t slen = seg->next ? GLH_SEG_SIZE : strlen(seg->s);
if(fwrite(seg->s, sizeof(char), slen, fp) != slen)
return _glh_cant_save_history(glh, "Error writing", filename, fp);
};
fputc('\n', fp);
};
/*
* Close the history file.
*/
if(fclose(fp) == EOF)
return _glh_cant_save_history(glh, "Error writing", filename, NULL);
return 0;
#endif
}
#ifndef WITHOUT_FILE_SYSTEM
/*.......................................................................
* This is a private error return function of _glh_save_history(). It
* composes an error report in the error buffer, composed using
* sprintf("%s %s (%s)", message, filename, strerror(errno)). It then
* closes fp and returns the error return code of _glh_save_history().
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* message const char * A message to be followed by the filename.
* filename const char * The name of the offending output file.
* fp FILE * The stream to be closed (send NULL if not
* open).
* Output:
* return int Always 1.
*/
static int _glh_cant_save_history(GlHistory *glh, const char *message,
const char *filename, FILE *fp)
{
_err_record_msg(glh->err, message, filename, " (",
strerror(errno), ")", END_ERR_MSG);
if(fp)
(void) fclose(fp);
return 1;
}
/*.......................................................................
* Write a timestamp to a given stdio stream, in the format
* yyyymmddhhmmss
*
* Input:
* fp FILE * The stream to write to.
* timestamp time_t The timestamp to be written.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _glh_write_timestamp(FILE *fp, time_t timestamp)
{
struct tm *t; /* THe broken-down calendar time */
/*
* Get the calendar components corresponding to the given timestamp.
*/
if(timestamp < 0 || (t = localtime(×tamp)) == NULL) {
if(fprintf(fp, "?") < 0)
return 1;
return 0;
};
/*
* Write the calendar time as yyyymmddhhmmss.
*/
if(fprintf(fp, "%04d%02d%02d%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1,
t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec) < 0)
return 1;
return 0;
}
#endif
/*.......................................................................
* Restore previous history lines from a given file.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* filename const char * The name of the file to read from.
* comment const char * The same comment string that was passed to
* _glh_save_history() when this file was
* written.
* line char * A buffer into which lines can be read.
* dim size_t The allocated dimension of line[].
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_load_history(GlHistory *glh, const char *filename, const char *comment,
char *line, size_t dim)
{
#ifdef WITHOUT_FILE_SYSTEM
_err_record_msg(glh->err, "Can't load history without filesystem access",
END_ERR_MSG);
errno = EINVAL;
return 1;
#else
FILE *fp; /* The output file */
size_t comment_len; /* The length of the comment string */
time_t timestamp; /* The timestamp of the history line */
unsigned group; /* The identifier of the history group to which */
/* the line belongs. */
int lineno; /* The line number being read */
/*
* Check the arguments.
*/
if(!glh || !filename || !comment || !line) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Measure the length of the comment string.
*/
comment_len = strlen(comment);
/*
* Clear the history list.
*/
_glh_clear_history(glh, 1);
/*
* Attempt to open the specified file. Don't treat it as an error
* if the file doesn't exist.
*/
fp = fopen(filename, "r");
if(!fp)
return 0;
/*
* Attempt to read each line and preceding peripheral info, and add these
* to the history list.
*/
for(lineno=1; fgets(line, dim, fp) != NULL; lineno++) {
char *lptr; /* A pointer into the input line */
/*
* Check that the line starts with the comment string.
*/
if(strncmp(line, comment, comment_len) != 0) {
return _glh_cant_load_history(glh, filename, lineno,
"Corrupt history parameter line", fp);
};
/*
* Skip spaces and tabs after the comment.
*/
for(lptr=line+comment_len; *lptr && (*lptr==' ' || *lptr=='\t'); lptr++)
;
/*
* The next word must be a timestamp.
*/
if(_glh_decode_timestamp(lptr, &lptr, ×tamp)) {
return _glh_cant_load_history(glh, filename, lineno,
"Corrupt timestamp", fp);
};
/*
* Skip spaces and tabs.
*/
while(*lptr==' ' || *lptr=='\t')
lptr++;
/*
* The next word must be an unsigned integer group number.
*/
group = (int) strtoul(lptr, &lptr, 10);
if(*lptr != ' ' && *lptr != '\n') {
return _glh_cant_load_history(glh, filename, lineno,
"Corrupt group id", fp);
};
/*
* Skip spaces and tabs.
*/
while(*lptr==' ' || *lptr=='\t')
lptr++;
/*
* There shouldn't be anything left on the line.
*/
if(*lptr != '\n') {
return _glh_cant_load_history(glh, filename, lineno,
"Corrupt parameter line", fp);
};
/*
* Now read the history line itself.
*/
lineno++;
if(fgets(line, dim, fp) == NULL)
return _glh_cant_load_history(glh, filename, lineno, "Read error", fp);
/*
* Append the line to the history buffer.
*/
if(_glh_add_history(glh, line, 1)) {
return _glh_cant_load_history(glh, filename, lineno,
"Insufficient memory to record line", fp);
};
/*
* Record the group and timestamp information along with the line.
*/
if(glh->list.tail) {
glh->list.tail->timestamp = timestamp;
glh->list.tail->group = group;
};
};
/*
* Close the file.
*/
(void) fclose(fp);
return 0;
#endif
}
#ifndef WITHOUT_FILE_SYSTEM
/*.......................................................................
* This is a private error return function of _glh_load_history().
*/
static int _glh_cant_load_history(GlHistory *glh, const char *filename,
int lineno, const char *message, FILE *fp)
{
char lnum[20];
/*
* Convert the line number to a string.
*/
snprintf(lnum, sizeof(lnum), "%d", lineno);
/*
* Render an error message.
*/
_err_record_msg(glh->err, filename, ":", lnum, ":", message, END_ERR_MSG);
/*
* Close the file.
*/
if(fp)
(void) fclose(fp);
return 1;
}
/*.......................................................................
* Read a timestamp from a string.
*
* Input:
* string char * The string to read from.
* Input/Output:
* endp char ** On output *endp will point to the next unprocessed
* character in string[].
* timestamp time_t * The timestamp will be assigned to *t.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _glh_decode_timestamp(char *string, char **endp, time_t *timestamp)
{
unsigned year,month,day,hour,min,sec; /* Calendar time components */
struct tm t;
/*
* There are 14 characters in the date format yyyymmddhhmmss.
*/
enum {TSLEN=14};
char timestr[TSLEN+1]; /* The timestamp part of the string */
/*
* If the time wasn't available at the time that the line was recorded
* it will have been written as "?". Check for this before trying
* to read the timestamp.
*/
if(string[0] == '\?') {
*endp = string+1;
*timestamp = -1;
return 0;
};
/*
* The timestamp is expected to be written in the form yyyymmddhhmmss.
*/
if(strlen(string) < TSLEN) {
*endp = string;
return 1;
};
/*
* Copy the timestamp out of the string.
*/
strncpy(timestr, string, TSLEN);
timestr[TSLEN] = '\0';
/*
* Decode the timestamp.
*/
if(sscanf(timestr, "%4u%2u%2u%2u%2u%2u", &year, &month, &day, &hour, &min,
&sec) != 6) {
*endp = string;
return 1;
};
/*
* Advance the string pointer over the successfully read timestamp.
*/
*endp = string + TSLEN;
/*
* Copy the read values into a struct tm.
*/
t.tm_sec = sec;
t.tm_min = min;
t.tm_hour = hour;
t.tm_mday = day;
t.tm_wday = 0;
t.tm_yday = 0;
t.tm_mon = month - 1;
t.tm_year = year - 1900;
t.tm_isdst = -1;
/*
* Convert the contents of the struct tm to a time_t.
*/
*timestamp = mktime(&t);
return 0;
}
#endif
/*.......................................................................
* Switch history groups.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* group unsigned The new group identifier. This will be recorded
* with subsequent history lines, and subsequent
* history searches will only return lines with
* this group identifier. This allows multiple
* separate history lists to exist within
* a single GlHistory object. Note that the
* default group identifier is 0.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_set_group(GlHistory *glh, unsigned group)
{
/*
* Check the arguments.
*/
if(!glh) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Is the group being changed?
*/
if(group != glh->group) {
/*
* Cancel any ongoing search.
*/
if(_glh_cancel_search(glh))
return 1;
/*
* Record the new group.
*/
glh->group = group;
};
return 0;
}
/*.......................................................................
* Query the current history group.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Output:
* return unsigned The group identifier.
*/
int _glh_get_group(GlHistory *glh)
{
return glh ? glh->group : 0;
}
/*.......................................................................
* Display the contents of the history list.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* write_fn GlWriteFn * The function to call to write the line, or
* 0 to discard the output.
* data void * Anonymous data to pass to write_fn().
* fmt const char * A format string. This can contain arbitrary
* characters, which are written verbatim, plus
* any of the following format directives:
* %D - The date, like 2001-11-20
* %T - The time of day, like 23:59:59
* %N - The sequential entry number of the
* line in the history buffer.
* %G - The history group number of the line.
* %% - A literal % character.
* %H - The history line.
* all_groups int If true, display history lines from all
* history groups. Otherwise only display
* those of the current history group.
* max_lines int If max_lines is < 0, all available lines
* are displayed. Otherwise only the most
* recent max_lines lines will be displayed.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _glh_show_history(GlHistory *glh, GlWriteFn *write_fn, void *data,
const char *fmt, int all_groups, int max_lines)
{
GlhLineNode *node; /* The line being displayed */
GlhLineNode *oldest; /* The oldest line to display */
GlhLineSeg *seg; /* One segment of a line being displayed */
enum {TSMAX=32}; /* The maximum length of the date and time string */
char buffer[TSMAX+1]; /* The buffer in which to write the date and time */
int idlen; /* The length of displayed ID strings */
unsigned grpmax; /* The maximum group number in the buffer */
int grplen; /* The number of characters needed to print grpmax */
int len; /* The length of a string to be written */
/*
* Check the arguments.
*/
if(!glh || !write_fn || !fmt) {
if(glh)
_err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
errno = EINVAL;
return 1;
};
/*
* Is history enabled?
*/
if(!glh->enable || !glh->list.head)
return 0;
/*
* Work out the length to display ID numbers, choosing the length of
* the biggest number in the buffer. Smaller numbers will be padded
* with leading zeroes if needed.
*/
snprintf(buffer, sizeof(buffer), "%lu", (unsigned long) glh->list.tail->id);
idlen = strlen(buffer);
/*
* Find the largest group number.
*/
grpmax = 0;
for(node=glh->list.head; node; node=node->next) {
if(node->group > grpmax)
grpmax = node->group;
};
/*
* Find out how many characters are needed to display the group number.
*/
snprintf(buffer, sizeof(buffer), "%u", (unsigned) grpmax);
grplen = strlen(buffer);
/*
* Find the node that follows the oldest line to be displayed.
*/
if(max_lines < 0) {
oldest = glh->list.head;
} else if(max_lines==0) {
return 0;
} else {
for(oldest=glh->list.tail; oldest; oldest=oldest->prev) {
if((all_groups || oldest->group == glh->group) && --max_lines <= 0)
break;
};
/*
* If the number of lines in the buffer doesn't exceed the specified
* maximum, start from the oldest line in the buffer.
*/
if(!oldest)
oldest = glh->list.head;
};
/*
* List the history lines in increasing time order.
*/
for(node=oldest; node; node=node->next) {
/*
* Only display lines from the current history group, unless
* told otherwise.
*/
if(all_groups || node->group == glh->group) {
const char *fptr; /* A pointer into the format string */
struct tm *t = NULL; /* The broken time version of the timestamp */
/*
* Work out the calendar representation of the node timestamp.
*/
if(node->timestamp != (time_t) -1)
t = localtime(&node->timestamp);
/*
* Parse the format string.
*/
fptr = fmt;
while(*fptr) {
/*
* Search for the start of the next format directive or the end of the string.
*/
const char *start = fptr;
while(*fptr && *fptr != '%')
fptr++;
/*
* Display any literal characters that precede the located directive.
*/
if(fptr > start) {
len = (int) (fptr - start);
if(write_fn(data, start, len) != len)
return 1;
};
/*
* Did we hit a new directive before the end of the line?
*/
if(*fptr) {
/*
* Obey the directive. Ignore unknown directives.
*/
switch(*++fptr) {
case 'D': /* Display the date */
if(t && strftime(buffer, TSMAX, "%Y-%m-%d", t) != 0) {
len = strlen(buffer);
if(write_fn(data, buffer, len) != len)
return 1;
};
break;
case 'T': /* Display the time of day */
if(t && strftime(buffer, TSMAX, "%H:%M:%S", t) != 0) {
len = strlen(buffer);
if(write_fn(data, buffer, len) != len)
return 1;
};
break;
case 'N': /* Display the sequential entry number */
snprintf(buffer, sizeof(buffer), "%*lu", idlen, (unsigned long) node->id);
len = strlen(buffer);
if(write_fn(data, buffer, len) != len)
return 1;
break;
case 'G':
snprintf(buffer, sizeof(buffer), "%*u", grplen, (unsigned) node->group);
len = strlen(buffer);
if(write_fn(data, buffer, len) != len)
return 1;
break;
case 'H': /* Display the history line */
for(seg=node->line->head; seg; seg=seg->next) {
len = seg->next ? GLH_SEG_SIZE : strlen(seg->s);
if(write_fn(data, seg->s, len) != len)
return 1;
};
break;
case '%': /* A literal % symbol */
if(write_fn(data, "%", 1) != 1)
return 1;
break;
};
/*
* Skip the directive.
*/
if(*fptr)
fptr++;
};
};
};
};
return 0;
}
/*.......................................................................
* Change the size of the history buffer.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* bufsize size_t The number of bytes in the history buffer, or 0
* to delete the buffer completely.
* Output:
* return int 0 - OK.
* 1 - Insufficient memory (the previous buffer
* will have been retained). No error message
* will be displayed.
*/
int _glh_resize_history(GlHistory *glh, size_t bufsize)
{
int nbuff; /* The number of segments in the new buffer */
int i;
/*
* Check the arguments.
*/
if(!glh) {
errno = EINVAL;
return 1;
};
/*
* How many buffer segments does the requested buffer size correspond
* to?
*/
nbuff = (bufsize+GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
/*
* Has a different size than the current size been requested?
*/
if(glh->nbuff != nbuff) {
/*
* Cancel any ongoing search.
*/
(void) _glh_cancel_search(glh);
/*
* Create a wholly new buffer?
*/
if(glh->nbuff == 0 && nbuff>0) {
glh->buffer = (GlhLineSeg *) malloc(sizeof(GlhLineSeg) * nbuff);
if(!glh->buffer)
return 1;
glh->nbuff = nbuff;
glh->nfree = glh->nbuff;
glh->nbusy = 0;
glh->nline = 0;
/*
* Link the currently unused nodes of the buffer into a list.
*/
glh->unused = glh->buffer;
for(i=0; i<glh->nbuff-1; i++) {
GlhLineSeg *seg = glh->unused + i;
seg->next = seg + 1;
};
glh->unused[i].next = NULL;
/*
* Delete an existing buffer?
*/
} else if(nbuff == 0) {
_glh_clear_history(glh, 1);
free(glh->buffer);
glh->buffer = NULL;
glh->unused = NULL;
glh->nbuff = 0;
glh->nfree = 0;
glh->nbusy = 0;
glh->nline = 0;
/*
* Change from one finite buffer size to another?
*/
} else {
GlhLineSeg *buffer; /* The resized buffer */
int nbusy; /* The number of used line segments in the new buffer */
/*
* Starting from the oldest line in the buffer, discard lines until
* the buffer contains at most 'nbuff' used line segments.
*/
while(glh->list.head && glh->nbusy > nbuff)
_glh_discard_line(glh, glh->list.head);
/*
* Attempt to allocate a new buffer.
*/
buffer = (GlhLineSeg *) malloc(nbuff * sizeof(GlhLineSeg));
if(!buffer) {
errno = ENOMEM;
return 1;
};
/*
* Copy the used segments of the old buffer to the start of the new buffer.
*/
nbusy = 0;
for(i=0; i<GLH_HASH_SIZE; i++) {
GlhHashBucket *b = glh->hash.bucket + i;
GlhHashNode *hnode;
for(hnode=b->lines; hnode; hnode=hnode->next) {
GlhLineSeg *seg = hnode->head;
hnode->head = buffer + nbusy;
for( ; seg; seg=seg->next) {
buffer[nbusy] = *seg;
buffer[nbusy].next = seg->next ? &buffer[nbusy+1] : NULL;
nbusy++;
};
};
};
/*
* Make a list of the new buffer's unused segments.
*/
for(i=nbusy; i<nbuff-1; i++)
buffer[i].next = &buffer[i+1];
if(i < nbuff)
buffer[i].next = NULL;
/*
* Discard the old buffer.
*/
free(glh->buffer);
/*
* Install the new buffer.
*/
glh->buffer = buffer;
glh->nbuff = nbuff;
glh->nbusy = nbusy;
glh->nfree = nbuff - nbusy;
glh->unused = glh->nfree > 0 ? (buffer + nbusy) : NULL;
};
};
return 0;
}
/*.......................................................................
* Set an upper limit to the number of lines that can be recorded in the
* history list, or remove a previously specified limit.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* max_lines int The maximum number of lines to allow, or -1 to
* cancel a previous limit and allow as many lines
* as will fit in the current history buffer size.
*/
void _glh_limit_history(GlHistory *glh, int max_lines)
{
if(!glh)
return;
/*
* Apply a new limit?
*/
if(max_lines >= 0 && max_lines != glh->max_lines) {
/*
* Count successively older lines until we reach the start of the
* list, or until we have seen max_lines lines (at which point 'node'
* will be line number max_lines+1).
*/
int nline = 0;
GlhLineNode *node;
for(node=glh->list.tail; node && ++nline <= max_lines; node=node->prev)
;
/*
* Discard any lines that exceed the limit.
*/
if(node) {
GlhLineNode *oldest = node->next; /* The oldest line to be kept */
/*
* Delete nodes from the head of the list until we reach the node that
* is to be kept.
*/
while(glh->list.head && glh->list.head != oldest)
_glh_discard_line(glh, glh->list.head);
};
};
/*
* Record the new limit.
*/
glh->max_lines = max_lines;
return;
}
/*.......................................................................
* Discard either all history, or the history associated with the current
* history group.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* all_groups int If true, clear all of the history. If false,
* clear only the stored lines associated with the
* currently selected history group.
*/
void _glh_clear_history(GlHistory *glh, int all_groups)
{
int i;
/*
* Check the arguments.
*/
if(!glh)
return;
/*
* Cancel any ongoing search.
*/
(void) _glh_cancel_search(glh);
/*
* Delete all history lines regardless of group?
*/
if(all_groups) {
/*
* Claer the time-ordered list of lines.
*/
_rst_FreeList(glh->list.node_mem);
glh->list.head = glh->list.tail = NULL;
glh->nline = 0;
glh->id_node = NULL;
/*
* Clear the hash table.
*/
for(i=0; i<GLH_HASH_SIZE; i++)
glh->hash.bucket[i].lines = NULL;
_rst_FreeList(glh->hash.node_mem);
/*
* Move all line segment nodes back onto the list of unused segments.
*/
if(glh->buffer) {
glh->unused = glh->buffer;
for(i=0; i<glh->nbuff-1; i++) {
GlhLineSeg *seg = glh->unused + i;
seg->next = seg + 1;
};
glh->unused[i].next = NULL;
glh->nfree = glh->nbuff;
glh->nbusy = 0;
} else {
glh->unused = NULL;
glh->nbusy = glh->nfree = 0;
};
/*
* Just delete lines of the current group?
*/
} else {
GlhLineNode *node; /* The line node being checked */
GlhLineNode *next; /* The line node that follows 'node' */
/*
* Search out and delete the line nodes of the current group.
*/
for(node=glh->list.head; node; node=next) {
/*
* Keep a record of the following node before we delete the current
* node.
*/
next = node->next;
/*
* Discard this node?
*/
if(node->group == glh->group)
_glh_discard_line(glh, node);
};
};
return;
}
/*.......................................................................
* Temporarily enable or disable the history list.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* enable int If true, turn on the history mechanism. If
* false, disable it.
*/
void _glh_toggle_history(GlHistory *glh, int enable)
{
if(glh)
glh->enable = enable;
}
/*.......................................................................
* Discard a given archived input line.
*
* Input:
* glh GlHistory * The history container object.
* node GlhLineNode * The line to be discarded, specified via its
* entry in the time-ordered list of historical
* input lines.
*/
static void _glh_discard_line(GlHistory *glh, GlhLineNode *node)
{
/*
* Remove the node from the linked list.
*/
if(node->prev)
node->prev->next = node->next;
else
glh->list.head = node->next;
if(node->next)
node->next->prev = node->prev;
else
glh->list.tail = node->prev;
/*
* If we are deleting the node that is marked as the start point of the
* last ID search, remove the cached starting point.
*/
if(node == glh->id_node)
glh->id_node = NULL;
/*
* If we are deleting the node that is marked as the start point of the
* next prefix search, cancel the search.
*/
if(node == glh->recall)
_glh_cancel_search(glh);
/*
* Delete our copy of the line.
*/
node->line = _glh_discard_copy(glh, node->line);
/*
* Return the node to the freelist.
*/
(void) _del_FreeListNode(glh->list.node_mem, node);
/*
* Record the removal of a line from the list.
*/
glh->nline--;
return;
}
/*.......................................................................
* Lookup the details of a given history line, given its id.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* id GlLineID The sequential number of the line.
* Input/Output:
* line const char ** A pointer to a copy of the history line will be
* assigned to *line. Beware that this pointer may
* be invalidated by the next call to any public
* history function.
* group unsigned * The group membership of the line will be assigned
* to *group.
* timestamp time_t * The timestamp of the line will be assigned to
* *timestamp.
* Output:
* return int 0 - The requested line wasn't found.
* 1 - The line was found.
*/
int _glh_lookup_history(GlHistory *glh, GlhLineID id, const char **line,
unsigned *group, time_t *timestamp)
{
GlhLineNode *node; /* The located line location node */
/*
* Check the arguments.
*/
if(!glh)
return 0;
/*
* Search for the line that has the specified ID.
*/
node = _glh_find_id(glh, id);
/*
* Not found?
*/
if(!node)
return 0;
/*
* Has the history line been requested?
*/
if(line) {
/*
* If necessary, reallocate the lookup buffer to accomodate the size of
* a copy of the located line.
*/
if(node->line->len + 1 > glh->lbuf_dim) {
int lbuf_dim = node->line->len + 1;
char *lbuf = realloc(glh->lbuf, lbuf_dim);
if(!lbuf) {
errno = ENOMEM;
return 0;
};
glh->lbuf_dim = lbuf_dim;
glh->lbuf = lbuf;
};
/*
* Copy the history line into the lookup buffer.
*/
_glh_return_line(node->line, glh->lbuf, glh->lbuf_dim);
/*
* Assign the lookup buffer as the returned line pointer.
*/
*line = glh->lbuf;
};
/*
* Does the caller want to know the group of the line?
*/
if(group)
*group = node->group;
/*
* Does the caller want to know the timestamp of the line?
*/
if(timestamp)
*timestamp = node->timestamp;
return 1;
}
/*.......................................................................
* Lookup a node in the history list by its ID.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* id GlhLineID The ID of the line to be returned.
* Output:
* return GlhLIneNode * The located node, or NULL if not found.
*/
static GlhLineNode *_glh_find_id(GlHistory *glh, GlhLineID id)
{
GlhLineNode *node; /* The node being checked */
/*
* Is history enabled?
*/
if(!glh->enable || !glh->list.head)
return NULL;
/*
* If possible, start at the end point of the last ID search.
* Otherwise start from the head of the list.
*/
node = glh->id_node;
if(!node)
node = glh->list.head;
/*
* Search forwards from 'node'?
*/
if(node->id < id) {
while(node && node->id != id)
node = node->next;
glh->id_node = node ? node : glh->list.tail;
/*
* Search backwards from 'node'?
*/
} else {
while(node && node->id != id)
node = node->prev;
glh->id_node = node ? node : glh->list.head;
};
/*
* Return the located node (this will be NULL if the ID wasn't found).
*/
return node;
}
/*.......................................................................
* Query the state of the history list. Note that any of the input/output
* pointers can be specified as NULL.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Input/Output:
* enabled int * If history is enabled, *enabled will be
* set to 1. Otherwise it will be assigned 0.
* group unsigned * The current history group ID will be assigned
* to *group.
* max_lines int * The currently requested limit on the number
* of history lines in the list, or -1 if
* unlimited.
*/
void _glh_state_of_history(GlHistory *glh, int *enabled, unsigned *group,
int *max_lines)
{
if(glh) {
if(enabled)
*enabled = glh->enable;
if(group)
*group = glh->group;
if(max_lines)
*max_lines = glh->max_lines;
};
}
/*.......................................................................
* Get the range of lines in the history buffer.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Input/Output:
* oldest unsigned long * The sequential entry number of the oldest
* line in the history list will be assigned
* to *oldest, unless there are no lines, in
* which case 0 will be assigned.
* newest unsigned long * The sequential entry number of the newest
* line in the history list will be assigned
* to *newest, unless there are no lines, in
* which case 0 will be assigned.
* nlines int * The number of lines currently in the history
* list.
*/
void _glh_range_of_history(GlHistory *glh, unsigned long *oldest,
unsigned long *newest, int *nlines)
{
if(glh) {
if(oldest)
*oldest = glh->list.head ? glh->list.head->id : 0;
if(newest)
*newest = glh->list.tail ? glh->list.tail->id : 0;
if(nlines)
*nlines = glh->nline;
};
}
/*.......................................................................
* Return the size of the history buffer and the amount of the
* buffer that is currently in use.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Input/Output:
* buff_size size_t * The size of the history buffer (bytes).
* buff_used size_t * The amount of the history buffer that
* is currently occupied (bytes).
*/
void _glh_size_of_history(GlHistory *glh, size_t *buff_size, size_t *buff_used)
{
if(glh) {
if(buff_size)
*buff_size = (glh->nbusy + glh->nfree) * GLH_SEG_SIZE;
/*
* Determine the amount of buffer space that is currently occupied.
*/
if(buff_used)
*buff_used = glh->nbusy * GLH_SEG_SIZE;
};
}
/*.......................................................................
* Return extra information (ie. in addition to that provided by errno)
* about the last error to occur in any of the public functions of this
* module.
*
* Input:
* glh GlHistory * The container of the history list.
* Output:
* return const char * A pointer to the internal buffer in which
* the error message is temporarily stored.
*/
const char *_glh_last_error(GlHistory *glh)
{
return glh ? _err_get_msg(glh->err) : "NULL GlHistory argument";
}
/*.......................................................................
* Unless already stored, store a copy of the line in the history buffer,
* then return a reference-counted hash-node pointer to this copy.
*
* Input:
* glh GlHistory * The history maintenance buffer.
* line const char * The history line to be recorded.
* n size_t The length of the string, excluding any '\0'
* terminator.
* Output:
* return GlhHashNode * The hash-node containing the stored line, or
* NULL on error.
*/
static GlhHashNode *_glh_acquire_copy(GlHistory *glh, const char *line,
size_t n)
{
GlhHashBucket *bucket; /* The hash-table bucket of the line */
GlhHashNode *hnode; /* The hash-table node of the line */
int i;
/*
* In which bucket should the line be recorded?
*/
bucket = glh_find_bucket(glh, line, n);
/*
* Is the line already recorded there?
*/
hnode = glh_find_hash_node(bucket, line, n);
/*
* If the line isn't recorded in the buffer yet, make room for it.
*/
if(!hnode) {
GlhLineSeg *seg; /* A line segment */
int offset; /* An offset into line[] */
/*
* How many string segments will be needed to record the new line,
* including space for a '\0' terminator?
*/
int nseg = ((n+1) + GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
/*
* Discard the oldest history lines in the buffer until at least
* 'nseg' segments have been freed up, or until we run out of buffer
* space.
*/
while(glh->nfree < nseg && glh->nbusy > 0)
_glh_discard_line(glh, glh->list.head);
/*
* If the buffer is smaller than the new line, don't attempt to truncate
* it to fit. Simply don't archive it.
*/
if(glh->nfree < nseg)
return NULL;
/*
* Record the line in the first 'nseg' segments of the list of unused segments.
*/
offset = 0;
for(i=0,seg=glh->unused; i<nseg-1; i++,seg=seg->next, offset+=GLH_SEG_SIZE)
memcpy(seg->s, line + offset, GLH_SEG_SIZE);
memcpy(seg->s, line + offset, n-offset);
seg->s[n-offset] = '\0';
/*
* Create a new hash-node for the line.
*/
hnode = (GlhHashNode *) _new_FreeListNode(glh->hash.node_mem);
if(!hnode)
return NULL;
/*
* Move the copy of the line from the list of unused segments to
* the hash node.
*/
hnode->head = glh->unused;
glh->unused = seg->next;
seg->next = NULL;
glh->nbusy += nseg;
glh->nfree -= nseg;
/*
* Prepend the new hash node to the list within the associated bucket.
*/
hnode->next = bucket->lines;
bucket->lines = hnode;
/*
* Initialize the rest of the members of the hash node.
*/
hnode->len = n;
hnode->reported = 0;
hnode->used = 0;
hnode->bucket = bucket;
};
/*
* Increment the reference count of the line.
*/
hnode->used++;
return hnode;
}
/*.......................................................................
* Decrement the reference count of the history line of a given hash-node,
* and if the count reaches zero, delete both the hash-node and the
* buffered copy of the line.
*
* Input:
* glh GlHistory * The history container object.
* hnode GlhHashNode * The node to be removed.
* Output:
* return GlhHashNode * The deleted hash-node (ie. NULL).
*/
static GlhHashNode *_glh_discard_copy(GlHistory *glh, GlhHashNode *hnode)
{
if(hnode) {
GlhHashBucket *bucket = hnode->bucket;
/*
* If decrementing the reference count of the hash-node doesn't reduce
* the reference count to zero, then the line is still in use in another
* object, so don't delete it yet. Return NULL to indicate that the caller's
* access to the hash-node copy has been deleted.
*/
if(--hnode->used >= 1)
return NULL;
/*
* Remove the hash-node from the list in its parent bucket.
*/
if(bucket->lines == hnode) {
bucket->lines = hnode->next;
} else {
GlhHashNode *prev; /* The node which precedes hnode in the bucket */
for(prev=bucket->lines; prev && prev->next != hnode; prev=prev->next)
;
if(prev)
prev->next = hnode->next;
};
hnode->next = NULL;
/*
* Return the line segments of the hash-node to the list of unused segments.
*/
if(hnode->head) {
GlhLineSeg *tail; /* The last node in the list of line segments */
int nseg; /* The number of segments being discarded */
/*
* Get the last node of the list of line segments referenced in the hash-node,
* while counting the number of line segments used.
*/
for(nseg=1,tail=hnode->head; tail->next; nseg++,tail=tail->next)
;
/*
* Prepend the list of line segments used by the hash node to the
* list of unused line segments.
*/
tail->next = glh->unused;
glh->unused = hnode->head;
glh->nbusy -= nseg;
glh->nfree += nseg;
};
/*
* Return the container of the hash-node to the freelist.
*/
hnode = (GlhHashNode *) _del_FreeListNode(glh->hash.node_mem, hnode);
};
return NULL;
}
/*.......................................................................
* Private function to locate the hash bucket associated with a given
* history line.
*
* This uses a hash-function described in the dragon-book
* ("Compilers - Principles, Techniques and Tools", by Aho, Sethi and
* Ullman; pub. Adison Wesley) page 435.
*
* Input:
* glh GlHistory * The history container object.
* line const char * The historical line to look up.
* n size_t The length of the line in line[], excluding
* any '\0' terminator.
* Output:
* return GlhHashBucket * The located hash-bucket.
*/
static GlhHashBucket *glh_find_bucket(GlHistory *glh, const char *line,
size_t n)
{
unsigned long h = 0L;
int i;
for(i=0; i<n; i++) {
unsigned char c = line[i];
h = 65599UL * h + c; /* 65599 is a prime close to 2^16 */
};
return glh->hash.bucket + (h % GLH_HASH_SIZE);
}
/*.......................................................................
* Find a given history line within a given hash-table bucket.
*
* Input:
* bucket GlhHashBucket * The hash-table bucket in which to search.
* line const char * The historical line to lookup.
* n size_t The length of the line in line[], excluding
* any '\0' terminator.
* Output:
* return GlhHashNode * The hash-table entry of the line, or NULL
* if not found.
*/
static GlhHashNode *glh_find_hash_node(GlhHashBucket *bucket, const char *line,
size_t n)
{
GlhHashNode *node; /* A node in the list of lines in the bucket */
/*
* Compare each of the lines in the list of lines, against 'line'.
*/
for(node=bucket->lines; node; node=node->next) {
if(_glh_is_line(node, line, n))
return node;
};
return NULL;
}
/*.......................................................................
* Return non-zero if a given string is equal to a given segmented line
* node.
*
* Input:
* hash GlhHashNode * The hash-table entry of the line.
* line const char * The string to be compared to the segmented
* line.
* n size_t The length of the line in line[], excluding
* any '\0' terminator.
* Output:
* return int 0 - The lines differ.
* 1 - The lines are the same.
*/
static int _glh_is_line(GlhHashNode *hash, const char *line, size_t n)
{
GlhLineSeg *seg; /* A node in the list of line segments */
int i;
/*
* Do the two lines have the same length?
*/
if(n != hash->len)
return 0;
/*
* Compare the characters of the segmented and unsegmented versions
* of the line.
*/
for(seg=hash->head; n>0 && seg; seg=seg->next) {
const char *s = seg->s;
for(i=0; n>0 && i<GLH_SEG_SIZE; i++,n--) {
if(*line++ != *s++)
return 0;
};
};
return 1;
}
/*.......................................................................
* Return non-zero if a given line has the specified segmented search
* prefix.
*
* Input:
* line GlhHashNode * The line to be compared against the prefix.
* prefix GlhHashNode * The search prefix, or NULL to match any string.
* Output:
* return int 0 - The line doesn't have the specified prefix.
* 1 - The line has the specified prefix.
*/
static int _glh_line_matches_prefix(GlhHashNode *line, GlhHashNode *prefix)
{
GlhLineStream lstr; /* The stream that is used to traverse 'line' */
GlhLineStream pstr; /* The stream that is used to traverse 'prefix' */
/*
* When prefix==NULL, this means that the nul string
* is to be matched, and this matches all lines.
*/
if(!prefix)
return 1;
/*
* Wrap the two history lines that are to be compared in iterator
* stream objects.
*/
glh_init_stream(&lstr, line);
glh_init_stream(&pstr, prefix);
/*
* If the prefix contains a glob pattern, match the prefix as a glob
* pattern.
*/
if(glh_contains_glob(prefix))
return glh_line_matches_glob(&lstr, &pstr);
/*
* Is the prefix longer than the line being compared against it?
*/
if(prefix->len > line->len)
return 0;
/*
* Compare the line to the prefix.
*/
while(pstr.c != '\0' && pstr.c == lstr.c) {
glh_step_stream(&lstr);
glh_step_stream(&pstr);
};
/*
* Did we reach the end of the prefix string before finding
* any differences?
*/
return pstr.c == '\0';
}
/*.......................................................................
* Copy a given history line into a specified output string.
*
* Input:
* hash GlhHashNode The hash-table entry of the history line to
* be copied.
* line char * A copy of the history line.
* dim size_t The allocated dimension of the line buffer.
*/
static void _glh_return_line(GlhHashNode *hash, char *line, size_t dim)
{
GlhLineSeg *seg; /* A node in the list of line segments */
int i;
for(seg=hash->head; dim>0 && seg; seg=seg->next) {
const char *s = seg->s;
for(i=0; dim>0 && i<GLH_SEG_SIZE; i++,dim--)
*line++ = *s++;
};
/*
* If the line wouldn't fit in the output buffer, replace the last character
* with a '\0' terminator.
*/
if(dim==0)
line[-1] = '\0';
}
/*.......................................................................
* This function should be called whenever a new line recall is
* attempted. It preserves a copy of the current input line in the
* history list while other lines in the history list are being
* returned.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* line char * The current contents of the input line buffer.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _glh_prepare_for_recall(GlHistory *glh, char *line)
{
/*
* If a recall session has already been started, but we have returned
* to the preserved copy of the input line, if the user has changed
* this line, we should replace the preserved copy of the original
* input line with the new one. To do this simply cancel the session,
* so that a new session is started below.
*/
if(glh->recall && glh->recall == glh->list.tail &&
!_glh_is_line(glh->recall->line, line, strlen(line))) {
_glh_cancel_search(glh);
};
/*
* If this is the first line recall of a new recall session, save the
* current line for potential recall later, and mark it as the last
* line recalled.
*/
if(!glh->recall) {
if(_glh_add_history(glh, line, 1))
return 1;
glh->recall = glh->list.tail;
/*
* The above call to _glh_add_history() will have incremented the line
* sequence number, after adding the line. Since we only want this to
* to be incremented for permanently entered lines, decrement it again.
*/
glh->seq--;
};
return 0;
}
/*.......................................................................
* Return non-zero if a history search session is currently in progress.
*
* Input:
* glh GlHistory * The input-line history maintenance object.
* Output:
* return int 0 - No search is currently in progress.
* 1 - A search is in progress.
*/
int _glh_search_active(GlHistory *glh)
{
return glh && glh->recall;
}
/*.......................................................................
* Initialize a character iterator object to point to the start of a
* given history line. The first character of the line will be placed
* in str->c, and subsequent characters can be placed there by calling
* glh_strep_stream().
*
* Input:
* str GlhLineStream * The iterator object to be initialized.
* line GlhHashNode * The history line to be iterated over (a
* NULL value here, is interpretted as an
* empty string by glh_step_stream()).
*/
static void glh_init_stream(GlhLineStream *str, GlhHashNode *line)
{
str->seg = line ? line->head : NULL;
str->posn = 0;
str->c = str->seg ? str->seg->s[0] : '\0';
}
/*.......................................................................
* Copy the next unread character in the line being iterated, in str->c.
* Once the end of the history line has been reached, all futher calls
* set str->c to '\0'.
*
* Input:
* str GlhLineStream * The history-line iterator to read from.
*/
static void glh_step_stream(GlhLineStream *str)
{
/*
* Get the character from the current iterator position within the line.
*/
str->c = str->seg ? str->seg->s[str->posn] : '\0';
/*
* Unless we have reached the end of the string, move the iterator
* to the position of the next character in the line.
*/
if(str->c != '\0' && ++str->posn >= GLH_SEG_SIZE) {
str->posn = 0;
str->seg = str->seg->next;
};
}
/*.......................................................................
* Return non-zero if the specified search prefix contains any glob
* wildcard characters.
*
* Input:
* prefix GlhHashNode * The search prefix.
* Output:
* return int 0 - The prefix doesn't contain any globbing
* characters.
* 1 - The prefix contains at least one
* globbing character.
*/
static int glh_contains_glob(GlhHashNode *prefix)
{
GlhLineStream pstr; /* The stream that is used to traverse 'prefix' */
/*
* Wrap a stream iterator around the prefix, so that we can traverse it
* without worrying about line-segmentation.
*/
glh_init_stream(&pstr, prefix);
/*
* Search for unescaped wildcard characters.
*/
while(pstr.c != '\0') {
switch(pstr.c) {
case '\\': /* Skip escaped characters */
glh_step_stream(&pstr);
break;
case '*': case '?': case '[': /* A wildcard character? */
return 1;
break;
};
glh_step_stream(&pstr);
};
/*
* No wildcard characters were found.
*/
return 0;
}
/*.......................................................................
* Return non-zero if the history line matches a search prefix containing
* a glob pattern.
*
* Input:
* lstr GlhLineStream * The iterator stream being used to traverse
* the history line that is being matched.
* pstr GlhLineStream * The iterator stream being used to traverse
* the pattern.
* Output:
* return int 0 - Doesn't match.
* 1 - The line matches the pattern.
*/
static int glh_line_matches_glob(GlhLineStream *lstr, GlhLineStream *pstr)
{
/*
* Match each character of the pattern until we reach the end of the
* pattern.
*/
while(pstr->c != '\0') {
/*
* Handle the next character of the pattern.
*/
switch(pstr->c) {
/*
* A match zero-or-more characters wildcard operator.
*/
case '*':
/*
* Skip the '*' character in the pattern.
*/
glh_step_stream(pstr);
/*
* If the pattern ends with the '*' wildcard, then the
* rest of the line matches this.
*/
if(pstr->c == '\0')
return 1;
/*
* Using the wildcard to match successively longer sections of
* the remaining characters of the line, attempt to match
* the tail of the line against the tail of the pattern.
*/
while(lstr->c) {
GlhLineStream old_lstr = *lstr;
GlhLineStream old_pstr = *pstr;
if(glh_line_matches_glob(lstr, pstr))
return 1;
/*
* Restore the line and pattern iterators for a new try.
*/
*lstr = old_lstr;
*pstr = old_pstr;
/*
* Prepare to try again, one character further into the line.
*/
glh_step_stream(lstr);
};
return 0; /* The pattern following the '*' didn't match */
break;
/*
* A match-one-character wildcard operator.
*/
case '?':
/*
* If there is a character to be matched, skip it and advance the
* pattern pointer.
*/
if(lstr->c) {
glh_step_stream(lstr);
glh_step_stream(pstr);
/*
* If we hit the end of the line, there is no character
* matching the operator, so the pattern doesn't match.
*/
} else {
return 0;
};
break;
/*
* A character range operator, with the character ranges enclosed
* in matching square brackets.
*/
case '[':
glh_step_stream(pstr); /* Skip the '[' character */
if(!lstr->c || !glh_matches_range(lstr->c, pstr))
return 0;
glh_step_stream(lstr); /* Skip the character that matched */
break;
/*
* A backslash in the pattern prevents the following character as
* being seen as a special character.
*/
case '\\':
glh_step_stream(pstr); /* Skip the backslash */
/* Note fallthrough to default */
/*
* A normal character to be matched explicitly.
*/
/* FALLTHROUGH */
default:
if(lstr->c == pstr->c) {
glh_step_stream(lstr);
glh_step_stream(pstr);
} else {
return 0;
};
break;
};
};
/*
* To get here, pattern must have been exhausted. The line only
* matches the pattern if the line as also been exhausted.
*/
return pstr->c == '\0' && lstr->c == '\0';
}
/*.......................................................................
* Match a character range expression terminated by an unescaped close
* square bracket.
*
* Input:
* c char The character to be matched with the range
* pattern.
* pstr GlhLineStream * The iterator stream being used to traverse
* the pattern.
* Output:
* return int 0 - Doesn't match.
* 1 - The character matched.
*/
static int glh_matches_range(char c, GlhLineStream *pstr)
{
int invert = 0; /* True to invert the sense of the match */
int matched = 0; /* True if the character matched the pattern */
char lastc = '\0'; /* The previous character in the pattern */
/*
* If the first character is a caret, the sense of the match is
* inverted and only if the character isn't one of those in the
* range, do we say that it matches.
*/
if(pstr->c == '^') {
glh_step_stream(pstr);
invert = 1;
};
/*
* The hyphen is only a special character when it follows the first
* character of the range (not including the caret).
*/
if(pstr->c == '-') {
glh_step_stream(pstr);
if(c == '-')
matched = 1;
/*
* Skip other leading '-' characters since they make no sense.
*/
while(pstr->c == '-')
glh_step_stream(pstr);
};
/*
* The hyphen is only a special character when it follows the first
* character of the range (not including the caret or a hyphen).
*/
if(pstr->c == ']') {
glh_step_stream(pstr);
if(c == ']')
matched = 1;
};
/*
* Having dealt with the characters that have special meanings at
* the beginning of a character range expression, see if the
* character matches any of the remaining characters of the range,
* up until a terminating ']' character is seen.
*/
while(!matched && pstr->c && pstr->c != ']') {
/*
* Is this a range of characters signaled by the two end characters
* separated by a hyphen?
*/
if(pstr->c == '-') {
glh_step_stream(pstr); /* Skip the hyphen */
if(pstr->c != ']') {
if(c >= lastc && c <= pstr->c)
matched = 1;
};
/*
* A normal character to be compared directly.
*/
} else if(pstr->c == c) {
matched = 1;
};
/*
* Record and skip the character that we just processed.
*/
lastc = pstr->c;
if(pstr->c != ']')
glh_step_stream(pstr);
};
/*
* Find the terminating ']'.
*/
while(pstr->c && pstr->c != ']')
glh_step_stream(pstr);
/*
* Did we find a terminating ']'?
*/
if(pstr->c == ']') {
/*
* Skip the terminating ']'.
*/
glh_step_stream(pstr);
/*
* If the pattern started with a caret, invert the sense of the match.
*/
if(invert)
matched = !matched;
/*
* If the pattern didn't end with a ']', then it doesn't match,
* regardless of the value of the required sense of the match.
*/
} else {
matched = 0;
};
return matched;
}
#ifndef history_h
#define history_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdio.h> /* FILE * */
/*-----------------------------------------------------------------------
* This module is used to record and traverse historical lines of user input.
*/
typedef struct GlHistory GlHistory;
/*
* Create a new history maintenance object.
*/
GlHistory *_new_GlHistory(size_t buflen);
/*
* Delete a history maintenance object.
*/
GlHistory *_del_GlHistory(GlHistory *glh);
int _glh_add_history(GlHistory *glh, const char *line, int force);
int _glh_search_prefix(GlHistory *glh, const char *line, int prefix_len);
char *_glh_find_backwards(GlHistory *glh, char *line, size_t dim);
char *_glh_find_forwards(GlHistory *glh, char *line, size_t dim);
int _glh_cancel_search(GlHistory *glh);
char *_glh_oldest_line(GlHistory *glh, char *line, size_t dim);
char *_glh_current_line(GlHistory *glh, char *line, size_t dim);
/*
* Whenever a new line is added to the history buffer, it is given
* a unique ID, recorded in an object of the following type.
*/
typedef unsigned long GlhLineID;
/*
* Query the id of a history line offset by a given number of lines from
* the one that is currently being recalled. If a recall session isn't
* in progress, or the offset points outside the history list, 0 is
* returned.
*/
GlhLineID _glh_line_id(GlHistory *glh, int offset);
/*
* Recall a line by its history buffer ID. If the line is no longer
* in the buffer, or the specified id is zero, NULL is returned.
*/
char *_glh_recall_line(GlHistory *glh, GlhLineID id, char *line, size_t dim);
/*
* Write the contents of the history buffer to a given file. Note that
* ~ and $ expansion are not performed on the filename.
*/
int _glh_save_history(GlHistory *glh, const char *filename,
const char *comment, int max_lines);
/*
* Restore the contents of the history buffer from a given file.
* Note that ~ and $ expansion are not performed on the filename.
*/
int _glh_load_history(GlHistory *glh, const char *filename, const char *comment,
char *line, size_t dim);
/*
* Set and query the current history group.
*/
int _glh_set_group(GlHistory *glh, unsigned group);
int _glh_get_group(GlHistory *glh);
/*
* Display the contents of the history list to the specified stdio
* output group.
*/
int _glh_show_history(GlHistory *glh, GlWriteFn *write_fn, void *data,
const char *fmt, int all_groups, int max_lines);
/*
* Change the size of the history buffer.
*/
int _glh_resize_history(GlHistory *glh, size_t bufsize);
/*
* Set an upper limit to the number of lines that can be recorded in the
* history list, or remove a previously specified limit.
*/
void _glh_limit_history(GlHistory *glh, int max_lines);
/*
* Discard either all history, or the history associated with the current
* history group.
*/
void _glh_clear_history(GlHistory *glh, int all_groups);
/*
* Temporarily enable or disable the history facility.
*/
void _glh_toggle_history(GlHistory *glh, int enable);
/*
* Lookup a history line by its sequential number of entry in the
* history buffer.
*/
int _glh_lookup_history(GlHistory *glh, GlhLineID id, const char **line,
unsigned *group, time_t *timestamp);
/*
* Query the state of the history list.
*/
void _glh_state_of_history(GlHistory *glh, int *enabled, unsigned *group,
int *max_lines);
/*
* Get the range of lines in the history buffer.
*/
void _glh_range_of_history(GlHistory *glh, unsigned long *oldest,
unsigned long *newest, int *nlines);
/*
* Return the size of the history buffer and the amount of the
* buffer that is currently in use.
*/
void _glh_size_of_history(GlHistory *glh, size_t *buff_size, size_t *buff_used);
/*
* Get information about the last error in this module.
*/
const char *_glh_last_error(GlHistory *glh);
/*
* Return non-zero if a history search session is currently in progress.
*/
int _glh_search_active(GlHistory *glh);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include "pathutil.h"
#include "homedir.h"
#include "errmsg.h"
/*
* Use the reentrant POSIX threads versions of the password lookup functions?
*/
#if defined(PREFER_REENTRANT) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L
#define THREAD_COMPATIBLE 1
/*
* Under Solaris we can use thr_main() to determine whether
* threads are actually running, and thus when it is necessary
* to avoid non-reentrant features.
*/
#if defined __sun && defined __SVR4
#include <thread.h> /* Solaris thr_main() */
#endif
#endif
/*
* Provide a password buffer size fallback in case the max size reported
* by sysconf() is said to be indeterminate.
*/
#define DEF_GETPW_R_SIZE_MAX 1024
/*
* The resources needed to lookup and record a home directory are
* maintained in objects of the following type.
*/
struct HomeDir {
ErrMsg *err; /* The error message report buffer */
char *buffer; /* A buffer for reading password entries and */
/* directory paths. */
int buflen; /* The allocated size of buffer[] */
#ifdef THREAD_COMPATIBLE
struct passwd pwd; /* The password entry of a user */
#endif
};
static const char *hd_getpwd(HomeDir *home);
/*.......................................................................
* Create a new HomeDir object.
*
* Output:
* return HomeDir * The new object, or NULL on error.
*/
HomeDir *_new_HomeDir(void)
{
HomeDir *home; /* The object to be returned */
size_t pathlen; /* The estimated maximum size of a pathname */
/*
* Allocate the container.
*/
home = (HomeDir *) malloc(sizeof(HomeDir));
if(!home) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_HomeDir().
*/
home->err = NULL;
home->buffer = NULL;
home->buflen = 0;
/*
* Allocate a place to record error messages.
*/
home->err = _new_ErrMsg();
if(!home->err)
return _del_HomeDir(home);
/*
* Allocate the buffer that is used by the reentrant POSIX password-entry
* lookup functions.
*/
#ifdef THREAD_COMPATIBLE
/*
* Get the length of the buffer needed by the reentrant version
* of getpwnam().
*/
#ifndef _SC_GETPW_R_SIZE_MAX
home->buflen = DEF_GETPW_R_SIZE_MAX;
#else
errno = 0;
home->buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
/*
* If the limit isn't available, substitute a suitably large fallback value.
*/
if(home->buflen < 0 || errno)
home->buflen = DEF_GETPW_R_SIZE_MAX;
#endif
#endif
/*
* If the existing buffer length requirement is too restrictive to record
* a pathname, increase its length.
*/
pathlen = _pu_pathname_dim();
if(pathlen > home->buflen)
home->buflen = pathlen;
/*
* Allocate a work buffer.
*/
home->buffer = (char *) malloc(home->buflen);
if(!home->buffer) {
errno = ENOMEM;
return _del_HomeDir(home);
};
return home;
}
/*.......................................................................
* Delete a HomeDir object.
*
* Input:
* home HomeDir * The object to be deleted.
* Output:
* return HomeDir * The deleted object (always NULL).
*/
HomeDir *_del_HomeDir(HomeDir *home)
{
if(home) {
home->err = _del_ErrMsg(home->err);
if(home->buffer)
free(home->buffer);
free(home);
};
return NULL;
}
/*.......................................................................
* Lookup the home directory of a given user in the password file.
*
* Input:
* home HomeDir * The resources needed to lookup the home directory.
* user const char * The name of the user to lookup, or "" to lookup
* the home directory of the person running the
* program.
* Output:
* return const char * The home directory. If the library was compiled
* with threads, this string is part of the HomeDir
* object and will change on subsequent calls. If
* the library wasn't compiled to be reentrant,
* then the string is a pointer into a static string
* in the C library and will change not only on
* subsequent calls to this function, but also if
* any calls are made to the C library password
* file lookup functions. Thus to be safe, you should
* make a copy of this string before calling any
* other function that might do a password file
* lookup.
*
* On error, NULL is returned and a description
* of the error can be acquired by calling
* _hd_last_home_dir_error().
*/
const char *_hd_lookup_home_dir(HomeDir *home, const char *user)
{
const char *home_dir; /* A pointer to the home directory of the user */
/*
* If no username has been specified, arrange to lookup the current
* user.
*/
int login_user = !user || *user=='\0';
/*
* Check the arguments.
*/
if(!home) {
errno = EINVAL;
return NULL;
};
/*
* Handle the ksh "~+". This expands to the absolute path of the
* current working directory.
*/
if(!login_user && strcmp(user, "+") == 0) {
home_dir = hd_getpwd(home);
if(!home_dir) {
_err_record_msg(home->err, "Can't determine current directory",
END_ERR_MSG);
return NULL;
}
return home_dir;
};
/*
* When looking up the home directory of the current user, see if the
* HOME environment variable is set, and if so, return its value.
*/
if(login_user) {
home_dir = getenv("HOME");
if(home_dir)
return home_dir;
};
/*
* Look up the password entry of the user.
* First the POSIX threads version - this is painful!
*/
#ifdef THREAD_COMPATIBLE
{
struct passwd *ret; /* The returned pointer to pwd */
int status; /* The return value of getpwnam_r() */
/*
* Look up the password entry of the specified user.
*/
if(login_user)
status = getpwuid_r(geteuid(), &home->pwd, home->buffer, home->buflen,
&ret);
else
status = getpwnam_r(user, &home->pwd, home->buffer, home->buflen, &ret);
if(status || !ret) {
_err_record_msg(home->err, "User '", user, "' doesn't exist.",
END_ERR_MSG);
return NULL;
};
/*
* Get a pointer to the string that holds the home directory.
*/
home_dir = home->pwd.pw_dir;
};
/*
* Now the classic unix version.
*/
#else
{
struct passwd *pwd = login_user ? getpwuid(geteuid()) : getpwnam(user);
if(!pwd) {
_err_record_msg(home->err, "User '", user, "' doesn't exist.",
END_ERR_MSG);
return NULL;
};
/*
* Get a pointer to the home directory.
*/
home_dir = pwd->pw_dir;
};
#endif
return home_dir;
}
/*.......................................................................
* Return a description of the last error that caused _hd_lookup_home_dir()
* to return NULL.
*
* Input:
* home HomeDir * The resources needed to record the home directory.
* Output:
* return char * The description of the last error.
*/
const char *_hd_last_home_dir_error(HomeDir *home)
{
return home ? _err_get_msg(home->err) : "NULL HomeDir argument";
}
/*.......................................................................
* The _hd_scan_user_home_dirs() function calls a user-provided function
* for each username known by the system, passing the function both
* the name and the home directory of the user.
*
* Input:
* home HomeDir * The resource object for reading home
* directories.
* prefix const char * Only information for usernames that
* start with this prefix will be
* returned. Note that the empty
& string "", matches all usernames.
* data void * Anonymous data to be passed to the
* callback function.
* callback_fn HOME_DIR_FN(*) The function to call for each user.
* Output:
* return int 0 - Successful completion.
* 1 - An error occurred. A description
* of the error can be obtained by
* calling _hd_last_home_dir_error().
*/
int _hd_scan_user_home_dirs(HomeDir *home, const char *prefix,
void *data, HOME_DIR_FN(*callback_fn))
{
int waserr = 0; /* True after errors */
int prefix_len; /* The length of prefix[] */
/*
* Check the arguments.
*/
if(!home || !prefix || !callback_fn) {
if(home) {
_err_record_msg(home->err,
"_hd_scan_user_home_dirs: Missing callback function",
END_ERR_MSG);
};
return 1;
};
/*
* Get the length of the username prefix.
*/
prefix_len = strlen(prefix);
/*
* There are no reentrant versions of getpwent() etc for scanning
* the password file, so disable username completion when the
* library is compiled to be reentrant.
*/
#if defined(PREFER_REENTRANT) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L
#if defined __sun && defined __SVR4
if(0)
#else
if(1)
#endif
{
struct passwd pwd_buffer; /* A returned password entry */
struct passwd *pwd; /* A pointer to pwd_buffer */
char buffer[512]; /* The buffer in which the string members of */
/* pwd_buffer are stored. */
/*
* See if the prefix that is being completed is a complete username.
*/
if(!waserr && getpwnam_r(prefix, &pwd_buffer, buffer, sizeof(buffer),
&pwd) == 0 && pwd != NULL) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
/*
* See if the username of the current user minimally matches the prefix.
*/
if(!waserr && getpwuid_r(getuid(), &pwd_buffer, buffer, sizeof(buffer),
&pwd) == 0 && pwd != NULL &&
strncmp(prefix, pwd->pw_name, prefix_len)==0) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
/*
* Reentrancy not required?
*/
} else
#endif
{
struct passwd pwd_buffer; /* A returned password entry */
struct passwd *pwd; /* The pointer to the latest password entry */
/*
* Open the password file.
*/
setpwent();
/*
* Read the contents of the password file, looking for usernames
* that start with the specified prefix, and adding them to the
* list of matches.
*/
#if defined __sun && defined __SVR4
while((pwd = getpwent_r(&pwd_buffer, home->buffer, home->buflen)) != NULL && !waserr) {
#else
while((pwd = getpwent()) != NULL && !waserr) {
#endif
if(strncmp(prefix, pwd->pw_name, prefix_len) == 0) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
};
/*
* Close the password file.
*/
endpwent();
};
/*
* Under ksh ~+ stands for the absolute pathname of the current working
* directory.
*/
if(!waserr && strncmp(prefix, "+", prefix_len) == 0) {
const char *pwd = hd_getpwd(home);
if(pwd) {
waserr = callback_fn(data, "+", pwd, _err_get_msg(home->err),ERR_MSG_LEN);
} else {
waserr = 1;
_err_record_msg(home->err, "Can't determine current directory.",
END_ERR_MSG);
};
};
return waserr;
}
/*.......................................................................
* Return the value of getenv("PWD") if this points to the current
* directory, or the return value of getcwd() otherwise. The reason for
* prefering PWD over getcwd() is that the former preserves the history
* of symbolic links that have been traversed to reach the current
* directory. This function is designed to provide the equivalent
* expansion of the ksh ~+ directive, which normally returns its value
* of PWD.
*
* Input:
* home HomeDir * The resource object for reading home directories.
* Output:
* return const char * A pointer to either home->buffer, where the
* pathname is recorded, the string returned by
* getenv("PWD"), or NULL on error.
*/
static const char *hd_getpwd(HomeDir *home)
{
/*
* Get the absolute path of the current working directory.
*/
char *cwd = getcwd(home->buffer, home->buflen);
/*
* Some shells set PWD with the path of the current working directory.
* This will differ from cwd in that it won't have had symbolic links
* expanded.
*/
const char *pwd = getenv("PWD");
/*
* If PWD was set, and it points to the same directory as cwd, return
* its value. Note that it won't be the same if the current shell or
* the current program has changed directories, after inheriting PWD
* from a parent shell.
*/
struct stat cwdstat, pwdstat;
if(pwd && cwd && stat(cwd, &cwdstat)==0 && stat(pwd, &pwdstat)==0 &&
cwdstat.st_dev == pwdstat.st_dev && cwdstat.st_ino == pwdstat.st_ino)
return pwd;
/*
* Also return pwd if getcwd() failed, since it represents the best
* information that we have access to.
*/
if(!cwd)
return pwd;
/*
* In the absence of a valid PWD, return cwd.
*/
return cwd;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
#ifndef homedir_h
#define homedir_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
typedef struct HomeDir HomeDir;
/*
* The following constructor and destructor functions create and
* delete the resources needed to look up home directories.
*/
HomeDir *_new_HomeDir(void);
HomeDir *_del_HomeDir(HomeDir *home);
/*
* Return the home directory of a specified user, or NULL if unknown.
*/
const char *_hd_lookup_home_dir(HomeDir *home, const char *user);
/*
* Get the description of the that occured when _hd_lookup_home_dir() was
* last called.
*/
const char *_hd_last_home_dir_error(HomeDir *home);
/*
* The _hd_scan_user_home_dirs() function calls a user-provided function
* for each username known by the system, passing the function both
* the name and the home directory of the user.
*
* The following macro can be used to declare both pointers and
* prototypes for the callback functions. The 'data' argument is
* a copy of the 'data' argument passed to _hd_scan_user_home_dirs()
* and is intended for the user of _hd_scan_user_home_dirs() to use
* to pass anonymous context data to the callback function.
* The username and home directories are passed to the callback function
* in the *usrnam and *homedir arguments respectively.
* To abort the scan, and have _hd_scan_user_home_dirs() return 1, the
* callback function can return 1. A description of up to maxerr
* characters before the terminating '\0', can be written to errmsg[].
* This can then be examined by calling _hd_last_home_dir_error().
* To indicate success and continue the scan, the callback function
* should return 0. _hd_scan_user_home_dirs() returns 0 on successful
* completion of the scan, or 1 if an error occurred or a call to the
* callback function returned 1.
*/
#define HOME_DIR_FN(fn) int (fn)(void *data, const char *usrnam, const char *homedir, char *errmsg, int maxerr)
int _hd_scan_user_home_dirs(HomeDir *home, const char *prefix, void *data,
HOME_DIR_FN(*callback_fn));
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "ioutil.h"
static int _io_pad_line(GlWriteFn *write_fn, void *data, int c, int n);
/*.......................................................................
* Display a left-justified string over multiple terminal lines,
* taking account of the specified width of the terminal. Optional
* indentation and an option prefix string can be specified to be
* displayed at the start of each new terminal line used, and if
* needed, a single paragraph can be broken across multiple calls.
* Note that literal newlines in the input string can be used to force
* a newline at any point, and that in order to allow individual
* paragraphs to be written using multiple calls to this function,
* unless an explicit newline character is specified at the end of the
* string, a newline will not be started at the end of the last word
* in the string. Note that when a new line is started between two
* words that are separated by spaces, those spaces are not output,
* whereas when a new line is started because a newline character was
* found in the string, only the spaces before the newline character
* are discarded.
*
* Input:
* write_fn GlWriteFn * The callback function to use to write the
* output.
* data void * A pointer to arbitrary data to be passed to
* write_fn() whenever it is called.
* fp FILE * The stdio stream to write to.
* indentation int The number of fill characters to use to
* indent the start of each new terminal line.
* prefix const char * An optional prefix string to write after the
* indentation margin at the start of each new
* terminal line. You can specify NULL if no
* prefix is required.
* suffix const char * An optional suffix string to draw at the end
* of the terminal line. The line will be padded
* where necessary to ensure that the suffix ends
* in the last column of the terminal line. If
* no suffix is desired, specify NULL.
* fill_char int The padding character to use when indenting
* and filling up to the suffix.
* term_width int The width of the terminal being written to.
* start int The number of characters already written to
* the start of the current terminal line. This
* is primarily used to allow individual
* paragraphs to be written over multiple calls
* to this function, but can also be used to
* allow you to start the first line of a
* paragraph with a different prefix or
* indentation than those specified above.
* string const char * The string to be written.
* Output:
* return int On error -1 is returned. Otherwise the
* return value is the terminal column index at
* which the cursor was left after writing the
* final word in the string. Successful return
* values can thus be passed verbatim to the
* 'start' arguments of subsequent calls to
* _io_display_text() to allow the printing of a
* paragraph to be broken across multiple calls
* to _io_display_text().
*/
int _io_display_text(GlWriteFn *write_fn, void *data, int indentation,
const char *prefix, const char *suffix, int fill_char,
int term_width, int start, const char *string)
{
int ndone; /* The number of characters written from string[] */
int nnew; /* The number of characters to be displayed next */
int was_space; /* True if the previous character was a space or tab */
int last = start; /* The column number of the last character written */
int prefix_len; /* The length of the optional line prefix string */
int suffix_len; /* The length of the optional line prefix string */
int margin_width; /* The total number of columns used by the indentation */
/* margin and the prefix string. */
int i;
/*
* Check the arguments?
*/
if(!string || !write_fn) {
errno = EINVAL;
return -1;
};
/*
* Enforce sensible values on the arguments.
*/
if(term_width < 0)
term_width = 0;
if(indentation > term_width)
indentation = term_width;
else if(indentation < 0)
indentation = 0;
if(start > term_width)
start = term_width;
else if(start < 0)
start = 0;
/*
* Get the length of the prefix string.
*/
prefix_len = prefix ? strlen(prefix) : 0;
/*
* Get the length of the suffix string.
*/
suffix_len = suffix ? strlen(suffix) : 0;
/*
* How many characters are devoted to indenting and prefixing each line?
*/
margin_width = indentation + prefix_len;
/*
* Write as many terminal lines as are needed to display the whole string.
*/
for(ndone=0; string[ndone]; start=0) {
last = start;
/*
* Write spaces from the current position in the terminal line to the
* width of the requested indentation margin.
*/
if(indentation > 0 && last < indentation) {
if(_io_pad_line(write_fn, data, fill_char, indentation - last))
return -1;
last = indentation;
};
/*
* If a prefix string has been specified, display it unless we have
* passed where it should end in the terminal output line.
*/
if(prefix_len > 0 && last < margin_width) {
int pstart = last - indentation;
int plen = prefix_len - pstart;
if(write_fn(data, prefix+pstart, plen) != plen)
return -1;
last = margin_width;
};
/*
* Locate the end of the last complete word in the string before
* (term_width - start) characters have been seen. To handle the case
* where a single word is wider than the available space after the
* indentation and prefix margins, always make sure that at least one
* word is printed after the margin, regardless of whether it won't
* fit on the line. The two exceptions to this rule are if an embedded
* newline is found in the string or the end of the string is reached
* before any word has been seen.
*/
nnew = 0;
was_space = 0;
for(i=ndone; string[i] && (last+i-ndone < term_width - suffix_len ||
(nnew==0 && last==margin_width)); i++) {
if(string[i] == '\n') {
if(!was_space)
nnew = i-ndone;
break;
} else if(isspace((int) string[i])) {
if(!was_space) {
nnew = i-ndone+1;
was_space = 1;
};
} else {
was_space = 0;
};
};
/*
* Does the end of the string delimit the last word that will fit on the
* output line?
*/
if(nnew==0 && string[i] == '\0')
nnew = i-ndone;
/*
* Write the new line.
*/
if(write_fn(data, string+ndone, nnew) != nnew)
return -1;
ndone += nnew;
last += nnew;
/*
* Start a newline unless we have reached the end of the input string.
* In the latter case, in order to give the caller the chance to
* concatenate multiple calls to _io_display_text(), omit the newline,
* leaving it up to the caller to write this.
*/
if(string[ndone] != '\0') {
/*
* If a suffix has been provided, pad out the end of the line with spaces
* such that the suffix will end in the right-most terminal column.
*/
if(suffix_len > 0) {
int npad = term_width - suffix_len - last;
if(npad > 0 && _io_pad_line(write_fn, data, fill_char, npad))
return -1;
last += npad;
if(write_fn(data, suffix, suffix_len) != suffix_len)
return -1;
last += suffix_len;
};
/*
* Start a new line.
*/
if(write_fn(data, "\n", 1) != 1)
return -1;
/*
* Skip any spaces and tabs that follow the last word that was written.
*/
while(string[ndone] && isspace((int)string[ndone]) &&
string[ndone] != '\n')
ndone++;
/*
* If the terminating character was a literal newline character,
* skip it in the input string, since we just wrote it.
*/
if(string[ndone] == '\n')
ndone++;
last = 0;
};
};
/*
* Return the column number of the last character printed.
*/
return last;
}
/*.......................................................................
* Write a given number of spaces to the specified stdio output string.
*
* Input:
* write_fn GlWriteFn * The callback function to use to write the
* output.
* data void * A pointer to arbitrary data to be passed to
* write_fn() whenever it is called.
* c int The padding character.
* n int The number of spaces to be written.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _io_pad_line(GlWriteFn *write_fn, void *data, int c, int n)
{
enum {FILL_SIZE=20};
char fill[FILL_SIZE+1];
/*
* Fill the buffer with the specified padding character.
*/
memset(fill, c, FILL_SIZE);
fill[FILL_SIZE] = '\0';
/*
* Write the spaces using the above literal string of spaces as
* many times as needed to output the requested number of spaces.
*/
while(n > 0) {
int nnew = n <= FILL_SIZE ? n : FILL_SIZE;
if(write_fn(data, fill, nnew) != nnew)
return 1;
n -= nnew;
};
return 0;
}
/*.......................................................................
* The following is an output callback function which uses fwrite()
* to write to the stdio stream specified via its callback data argument.
*
* Input:
* data void * The stdio stream to write to, specified via a
* (FILE *) pointer cast to (void *).
* s const char * The string to be written.
* n int The length of the prefix of s[] to attempt to
* write.
* Output:
* return int The number of characters written from s[]. This
* should normally be a number in the range 0 to n.
* To signal that an I/O error occurred, return -1.
*/
GL_WRITE_FN(_io_write_stdio)
{
int ndone; /* The total number of characters written */
int nnew; /* The number of characters written in the latest write */
/*
* The callback data is the stdio stream to write to.
*/
FILE *fp = (FILE *) data;
/*
* Because of signals we may need to do more than one write to output
* the whole string.
*/
for(ndone=0; ndone<n; ndone += nnew) {
int nmore = n - ndone;
nnew = fwrite(s, sizeof(char), nmore, fp);
if(nnew < nmore) {
if(errno == EINTR)
clearerr(fp);
else
return ferror(fp) ? -1 : ndone + nnew;
};
};
return ndone;
}
#ifndef ioutil_h
#define ioutil_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*.......................................................................
* Callback functions of the following type can be registered to write
* to a terminal, when the default blocking writes to a local terminal
* aren't appropriate. In particular, if you don't want gl_get_line()
* to block, then this function should return before writing the
* specified number of characters if doing otherwise would involve
* waiting.
*
* Input:
* data void * The anonymous data pointer that was registered with
* this callback function.
* s const char * The string to be written. Beware that this string
* may not have a terminating '\0' character.
* n int The length of the prefix of s[] to attempt to
* write.
* Output:
* return int The number of characters written from s[]. This
* should normally be a number in the range 0 to n.
* To signal that an I/O error occurred, return -1.
*/
#define GL_WRITE_FN(fn) int (fn)(void *data, const char *s, int n)
typedef GL_WRITE_FN(GlWriteFn);
/*
* The following output callback function requires a (FILE *) callback
* data argument, and writes to this stream using the fwrite stdio
* function.
*/
GL_WRITE_FN(_io_write_stdio);
/*
* Left justify text within the bounds of the terminal adding optional
* indentation, prefixes and suffixes to each line if requested.
*/
int _io_display_text(GlWriteFn *write_fn, void *data, int indentation,
const char *prefix, const char *suffix, int fill_char,
int term_width, int start, const char *string);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "keytab.h"
#include "strngmem.h"
#include "getline.h"
#include "errmsg.h"
#include "hash.h"
/*
* When allocating or reallocating the key-binding table, how
* many entries should be added?
*/
#define KT_TABLE_INC 100
/*
* Define the size of the hash table that is used to associate action
* names with action functions. This should be a prime number.
*/
#define KT_HASH_SIZE 113
/*
* Define a binary-symbol-table object.
*/
struct KeyTab {
ErrMsg *err; /* Information about the last error */
int size; /* The allocated dimension of table[] */
int nkey; /* The current number of members in the table */
KeySym *table; /* The table of lexically sorted key sequences */
HashTable *actions; /* The hash table of actions */
StringMem *smem; /* Memory for allocating strings */
};
static int _kt_extend_table(KeyTab *kt);
static int _kt_parse_keybinding_string(const char *keyseq,
char *binary, int *nc);
static int _kt_compare_strings(const char *s1, int n1, const char *s2, int n2);
static void _kt_assign_action(KeySym *sym, KtBinder binder, KtKeyFn *keyfn,
void *data);
static char _kt_backslash_escape(const char *string, const char **endp);
static int _kt_is_emacs_meta(const char *string);
static int _kt_is_emacs_ctrl(const char *string);
static KtKeyMatch _kt_locate_keybinding(KeyTab *kt, const char *binary_keyseq,
int nc, int *first, int *last);
/*.......................................................................
* Create a new key-binding symbol table.
*
* Output:
* return KeyTab * The new object, or NULL on error.
*/
KeyTab *_new_KeyTab(void)
{
KeyTab *kt; /* The object to be returned */
/*
* Allocate the container.
*/
kt = (KeyTab *) malloc(sizeof(KeyTab));
if(!kt) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_KeyTab().
*/
kt->err = NULL;
kt->size = KT_TABLE_INC;
kt->nkey = 0;
kt->table = NULL;
kt->actions = NULL;
kt->smem = NULL;
/*
* Allocate a place to record error messages.
*/
kt->err = _new_ErrMsg();
if(!kt->err)
return _del_KeyTab(kt);
/*
* Allocate the table.
*/
kt->table = (KeySym *) malloc(sizeof(kt->table[0]) * kt->size);
if(!kt->table) {
errno = ENOMEM;
return _del_KeyTab(kt);
};
/*
* Allocate a hash table of actions.
*/
kt->actions = _new_HashTable(NULL, KT_HASH_SIZE, IGNORE_CASE, NULL, 0);
if(!kt->actions)
return _del_KeyTab(kt);
/*
* Allocate a string allocation object. This allows allocation of
* small strings without fragmenting the heap.
*/
kt->smem = _new_StringMem(KT_TABLE_INC);
if(!kt->smem)
return _del_KeyTab(kt);
return kt;
}
/*.......................................................................
* Delete a KeyTab object.
*
* Input:
* kt KeyTab * The object to be deleted.
* Output:
* return KeyTab * The deleted object (always NULL).
*/
KeyTab *_del_KeyTab(KeyTab *kt)
{
if(kt) {
if(kt->table)
free(kt->table);
kt->actions = _del_HashTable(kt->actions);
kt->smem = _del_StringMem(kt->smem, 1);
kt->err = _del_ErrMsg(kt->err);
free(kt);
};
return NULL;
}
/*.......................................................................
* Increase the size of the table to accomodate more keys.
*
* Input:
* kt KeyTab * The table to be extended.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _kt_extend_table(KeyTab *kt)
{
/*
* Attempt to increase the size of the table.
*/
KeySym *newtab = (KeySym *) realloc(kt->table, sizeof(kt->table[0]) *
(kt->size + KT_TABLE_INC));
/*
* Failed?
*/
if(!newtab) {
_err_record_msg(kt->err, "Can't extend keybinding table", END_ERR_MSG);
errno = ENOMEM;
return 1;
};
/*
* Install the resized table.
*/
kt->table = newtab;
kt->size += KT_TABLE_INC;
return 0;
}
/*.......................................................................
* Add, update or remove a keybinding to the table.
*
* Input:
* kt KeyTab * The table to add the binding to.
* binder KtBinder The source of the binding.
* keyseq const char * The key-sequence to bind.
* action char * The action to associate with the key sequence, or
* NULL to remove the action associated with the
* key sequence.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _kt_set_keybinding(KeyTab *kt, KtBinder binder, const char *keyseq,
const char *action)
{
KtKeyFn *keyfn; /* The action function */
void *data; /* The callback data of the action function */
/*
* Check arguments.
*/
if(kt==NULL || !keyseq) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* Lookup the function that implements the specified action.
*/
if(!action) {
keyfn = 0;
data = NULL;
} else {
Symbol *sym = _find_HashSymbol(kt->actions, action);
if(!sym) {
_err_record_msg(kt->err, "Unknown key-binding action: ", action,
END_ERR_MSG);
errno = EINVAL;
return 1;
};
keyfn = (KtKeyFn *) sym->fn;
data = sym->data;
};
/*
* Record the action in the table.
*/
return _kt_set_keyfn(kt, binder, keyseq, keyfn, data);
}
/*.......................................................................
* Add, update or remove a keybinding to the table, specifying an action
* function directly.
*
* Input:
* kt KeyTab * The table to add the binding to.
* binder KtBinder The source of the binding.
* keyseq char * The key-sequence to bind.
* keyfn KtKeyFn * The action function, or NULL to remove any existing
* action function.
* data void * A pointer to anonymous data to be passed to keyfn
* whenever it is called.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _kt_set_keyfn(KeyTab *kt, KtBinder binder, const char *keyseq,
KtKeyFn *keyfn, void *data)
{
const char *kptr; /* A pointer into keyseq[] */
char *binary; /* The binary version of keyseq[] */
int nc; /* The number of characters in binary[] */
int first,last; /* The first and last entries in the table which */
/* minimally match. */
int size; /* The size to allocate for the binary string */
int i;
/*
* Check arguments.
*/
if(kt==NULL || !keyseq) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* Work out a pessimistic estimate of how much space will be needed
* for the binary copy of the string, noting that binary meta characters
* embedded in the input string get split into two characters.
*/
for(size=0,kptr = keyseq; *kptr; kptr++)
size += IS_META_CHAR(*kptr) ? 2 : 1;
/*
* Allocate a string that has the length of keyseq[].
*/
binary = _new_StringMemString(kt->smem, size + 1);
if(!binary) {
errno = ENOMEM;
_err_record_msg(kt->err, "Insufficient memory to record key sequence",
END_ERR_MSG);
return 1;
};
/*
* Convert control and octal character specifications to binary characters.
*/
if(_kt_parse_keybinding_string(keyseq, binary, &nc)) {
binary = _del_StringMemString(kt->smem, binary);
return 1;
};
/*
* Lookup the position in the table at which to insert the binding.
*/
switch(_kt_locate_keybinding(kt, binary, nc, &first, &last)) {
/*
* If an exact match for the key-sequence is already in the table,
* simply replace its binding function (or delete the entry if
* the new binding is 0).
*/
case KT_EXACT_MATCH:
if(keyfn) {
_kt_assign_action(kt->table + first, binder, keyfn, data);
} else {
_del_StringMemString(kt->smem, kt->table[first].keyseq);
memmove(kt->table + first, kt->table + first + 1,
(kt->nkey - first - 1) * sizeof(kt->table[0]));
kt->nkey--;
};
binary = _del_StringMemString(kt->smem, binary);
break;
/*
* If an ambiguous match has been found and we are installing a
* callback, then our new key-sequence would hide all of the ambiguous
* matches, so we shouldn't allow it.
*/
case KT_AMBIG_MATCH:
if(keyfn) {
_err_record_msg(kt->err, "Can't bind \"", keyseq,
"\", because it is a prefix of another binding",
END_ERR_MSG);
binary = _del_StringMemString(kt->smem, binary);
errno = EPERM;
return 1;
};
break;
/*
* If the entry doesn't exist, create it.
*/
case KT_NO_MATCH:
/*
* Add a new binding?
*/
if(keyfn) {
KeySym *sym;
/*
* We will need a new entry, extend the table if needed.
*/
if(kt->nkey + 1 > kt->size) {
if(_kt_extend_table(kt)) {
binary = _del_StringMemString(kt->smem, binary);
return 1;
};
};
/*
* Make space to insert the new key-sequence before 'last'.
*/
if(last < kt->nkey) {
memmove(kt->table + last + 1, kt->table + last,
(kt->nkey - last) * sizeof(kt->table[0]));
};
/*
* Insert the new binding in the vacated position.
*/
sym = kt->table + last;
sym->keyseq = binary;
sym->nc = nc;
for(i=0; i<KTB_NBIND; i++) {
KtAction *action = sym->actions + i;
action->fn = 0;
action->data = NULL;
};
sym->binder = -1;
_kt_assign_action(sym, binder, keyfn, data);
kt->nkey++;
};
break;
case KT_BAD_MATCH:
binary = _del_StringMemString(kt->smem, binary);
return 1;
break;
};
return 0;
}
/*.......................................................................
* Perform a min-match lookup of a key-binding.
*
* Input:
* kt KeyTab * The keybinding table to lookup in.
* binary_keyseq char * The binary key-sequence to lookup.
* nc int the number of characters in keyseq[].
* Input/Output:
* first,last int * If there is an ambiguous or exact match, the indexes
* of the first and last symbols that minimally match
* will be assigned to *first and *last respectively.
* If there is no match, then first and last will
* bracket the location where the symbol should be
* inserted.
* Output:
* return KtKeyMatch One of the following enumerators:
* KT_EXACT_MATCH - An exact match was found.
* KT_AMBIG_MATCH - An ambiguous match was found.
* KT_NO_MATCH - No match was found.
* KT_BAD_MATCH - An error occurred while searching.
*/
static KtKeyMatch _kt_locate_keybinding(KeyTab *kt, const char *binary_keyseq,
int nc, int *first, int *last)
{
int mid; /* The index at which to bisect the table */
int bot; /* The lowest index of the table not searched yet */
int top; /* The highest index of the table not searched yet */
int test; /* The return value of strcmp() */
/*
* Perform a binary search for the key-sequence.
*/
bot = 0;
top = kt->nkey - 1;
while(top >= bot) {
mid = (top + bot)/2;
test = _kt_compare_strings(kt->table[mid].keyseq, kt->table[mid].nc,
binary_keyseq, nc);
if(test > 0)
top = mid - 1;
else if(test < 0)
bot = mid + 1;
else {
*first = *last = mid;
return KT_EXACT_MATCH;
};
};
/*
* An exact match wasn't found, but top is the index just below the
* index where a match would be found, and bot is the index just above
* where the match ought to be found.
*/
*first = top;
*last = bot;
/*
* See if any ambiguous matches exist, and if so make *first and *last
* refer to the first and last matches.
*/
if(*last < kt->nkey && kt->table[*last].nc > nc &&
_kt_compare_strings(kt->table[*last].keyseq, nc, binary_keyseq, nc)==0) {
*first = *last;
while(*last+1 < kt->nkey && kt->table[*last+1].nc > nc &&
_kt_compare_strings(kt->table[*last+1].keyseq, nc, binary_keyseq, nc)==0)
(*last)++;
return KT_AMBIG_MATCH;
};
/*
* No match.
*/
return KT_NO_MATCH;
}
/*.......................................................................
* Lookup the sub-array of key-bindings who's key-sequences minimally
* match a given key-sequence.
*
* Input:
* kt KeyTab * The keybinding table to lookup in.
* binary_keyseq char * The binary key-sequence to lookup.
* nc int the number of characters in keyseq[].
* Input/Output:
* matches KeySym ** The array of minimally matching symbols
* can be found in (*matches)[0..nmatch-1], unless
* no match was found, in which case *matches will
* be set to NULL.
* nmatch int The number of ambiguously matching symbols. This
* will be 0 if there is no match, 1 for an exact
* match, and a number greater than 1 for an ambiguous
* match.
* Output:
* return KtKeyMatch One of the following enumerators:
* KT_EXACT_MATCH - An exact match was found.
* KT_AMBIG_MATCH - An ambiguous match was found.
* KT_NO_MATCH - No match was found.
* KT_BAD_MATCH - An error occurred while searching.
*/
KtKeyMatch _kt_lookup_keybinding(KeyTab *kt, const char *binary_keyseq,
int nc, KeySym **matches, int *nmatch)
{
KtKeyMatch status; /* The return status */
int first,last; /* The indexes of the first and last matching entry */
/* in the symbol table. */
/*
* Check the arguments.
*/
if(!kt || !binary_keyseq || !matches || !nmatch || nc < 0) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return KT_BAD_MATCH;
};
/*
* Lookup the indexes of the binding-table entries that bracket the
* target key-sequence.
*/
status = _kt_locate_keybinding(kt, binary_keyseq, nc, &first, &last);
/*
* Translate the indexes into the corresponding subarray of matching
* table entries.
*/
switch(status) {
case KT_EXACT_MATCH:
case KT_AMBIG_MATCH:
*matches = kt->table + first;
*nmatch = last - first + 1;
break;
default:
*matches = NULL;
*nmatch = 0;
break;
};
return status;
}
/*.......................................................................
* Convert a keybinding string into a uniq binary representation.
*
* Control characters can be given directly in their binary form,
* expressed as either ^ or C-, followed by the character, expressed in
* octal, like \129 or via C-style backslash escapes, with the addition
* of '\E' to denote the escape key. Similarly, meta characters can be
* given directly in binary or expressed as M- followed by the character.
* Meta characters are recorded as two characters in the binary output
* string, the first being the escape key, and the second being the key
* that was modified by the meta key. This means that binding to
* \EA or ^[A or M-A are all equivalent.
*
* Input:
* keyseq char * The key sequence being added.
* Input/Output:
* binary char * The binary version of the key sequence will be
* assigned to binary[], which must have at least
* as many characters as keyseq[] plus the number
* of embedded binary meta characters.
* nc int * The number of characters assigned to binary[]
* will be recorded in *nc.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int _kt_parse_keybinding_string(const char *keyseq, char *binary,
int *nc)
{
const char *iptr = keyseq; /* Pointer into keyseq[] */
char *optr = binary; /* Pointer into binary[] */
char c; /* An intermediate character */
/*
* Parse the input characters until they are exhausted or the
* output string becomes full.
*/
while(*iptr) {
/*
* Check for special characters.
*/
switch(*iptr) {
case '^': /* A control character specification */
/*
* Convert the caret expression into the corresponding control
* character unless no character follows the caret, in which case
* record a literal caret.
*/
if(iptr[1]) {
/*
* Get the next, possibly escaped, character.
*/
if(iptr[1] == '\\') {
c = _kt_backslash_escape(iptr+2, &iptr);
} else {
c = iptr[1];
iptr += 2;
};
/*
* Convert the character to a control character.
*/
*optr++ = MAKE_CTRL(c);
} else {
*optr++ = *iptr++;
};
break;
/*
* A backslash-escaped character?
*/
case '\\':
/*
* Convert the escape sequence to a binary character.
*/
*optr++ = _kt_backslash_escape(iptr+1, &iptr);
break;
/*
* Possibly an emacs-style meta character?
*/
case 'M':
if(_kt_is_emacs_meta(iptr)) {
*optr++ = GL_ESC_CHAR;
iptr += 2;
} else {
*optr++ = *iptr++;
};
break;
/*
* Possibly an emacs-style control character specification?
*/
case 'C':
if(_kt_is_emacs_ctrl(iptr)) {
*optr++ = MAKE_CTRL(iptr[2]);
iptr += 3;
} else {
*optr++ = *iptr++;
};
break;
default:
/*
* Convert embedded meta characters into an escape character followed
* by the meta-unmodified character.
*/
if(IS_META_CHAR(*iptr)) {
*optr++ = GL_ESC_CHAR;
*optr++ = META_TO_CHAR(*iptr);
iptr++;
/*
* To allow keysequences that start with printable characters to
* be distinguished from the cursor-key keywords, prepend a backslash
* to the former. This same operation is performed in gl_interpret_char()
* before looking up a keysequence that starts with a printable character.
*/
} else if(iptr==keyseq && !IS_CTRL_CHAR(*iptr) &&
strcmp(keyseq, "up") != 0 && strcmp(keyseq, "down") != 0 &&
strcmp(keyseq, "left") != 0 && strcmp(keyseq, "right") != 0) {
*optr++ = '\\';
*optr++ = *iptr++;
} else {
*optr++ = *iptr++;
};
};
};
/*
* How many characters were placed in the output array?
*/
*nc = optr - binary;
return 0;
}
/*.......................................................................
* Add, remove or modify an action.
*
* Input:
* kt KeyTab * The key-binding table.
* action char * The name of the action.
* fn KtKeyFn * The function that implements the action, or NULL
* to remove an existing action.
* data void * A pointer to arbitrary callback data to pass to the
* action function whenever it is called.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _kt_set_action(KeyTab *kt, const char *action, KtKeyFn *fn, void *data)
{
Symbol *sym; /* The symbol table entry of the action */
/*
* Check the arguments.
*/
if(!kt || !action) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* If no function was provided, delete an existing action.
*/
if(!fn) {
sym = _del_HashSymbol(kt->actions, action);
return 0;
};
/*
* If the action already exists, replace its action function.
*/
sym = _find_HashSymbol(kt->actions, action);
if(sym) {
sym->fn = (void (*)(void))fn;
sym->data = data;
return 0;
};
/*
* Add a new action.
*/
if(!_new_HashSymbol(kt->actions, action, 0, (void (*)(void))fn, data, 0)) {
_err_record_msg(kt->err, "Insufficient memory to record key-binding action",
END_ERR_MSG);
return 1;
};
return 0;
}
/*.......................................................................
* Compare two strings of specified length which may contain embedded
* ascii NUL's.
*
* Input:
* s1 char * The first of the strings to be compared.
* n1 int The length of the string in s1.
* s2 char * The second of the strings to be compared.
* n2 int The length of the string in s2.
* Output:
* return int < 0 if(s1 < s2)
* 0 if(s1 == s2)
* > 0 if(s1 > s2)
*/
static int _kt_compare_strings(const char *s1, int n1, const char *s2, int n2)
{
int i;
/*
* Find the first character where the two strings differ.
*/
for(i=0; i<n1 && i<n2 && s1[i]==s2[i]; i++)
;
/*
* Did we hit the end of either string before finding a difference?
*/
if(i==n1 || i==n2) {
if(n1 == n2)
return 0;
else if(n1==i)
return -1;
else
return 1;
};
/*
* Compare the two characters that differed to determine which
* string is greatest.
*/
return s1[i] - s2[i];
}
/*.......................................................................
* Assign a given action function to a binding table entry.
*
* Input:
* sym KeySym * The binding table entry to be modified.
* binder KtBinder The source of the binding.
* keyfn KtKeyFn * The action function.
* data void * A pointer to arbitrary callback data to pass to
* the action function whenever it is called.
*/
static void _kt_assign_action(KeySym *sym, KtBinder binder, KtKeyFn *keyfn,
void *data)
{
KtAction *action; /* An action function/data pair */
int i;
/*
* Unknown binding source?
*/
if(binder < 0 || binder >= KTB_NBIND)
return;
/*
* Record the action according to its source.
*/
action = sym->actions + binder;
action->fn = keyfn;
action->data = data;
/*
* Find the highest priority binding source that has supplied an
* action. Note that the actions[] array is ordered in order of
* descreasing priority, so the first entry that contains a function
* is the one to use.
*/
for(i=0; i<KTB_NBIND && !sym->actions[i].fn; i++)
;
/*
* Record the index of this action for use during lookups.
*/
sym->binder = i < KTB_NBIND ? i : -1;
return;
}
/*.......................................................................
* Remove all key bindings that came from a specified source.
*
* Input:
* kt KeyTab * The table of key bindings.
* binder KtBinder The source of the bindings to be cleared.
*/
void _kt_clear_bindings(KeyTab *kt, KtBinder binder)
{
int oldkey; /* The index of a key in the original binding table */
int newkey; /* The index of a key in the updated binding table */
/*
* If there is no table, then no bindings exist to be deleted.
*/
if(!kt)
return;
/*
* Clear bindings of the given source.
*/
for(oldkey=0; oldkey<kt->nkey; oldkey++)
_kt_assign_action(kt->table + oldkey, binder, 0, NULL);
/*
* Delete entries that now don't have a binding from any source.
*/
newkey = 0;
for(oldkey=0; oldkey<kt->nkey; oldkey++) {
KeySym *sym = kt->table + oldkey;
if(sym->binder < 0) {
_del_StringMemString(kt->smem, sym->keyseq);
} else {
if(oldkey != newkey)
kt->table[newkey] = *sym;
newkey++;
};
};
/*
* Record the number of keys that were kept.
*/
kt->nkey = newkey;
return;
}
/*.......................................................................
* Translate a backslash escape sequence to a binary character.
*
* Input:
* string const char * The characters that follow the backslash.
* Input/Output:
* endp const char ** If endp!=NULL, on return *endp will be made to
* point to the character in string[] which follows
* the escape sequence.
* Output:
* return char The binary character.
*/
static char _kt_backslash_escape(const char *string, const char **endp)
{
char c; /* The output character */
/*
* Is the backslash followed by one or more octal digits?
*/
switch(*string) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
c = strtol(string, (char **)&string, 8);
break;
case 'a':
c = '\a';
string++;
break;
case 'b':
c = '\b';
string++;
break;
case 'e': case 'E': /* Escape */
c = GL_ESC_CHAR;
string++;
break;
case 'f':
c = '\f';
string++;
break;
case 'n':
c = '\n';
string++;
break;
case 'r':
c = '\r';
string++;
break;
case 't':
c = '\t';
string++;
break;
case 'v':
c = '\v';
string++;
break;
case '\0':
c = '\\';
break;
default:
c = *string++;
break;
};
/*
* Report the character which follows the escape sequence.
*/
if(endp)
*endp = string;
return c;
}
/*.......................................................................
* Return non-zero if the next two characters are M- and a third character
* follows. Otherwise return 0.
*
* Input:
* string const char * The sub-string to scan.
* Output:
* return int 1 - The next two characters are M- and these
* are followed by at least one character.
* 0 - The next two characters aren't M- or no
* character follows a M- pair.
*/
static int _kt_is_emacs_meta(const char *string)
{
return *string++ == 'M' && *string++ == '-' && *string;
}
/*.......................................................................
* Return non-zero if the next two characters are C- and a third character
* follows. Otherwise return 0.
*
* Input:
* string const char * The sub-string to scan.
* Output:
* return int 1 - The next two characters are C- and these
* are followed by at least one character.
* 0 - The next two characters aren't C- or no
* character follows a C- pair.
*/
static int _kt_is_emacs_ctrl(const char *string)
{
return *string++ == 'C' && *string++ == '-' && *string;
}
/*.......................................................................
* Merge an array of bindings with existing bindings.
*
* Input:
* kt KeyTab * The table of key bindings.
* binder KtBinder The source of the bindings.
* bindings const KtKeyBinding * The array of bindings.
* n int The number of bindings in bindings[].
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int _kt_add_bindings(KeyTab *kt, KtBinder binder, const KtKeyBinding *bindings,
unsigned n)
{
int i;
/*
* Check the arguments.
*/
if(!kt || !bindings) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* Install the array of bindings.
*/
for(i=0; i<n; i++) {
if(_kt_set_keybinding(kt, binder, bindings[i].keyseq, bindings[i].action))
return 1;
};
return 0;
}
/*.......................................................................
* Lookup the function that implements a given action.
*
* Input:
* kt KeyTab * The table of key bindings.
* action const char * The name of the action to look up.
* Input/Output:
* fn KtKeyFn ** If the action is found, the function that
* implements it will be assigned to *fn. Note
* that fn can be NULL.
* data void ** If the action is found, the callback data
* associated with the action function, will be
* assigned to *data. Note that data can be NULL.
* Output:
* return int 0 - OK.
* 1 - Action not found.
*/
int _kt_lookup_action(KeyTab *kt, const char *action,
KtKeyFn **fn, void **data)
{
Symbol *sym; /* The symbol table entry of the action */
/*
* Check the arguments.
*/
if(!kt || !action) {
errno = EINVAL;
if(kt)
_err_record_msg(kt->err, "NULL argument(s)", END_ERR_MSG);
return 1;
};
/*
* Lookup the symbol table entry of the action.
*/
sym = _find_HashSymbol(kt->actions, action);
if(!sym)
return 1;
/*
* Return the function and ccallback data associated with the action.
*/
if(fn)
*fn = (KtKeyFn *) sym->fn;
if(data)
*data = sym->data;
return 0;
}
/*.......................................................................
* Return extra information (ie. in addition to that provided by errno)
* about the last error to occur in any of the public functions of this
* module.
*
* Input:
* kt KeyTab * The table of key bindings.
* Output:
* return const char * A pointer to the internal buffer in which
* the error message is temporarily stored.
*/
const char *_kt_last_error(KeyTab *kt)
{
return kt ? _err_get_msg(kt->err) : "NULL KeyTab argument";
}
#ifndef keytab_h
#define keytab_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include "libtecla.h"
/*-----------------------------------------------------------------------*
* This module defines a binary-search symbol table of key-bindings. *
*-----------------------------------------------------------------------*/
/*
* All key-binding functions are defined as follows.
*
* Input:
* gl GetLine * The resource object of this library.
* count int A positive repeat count specified by the user,
* or 1. Action functions should ignore this if
* repeating the action multiple times isn't
* appropriate.
* data void * A pointer to action-specific data,
* cast to (void *).
* Output:
* return int 0 - OK.
* 1 - Error.
*/
#define KT_KEY_FN(fn) int (fn)(GetLine *gl, int count, void *data)
typedef KT_KEY_FN(KtKeyFn);
/*
* Allow the association of arbitrary callback data with each action
* function.
*/
typedef struct {
KtKeyFn *fn; /* The acion function */
void *data; /* A pointer to arbitrary data to be passed to */
/* fn() whenever it is called. */
} KtAction;
/*
* Enumerate the possible sources of key-bindings in order of decreasing
* priority.
*/
typedef enum {
KTB_USER, /* This is a binding being set by the user */
KTB_NORM, /* This is the default binding set by the library */
KTB_TERM, /* This is a binding taken from the terminal settings */
/* The following entry must always be last */
KTB_NBIND /* The number of binding sources listed above */
} KtBinder;
/*
* Define an entry of a key-binding binary symbol table.
*/
typedef struct {
char *keyseq; /* The key sequence that triggers the macro */
int nc; /* The number of characters in keyseq[] */
KtAction actions[KTB_NBIND]; /* Bindings from different sources */
int binder; /* The index of the highest priority element */
/* of actions[] that has been assigned an */
/* action function, or -1 if none have. */
} KeySym;
/*
* Provide an opaque type alias to the symbol table container.
*/
typedef struct KeyTab KeyTab;
/*
* Create a new symbol table.
*/
KeyTab *_new_KeyTab(void);
/*
* Delete the symbol table.
*/
KeyTab *_del_KeyTab(KeyTab *kt);
int _kt_set_keybinding(KeyTab *kt, KtBinder binder,
const char *keyseq, const char *action);
int _kt_set_keyfn(KeyTab *kt, KtBinder binder, const char *keyseq,
KtKeyFn *fn, void *data);
int _kt_set_action(KeyTab *kt, const char *action, KtKeyFn *fn, void *data);
/*
* Lookup the function that implements a given action.
*/
int _kt_lookup_action(KeyTab *kt, const char *action,
KtKeyFn **fn, void **data);
typedef enum {
KT_EXACT_MATCH, /* An exact match was found */
KT_AMBIG_MATCH, /* An ambiguous match was found */
KT_NO_MATCH, /* No match was found */
KT_BAD_MATCH /* An error occurred while searching */
} KtKeyMatch;
KtKeyMatch _kt_lookup_keybinding(KeyTab *kt, const char *binary_keyseq,
int nc, KeySym **matches, int *nmatch);
/*
* Remove all key bindings that came from a specified source.
*/
void _kt_clear_bindings(KeyTab *kt, KtBinder binder);
/*
* When installing an array of keybings each binding is defined by
* an element of the following type:
*/
typedef struct {
const char *keyseq; /* The sequence of keys that trigger this binding */
const char *action; /* The name of the action function that is triggered */
} KtKeyBinding;
/*
* Merge an array of bindings with existing bindings.
*/
int _kt_add_bindings(KeyTab *kt, KtBinder binder, const KtKeyBinding *bindings,
unsigned n);
/*
* Get information about the last error in this module.
*/
const char *_kt_last_error(KeyTab *kt);
#endif
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
#
#
# MAPFILE HEADER START
#
# WARNING: STOP NOW. DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
# usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#
$mapfile_version 2
#
# The instances of "tecla_l.5" below (note "l" vs "1") are by design;
# quoting the author:
#
# Unfortunately the tecla_l.5 version string is by now embedded in any
# executable that linked with libtecla versions 1.5 ..., so I can't fix
# the typo without preventing those programs from linking against 1.6.
# Thus I now have to derive tecla_1.6 from tecla_l.5, in the map file.
#
SYMBOL_VERSION tecla_1.6 {
global:
gl_append_history;
gl_automatic_history;
gl_query_char;
gl_read_char;
} tecla_l.5;
SYMBOL_VERSION tecla_l.5 {
global:
cpl_recall_matches;
gl_abandon_line;
gl_bind_keyseq;
gl_catch_blocked;
gl_completion_action;
gl_display_text;
gl_erase_terminal;
gl_error_message;
gl_handle_signal;
gl_inactivity_timeout;
gl_io_mode;
gl_list_signals;
gl_normal_io;
gl_pending_io;
gl_raw_io;
gl_register_action;
gl_return_status;
gl_set_term_size;
gl_tty_signals;
} tecla_1.4;
SYMBOL_VERSION tecla_1.4 {
global:
gl_clear_history;
gl_configure_getline;
gl_echo_mode;
gl_group_history;
gl_ignore_signal;
gl_last_signal;
gl_limit_history;
gl_load_history;
gl_lookup_history;
gl_prompt_style;
gl_range_of_history;
gl_replace_prompt;
gl_resize_history;
gl_save_history;
gl_show_history;
gl_size_of_history;
gl_state_of_history;
gl_terminal_size;
gl_toggle_history;
gl_trap_signal;
gl_watch_fd;
libtecla_version;
} tecla_1.3;
SYMBOL_VERSION tecla_1.3 {
global:
ef_list_expansions;
} tecla_1.2;
SYMBOL_VERSION tecla_1.2 {
global:
cfc_file_start;
cfc_literal_escapes;
cfc_set_check_fn;
cpl_add_completion;
cpl_check_exe;
cpl_complete_word;
cpl_file_completions;
cpl_init_FileArgs;
cpl_last_error;
cpl_list_completions;
cpl_record_error;
del_CplFileConf;
del_ExpandFile;
del_GetLine;
del_PathCache;
del_PcaPathConf;
del_WordCompletion;
ef_expand_file;
ef_last_error;
gl_change_terminal;
gl_customize_completion;
gl_get_line;
new_CplFileConf;
new_ExpandFile;
new_GetLine;
new_PathCache;
new_PcaPathConf;
new_WordCompletion;
pca_last_error;
pca_lookup_file;
pca_path_completions;
pca_scan_path;
pca_set_check_fn;
ppc_file_start;
ppc_literal_escapes;
local:
*;
};
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "pathutil.h"
/*.......................................................................
* Create a new PathName object.
*
* Output:
* return PathName * The new object, or NULL on error.
*/
PathName *_new_PathName(void)
{
PathName *path; /* The object to be returned */
/*
* Allocate the container.
*/
path = (PathName *) malloc(sizeof(PathName));
if(!path) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_PathName().
*/
path->name = NULL;
path->dim = 0;
/*
* Figure out the maximum length of an expanded pathname.
*/
path->dim = _pu_pathname_dim();
if(path->dim == 0)
return _del_PathName(path);
/*
* Allocate the pathname buffer.
*/
path->name = (char *)malloc(path->dim * sizeof(char));
if(!path->name) {
errno = ENOMEM;
return _del_PathName(path);
};
return path;
}
/*.......................................................................
* Delete a PathName object.
*
* Input:
* path PathName * The object to be deleted.
* Output:
* return PathName * The deleted object (always NULL).
*/
PathName *_del_PathName(PathName *path)
{
if(path) {
if(path->name)
free(path->name);
free(path);
};
return NULL;
}
/*.......................................................................
* Return the pathname to a zero-length string.
*
* Input:
* path PathName * The pathname container.
* Output:
* return char * The cleared pathname buffer, or NULL on error.
*/
char *_pn_clear_path(PathName *path)
{
/*
* Check the arguments.
*/
if(!path) {
errno = EINVAL;
return NULL;
};
path->name[0] = '\0';
return path->name;
}
/*.......................................................................
* Append a string to a pathname, increasing the size of the pathname
* buffer if needed.
*
* Input:
* path PathName * The pathname container.
* string const char * The string to be appended to the pathname.
* Note that regardless of the slen argument,
* this should be a '\0' terminated string.
* slen int The maximum number of characters to append
* from string[], or -1 to append the whole
* string.
* remove_escapes int If true, remove the backslashes that escape
* spaces, tabs, backslashes etc..
* Output:
* return char * The pathname string path->name[], which may
* have been reallocated, or NULL if there was
* insufficient memory to extend the pathname.
*/
char *_pn_append_to_path(PathName *path, const char *string, int slen,
int remove_escapes)
{
int pathlen; /* The length of the pathname */
int i;
/*
* Check the arguments.
*/
if(!path || !string) {
errno = EINVAL;
return NULL;
};
/*
* Get the current length of the pathname.
*/
pathlen = strlen(path->name);
/*
* How many characters should be appended?
*/
if(slen < 0 || slen > strlen(string))
slen = strlen(string);
/*
* Resize the pathname if needed.
*/
if(!_pn_resize_path(path, pathlen + slen))
return NULL;
/*
* Append the string to the output pathname, removing any escape
* characters found therein.
*/
if(remove_escapes) {
int is_escape = 0;
for(i=0; i<slen; i++) {
is_escape = !is_escape && string[i] == '\\';
if(!is_escape)
path->name[pathlen++] = string[i];
};
/*
* Terminate the string.
*/
path->name[pathlen] = '\0';
} else {
/*
* Append the string directly to the pathname.
*/
memcpy(path->name + pathlen, string, slen);
path->name[pathlen + slen] = '\0';
};
return path->name;
}
/*.......................................................................
* Prepend a string to a pathname, increasing the size of the pathname
* buffer if needed.
*
* Input:
* path PathName * The pathname container.
* string const char * The string to be prepended to the pathname.
* Note that regardless of the slen argument,
* this should be a '\0' terminated string.
* slen int The maximum number of characters to prepend
* from string[], or -1 to append the whole
* string.
* remove_escapes int If true, remove the backslashes that escape
* spaces, tabs, backslashes etc..
* Output:
* return char * The pathname string path->name[], which may
* have been reallocated, or NULL if there was
* insufficient memory to extend the pathname.
*/
char *_pn_prepend_to_path(PathName *path, const char *string, int slen,
int remove_escapes)
{
int pathlen; /* The length of the pathname */
int shift; /* The number of characters to shift the suffix by */
int i,j;
/*
* Check the arguments.
*/
if(!path || !string) {
errno = EINVAL;
return NULL;
};
/*
* Get the current length of the pathname.
*/
pathlen = strlen(path->name);
/*
* How many characters should be appended?
*/
if(slen < 0 || slen > strlen(string))
slen = strlen(string);
/*
* Work out how far we need to shift the original path string to make
* way for the new prefix. When removing escape characters, we need
* final length of the new prefix, after unescaped backslashes have
* been removed.
*/
if(remove_escapes) {
int is_escape = 0;
for(shift=0,i=0; i<slen; i++) {
is_escape = !is_escape && string[i] == '\\';
if(!is_escape)
shift++;
};
} else {
shift = slen;
};
/*
* Resize the pathname if needed.
*/
if(!_pn_resize_path(path, pathlen + shift))
return NULL;
/*
* Make room for the prefix at the beginning of the string.
*/
memmove(path->name + shift, path->name, pathlen+1);
/*
* Copy the new prefix into the vacated space at the beginning of the
* output pathname, removing any escape characters if needed.
*/
if(remove_escapes) {
int is_escape = 0;
for(i=j=0; i<slen; i++) {
is_escape = !is_escape && string[i] == '\\';
if(!is_escape)
path->name[j++] = string[i];
};
} else {
memcpy(path->name, string, slen);
};
return path->name;
}
/*.......................................................................
* If needed reallocate a given pathname buffer to allow a string of
* a given length to be stored in it.
*
* Input:
* path PathName * The pathname container object.
* length size_t The required length of the pathname buffer,
* not including the terminating '\0'.
* Output:
* return char * The pathname buffer, or NULL if there was
* insufficient memory.
*/
char *_pn_resize_path(PathName *path, size_t length)
{
/*
* Check the arguments.
*/
if(!path) {
errno = EINVAL;
return NULL;
};
/*
* If the pathname buffer isn't large enough to accomodate a string
* of the specified length, attempt to reallocate it with the new
* size, plus space for a terminating '\0'. Also add a bit of
* head room to prevent too many reallocations if the initial length
* turned out to be very optimistic.
*/
if(length + 1 > path->dim) {
size_t dim = length + 1 + PN_PATHNAME_INC;
char *name = (char *) realloc(path->name, dim);
if(!name)
return NULL;
path->name = name;
path->dim = dim;
};
return path->name;
}
/*.......................................................................
* Estimate the largest amount of space needed to store a pathname.
*
* Output:
* return size_t The number of bytes needed, including space for the
* terminating '\0'.
*/
size_t _pu_pathname_dim(void)
{
int maxlen; /* The return value excluding space for the '\0' */
/*
* If the POSIX PATH_MAX macro is defined in limits.h, use it.
*/
#ifdef PATH_MAX
maxlen = PATH_MAX;
/*
* If we have pathconf, use it.
*/
#elif defined(_PC_PATH_MAX)
errno = 0;
maxlen = pathconf(FS_ROOT_DIR, _PC_PATH_MAX);
if(maxlen <= 0 || errno)
maxlen = MAX_PATHLEN_FALLBACK;
/*
* None of the above approaches worked, so substitute our fallback
* guess.
*/
#else
maxlen = MAX_PATHLEN_FALLBACK;
#endif
/*
* Return the amount of space needed to accomodate a pathname plus
* a terminating '\0'.
*/
return maxlen + 1;
}
/*.......................................................................
* Return non-zero if the specified path name refers to a directory.
*
* Input:
* pathname const char * The path to test.
* Output:
* return int 0 - Not a directory.
* 1 - pathname[] refers to a directory.
*/
int _pu_path_is_dir(const char *pathname)
{
struct stat statbuf; /* The file-statistics return buffer */
/*
* Look up the file attributes.
*/
if(stat(pathname, &statbuf) < 0)
return 0;
/*
* Is the file a directory?
*/
return S_ISDIR(statbuf.st_mode) != 0;
}
/*.......................................................................
* Return non-zero if the specified path name refers to a regular file.
*
* Input:
* pathname const char * The path to test.
* Output:
* return int 0 - Not a regular file.
* 1 - pathname[] refers to a regular file.
*/
int _pu_path_is_file(const char *pathname)
{
struct stat statbuf; /* The file-statistics return buffer */
/*
* Look up the file attributes.
*/
if(stat(pathname, &statbuf) < 0)
return 0;
/*
* Is the file a regular file?
*/
return S_ISREG(statbuf.st_mode) != 0;
}
/*.......................................................................
* Return non-zero if the specified path name refers to an executable.
*
* Input:
* pathname const char * The path to test.
* Output:
* return int 0 - Not an executable file.
* 1 - pathname[] refers to an executable file.
*/
int _pu_path_is_exe(const char *pathname)
{
struct stat statbuf; /* The file-statistics return buffer */
/*
* Look up the file attributes.
*/
if(stat(pathname, &statbuf) < 0)
return 0;
/*
* Is the file a regular file which is executable by the current user.
*/
return S_ISREG(statbuf.st_mode) != 0 &&
(statbuf.st_mode & (S_IXOTH | S_IXGRP | S_IXUSR)) &&
access(pathname, X_OK) == 0;
}
/*.......................................................................
* Search backwards for the potential start of a filename. This
* looks backwards from the specified index in a given string,
* stopping at the first unescaped space or the start of the line.
*
* Input:
* string const char * The string to search backwards in.
* back_from int The index of the first character in string[]
* that follows the pathname.
* Output:
* return char * The pointer to the first character of
* the potential pathname, or NULL on error.
*/
char *_pu_start_of_path(const char *string, int back_from)
{
int i, j;
/*
* Check the arguments.
*/
if(!string || back_from < 0) {
errno = EINVAL;
return NULL;
};
/*
* Search backwards from the specified index.
*/
for(i=back_from-1; i>=0; i--) {
int c = string[i];
/*
* Stop on unescaped spaces.
*/
if(isspace((int)(unsigned char)c)) {
/*
* The space can't be escaped if we are at the start of the line.
*/
if(i==0)
break;
/*
* Find the extent of the escape characters which precedes the space.
*/
for(j=i-1; j>=0 && string[j]=='\\'; j--)
;
/*
* If there isn't an odd number of escape characters before the space,
* then the space isn't escaped.
*/
if((i - 1 - j) % 2 == 0)
break;
};
};
return (char *)string + i + 1;
}
/*.......................................................................
* Find the length of a potential filename starting from a given
* point. This looks forwards from the specified index in a given string,
* stopping at the first unescaped space or the end of the line.
*
* Input:
* string const char * The string to search backwards in.
* start_from int The index of the first character of the pathname
* in string[].
* Output:
* return char * The pointer to the character that follows
* the potential pathname, or NULL on error.
*/
char *_pu_end_of_path(const char *string, int start_from)
{
int c; /* The character being examined */
int escaped = 0; /* True when the next character is escaped */
int i;
/*
* Check the arguments.
*/
if(!string || start_from < 0) {
errno = EINVAL;
return NULL;
};
/*
* Search forwards from the specified index.
*/
for(i=start_from; (c=string[i]) != '\0'; i++) {
if(escaped) {
escaped = 0;
} else if(isspace(c)) {
break;
} else if(c == '\\') {
escaped = 1;
};
};
return (char *)string + i;
}
/*.......................................................................
* Return non-zero if the specified path name refers to an existing file.
*
* Input:
* pathname const char * The path to test.
* Output:
* return int 0 - The file doesn't exist.
* 1 - The file does exist.
*/
int _pu_file_exists(const char *pathname)
{
struct stat statbuf;
return stat(pathname, &statbuf) == 0;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
#ifndef pathutil_h
#define pathutil_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* The following object encapsulates a buffer designed to be used to
* store pathnames. The pathname member of the object is initially
* allocated with the size that _pu_pathname_dim() returns, and then
* if this turns out to be pessimistic, the pathname can be reallocated
* via calls to pb_append_to_path() and/or pb_resize_path().
*/
typedef struct {
char *name; /* The path buffer */
size_t dim; /* The current allocated size of buffer[] */
} PathName;
PathName *_new_PathName(void);
PathName *_del_PathName(PathName *path);
char *_pn_clear_path(PathName *path);
char *_pn_append_to_path(PathName *path, const char *string, int slen,
int remove_escapes);
char *_pn_prepend_to_path(PathName *path, const char *string, int slen,
int remove_escapes);
char *_pn_resize_path(PathName *path, size_t length);
/*
* Search backwards for the potential start of a filename. This
* looks backwards from the specified index in a given string,
* stopping at the first unescaped space or the start of the line.
*/
char *_pu_start_of_path(const char *string, int back_from);
/*
* Find the end of a potential filename, starting from a given index
* in the string. This looks forwards from the specified index in a
* given string, stopping at the first unescaped space or the end
* of the line.
*/
char *_pu_end_of_path(const char *string, int start_from);
/*
* Return an estimate of the the length of the longest pathname
* on the local system.
*/
size_t _pu_pathname_dim(void);
/*
* Return non-zero if the specified path name refers to a directory.
*/
int _pu_path_is_dir(const char *pathname);
/*
* Return non-zero if the specified path name refers to a regular file.
*/
int _pu_path_is_file(const char *pathname);
/*
* Return non-zero if the specified path name refers to an executable.
*/
int _pu_path_is_exe(const char *pathname);
/*
* Return non-zero if a file exists with the specified pathname.
*/
int _pu_file_exists(const char *pathname);
/*
* If neither the POSIX PATH_MAX macro nor the pathconf() function
* can be used to find out the maximum pathlength on the target
* system, the following fallback maximum length is used.
*/
#define MAX_PATHLEN_FALLBACK 1024
/*
* If the pathname buffer turns out to be too small, it will be extended
* in chunks of the following amount (plus whatever is needed at the time).
*/
#define PN_PATHNAME_INC 100
/*
* Define the special character-sequences of the filesystem.
*/
#define FS_ROOT_DIR "/" /* The root directory */
#define FS_ROOT_DIR_LEN (sizeof(FS_ROOT_DIR) - 1)
#define FS_PWD "." /* The current working directory */
#define FS_PWD_LEN (sizeof(FS_PWD_LEN) - 1)
#define FS_DIR_SEP "/" /* The directory separator string */
#define FS_DIR_SEP_LEN (sizeof(FS_DIR_SEP) - 1)
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "libtecla.h"
#include "pathutil.h"
#include "homedir.h"
#include "freelist.h"
#include "direader.h"
#include "stringrp.h"
#include "errmsg.h"
/*
* The new_PcaPathConf() constructor sets the integer first member of
* the returned object to the following magic number. This is then
* checked for by pca_path_completions() as a sanity check.
*/
#define PPC_ID_CODE 4567
/*
* A pointer to a structure of the following type can be passed to
* the builtin path-completion callback function to modify its behavior.
*/
struct PcaPathConf {
int id; /* This is set to PPC_ID_CODE by new_PcaPathConf() */
PathCache *pc; /* The path-list cache in which to look up the executables */
int escaped; /* If non-zero, backslashes in the input line are */
/* interpreted as escaping special characters and */
/* spaces, and any special characters and spaces in */
/* the listed completions will also be escaped with */
/* added backslashes. This is the default behaviour. */
/* If zero, backslashes are interpreted as being */
/* literal parts of the file name, and none are added */
/* to the completion suffixes. */
int file_start; /* The index in the input line of the first character */
/* of the file name. If you specify -1 here, */
/* pca_path_completions() identifies the */
/* the start of the file by looking backwards for */
/* an unescaped space, or the beginning of the line. */
};
/*
* Prepended to each chached filename is a character which contains
* one of the following status codes. When a given filename (minus
* this byte) is passed to the application's check_fn(), the result
* is recorded in this byte, such that the next time it is looked
* up, we don't have to call check_fn() again. These codes are cleared
* whenever the path is scanned and whenever the check_fn() callback
* is changed.
*/
typedef enum {
PCA_F_ENIGMA='?', /* The file remains to be checked */
PCA_F_WANTED='+', /* The file has been selected by the caller's callback */
PCA_F_IGNORE='-' /* The file has been rejected by the caller's callback */
} PcaFileStatus;
/*
* Encapsulate the memory management objects which supply memoy for
* the arrays of filenames.
*/
typedef struct {
StringGroup *sg; /* The memory used to record the names of files */
size_t files_dim; /* The allocated size of files[] */
char **files; /* Memory for 'files_dim' pointers to files */
size_t nfiles; /* The number of filenames currently in files[] */
} CacheMem;
static CacheMem *new_CacheMem(void);
static CacheMem *del_CacheMem(CacheMem *cm);
static void rst_CacheMem(CacheMem *cm);
/*
* Lists of nodes of the following type are used to record the
* names and contents of individual directories.
*/
typedef struct PathNode PathNode;
struct PathNode {
PathNode *next; /* The next directory in the path */
int relative; /* True if the directory is a relative pathname */
CacheMem *mem; /* The memory used to store dir[] and files[] */
char *dir; /* The directory pathname (stored in pc->sg) */
int nfile; /* The number of filenames stored in 'files' */
char **files; /* Files of interest in the current directory, */
/* or NULL if dir[] is a relative pathname */
/* who's contents can't be cached. This array */
/* and its contents are taken from pc->abs_mem */
/* or pc->rel_mem */
};
/*
* Append a new node to the list of directories in the path.
*/
static int add_PathNode(PathCache *pc, const char *dirname);
/*
* Set the maximum length allowed for usernames.
* names.
*/
#define USR_LEN 100
/*
* PathCache objects encapsulate the resources needed to record
* files of interest from comma-separated lists of directories.
*/
struct PathCache {
ErrMsg *err; /* The error reporting buffer */
FreeList *node_mem; /* A free-list of PathNode objects */
CacheMem *abs_mem; /* Memory for the filenames of absolute paths */
CacheMem *rel_mem; /* Memory for the filenames of relative paths */
PathNode *head; /* The head of the list of directories in the */
/* path, or NULL if no path has been scanned yet. */
PathNode *tail; /* The tail of the list of directories in the */
/* path, or NULL if no path has been scanned yet. */
PathName *path; /* The fully qualified name of a file */
HomeDir *home; /* Home-directory lookup object */
DirReader *dr; /* A portable directory reader */
CplFileConf *cfc; /* Configuration parameters to pass to */
/* cpl_file_completions() */
CplCheckFn *check_fn; /* The callback used to determine if a given */
/* filename should be recorded in the cache. */
void *data; /* Annonymous data to be passed to pc->check_fn() */
char usrnam[USR_LEN+1];/* The buffer used when reading the names of */
/* users. */
};
/*
* Empty the cache.
*/
static void pca_clear_cache(PathCache *pc);
/*
* Read a username from string[] and record it in pc->usrnam[].
*/
static int pca_read_username(PathCache *pc, const char *string, int slen,
int literal, const char **nextp);
/*
* Extract the next component of a colon separated list of directory
* paths.
*/
static int pca_extract_dir(PathCache *pc, const char *path,
const char **nextp);
/*
* Scan absolute directories for files of interest, recording their names
* in mem->sg and recording pointers to these names in mem->files[].
*/
static int pca_scan_dir(PathCache *pc, const char *dirname, CacheMem *mem);
/*
* A qsort() comparison function for comparing the cached filename
* strings pointed to by two (char **) array elements. Note that
* this ignores the initial cache-status byte of each filename.
*/
static int pca_cmp_matches(const void *v1, const void *v2);
/*
* A qsort() comparison function for comparing a filename
* against an element of an array of pointers to filename cache
* entries.
*/
static int pca_cmp_file(const void *v1, const void *v2);
/*
* Initialize a PcaPathConf configuration objects with the default
* options.
*/
static int pca_init_PcaPathConf(PcaPathConf *ppc, PathCache *pc);
/*
* Make a copy of a completion suffix, suitable for passing to
* cpl_add_completion().
*/
static int pca_prepare_suffix(PathCache *pc, const char *suffix,
int add_escapes);
/*
* Return non-zero if the specified string appears to start with a pathname.
*/
static int cpa_cmd_contains_path(const char *prefix, int prefix_len);
/*
* Return a given prefix with escapes optionally removed.
*/
static const char *pca_prepare_prefix(PathCache *pc, const char *prefix,
size_t prefix_len, int escaped);
/*
* If there is a tilde expression at the beginning of the specified path,
* place the corresponding home directory into pc->path. Otherwise
* just clear pc->path.
*/
static int pca_expand_tilde(PathCache *pc, const char *path, int pathlen,
int literal, const char **endp);
/*
* Clear the filename status codes that are recorded before each filename
* in the cache.
*/
static void pca_remove_marks(PathCache *pc);
/*
* Specify how many PathNode's to allocate at a time.
*/
#define PATH_NODE_BLK 30
/*
* Specify the amount by which the files[] arrays are to be extended
* whenever they are found to be too small.
*/
#define FILES_BLK_FACT 256
/*.......................................................................
* Create a new object who's function is to maintain a cache of
* filenames found within a list of directories, and provide quick
* lookup and completion of selected files in this cache.
*
* Output:
* return PathCache * The new, initially empty cache, or NULL
* on error.
*/
PathCache *new_PathCache(void)
{
PathCache *pc; /* The object to be returned */
/*
* Allocate the container.
*/
pc = (PathCache *)malloc(sizeof(PathCache));
if(!pc) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_PathCache().
*/
pc->err = NULL;
pc->node_mem = NULL;
pc->abs_mem = NULL;
pc->rel_mem = NULL;
pc->head = NULL;
pc->tail = NULL;
pc->path = NULL;
pc->home = NULL;
pc->dr = NULL;
pc->cfc = NULL;
pc->check_fn = 0;
pc->data = NULL;
pc->usrnam[0] = '\0';
/*
* Allocate a place to record error messages.
*/
pc->err = _new_ErrMsg();
if(!pc->err)
return del_PathCache(pc);
/*
* Allocate the freelist of directory list nodes.
*/
pc->node_mem = _new_FreeList(sizeof(PathNode), PATH_NODE_BLK);
if(!pc->node_mem)
return del_PathCache(pc);
/*
* Allocate memory for recording names of files in absolute paths.
*/
pc->abs_mem = new_CacheMem();
if(!pc->abs_mem)
return del_PathCache(pc);
/*
* Allocate memory for recording names of files in relative paths.
*/
pc->rel_mem = new_CacheMem();
if(!pc->rel_mem)
return del_PathCache(pc);
/*
* Allocate a pathname buffer.
*/
pc->path = _new_PathName();
if(!pc->path)
return del_PathCache(pc);
/*
* Allocate an object for looking up home-directories.
*/
pc->home = _new_HomeDir();
if(!pc->home)
return del_PathCache(pc);
/*
* Allocate an object for reading directories.
*/
pc->dr = _new_DirReader();
if(!pc->dr)
return del_PathCache(pc);
/*
* Allocate a cpl_file_completions() configuration object.
*/
pc->cfc = new_CplFileConf();
if(!pc->cfc)
return del_PathCache(pc);
/*
* Configure cpl_file_completions() to use check_fn() to select
* files of interest.
*/
cfc_set_check_fn(pc->cfc, pc->check_fn, pc->data);
/*
* Return the cache, ready for use.
*/
return pc;
}
/*.......................................................................
* Delete a given cache of files, returning the resources that it
* was using to the system.
*
* Input:
* pc PathCache * The cache to be deleted (can be NULL).
* Output:
* return PathCache * The deleted object (ie. allways NULL).
*/
PathCache *del_PathCache(PathCache *pc)
{
if(pc) {
/*
* Delete the error message buffer.
*/
pc->err = _del_ErrMsg(pc->err);
/*
* Delete the memory of the list of path nodes.
*/
pc->node_mem = _del_FreeList(pc->node_mem, 1);
/*
* Delete the memory used to record filenames.
*/
pc->abs_mem = del_CacheMem(pc->abs_mem);
pc->rel_mem = del_CacheMem(pc->rel_mem);
/*
* The list of PathNode's was already deleted when node_mem was
* deleted.
*/
pc->head = NULL;
pc->tail = NULL;
/*
* Delete the pathname buffer.
*/
pc->path = _del_PathName(pc->path);
/*
* Delete the home-directory lookup object.
*/
pc->home = _del_HomeDir(pc->home);
/*
* Delete the directory reader.
*/
pc->dr = _del_DirReader(pc->dr);
/*
* Delete the cpl_file_completions() config object.
*/
pc->cfc = del_CplFileConf(pc->cfc);
/*
* Delete the container.
*/
free(pc);
};
return NULL;
}
/*.......................................................................
* If you want subsequent calls to pca_lookup_file() and
* pca_path_completions() to only return the filenames of certain
* types of files, for example executables, or filenames ending in
* ".ps", call this function to register a file-selection callback
* function. This callback function takes the full pathname of a file,
* plus application-specific data, and returns 1 if the file is of
* interest, and zero otherwise.
*
* Input:
* pc PathCache * The filename cache.
* check_fn CplCheckFn * The function to call to see if the name of
* a given file should be included in the
* cache. This determines what type of files
* will reside in the cache. To revert to
* selecting all files, regardless of type,
* pass 0 here.
* data void * You can pass a pointer to anything you
* like here, including NULL. It will be
* passed to your check_fn() callback
* function, for its private use.
*/
void pca_set_check_fn(PathCache *pc, CplCheckFn *check_fn, void *data)
{
if(pc) {
/*
* If the callback or its data pointer have changed, clear the cached
* statuses of files that were accepted or rejected by the previous
* calback.
*/
if(check_fn != pc->check_fn || data != pc->data)
pca_remove_marks(pc);
/*
* Record the new callback locally.
*/
pc->check_fn = check_fn;
pc->data = data;
/*
* Configure cpl_file_completions() to use the same callback to
* select files of interest.
*/
cfc_set_check_fn(pc->cfc, check_fn, data);
};
return;
}
/*.......................................................................
* Return a description of the last path-caching error that occurred.
*
* Input:
* pc PathCache * The filename cache that suffered the error.
* Output:
* return char * The description of the last error.
*/
const char *pca_last_error(PathCache *pc)
{
return pc ? _err_get_msg(pc->err) : "NULL PathCache argument";
}
/*.......................................................................
* Discard all cached filenames.
*
* Input:
* pc PathCache * The cache to be cleared.
*/
static void pca_clear_cache(PathCache *pc)
{
if(pc) {
/*
* Return all path-nodes to the freelist.
*/
_rst_FreeList(pc->node_mem);
pc->head = pc->tail = NULL;
/*
* Delete all filename strings.
*/
rst_CacheMem(pc->abs_mem);
rst_CacheMem(pc->rel_mem);
};
return;
}
/*.......................................................................
* Build the list of files of interest contained in a given
* colon-separated list of directories.
*
* Input:
* pc PathCache * The cache in which to store the names of
* the files that are found in the list of
* directories.
* path const char * A colon-separated list of directory
* paths. Under UNIX, when searching for
* executables, this should be the return
* value of getenv("PATH").
* Output:
* return int 0 - OK.
* 1 - An error occurred. A description of
* the error can be acquired by calling
* pca_last_error(pc).
*/
int pca_scan_path(PathCache *pc, const char *path)
{
const char *pptr; /* A pointer to the next unprocessed character in path[] */
PathNode *node; /* A node in the list of directory paths */
char **fptr; /* A pointer into pc->abs_mem->files[] */
/*
* Check the arguments.
*/
if(!pc)
return 1;
/*
* Clear the outdated contents of the cache.
*/
pca_clear_cache(pc);
/*
* If no path list was provided, there is nothing to be added to the
* cache.
*/
if(!path)
return 0;
/*
* Extract directories from the path list, expanding tilde expressions
* on the fly into pc->pathname, then add them to the list of path
* nodes, along with a sorted list of the filenames of interest that
* the directories hold.
*/
pptr = path;
while(*pptr) {
/*
* Extract the next pathname component into pc->path->name.
*/
if(pca_extract_dir(pc, pptr, &pptr))
return 1;
/*
* Add a new node to the list of paths, containing both the
* directory name and, if not a relative pathname, the list of
* files of interest in the directory.
*/
if(add_PathNode(pc, pc->path->name))
return 1;
};
/*
* The file arrays in each absolute directory node are sections of
* pc->abs_mem->files[]. Record pointers to the starts of each
* of these sections in each directory node. Note that this couldn't
* be done in add_PathNode(), because pc->abs_mem->files[] may
* get reallocated in subsequent calls to add_PathNode(), thus
* invalidating any pointers to it.
*/
fptr = pc->abs_mem->files;
for(node=pc->head; node; node=node->next) {
node->files = fptr;
fptr += node->nfile;
};
return 0;
}
/*.......................................................................
* Extract the next directory path from a colon-separated list of
* directories, expanding tilde home-directory expressions where needed.
*
* Input:
* pc PathCache * The cache of filenames.
* path const char * A pointer to the start of the next component
* in the path list.
* Input/Output:
* nextp const char ** A pointer to the next unprocessed character
* in path[] will be assigned to *nextp.
* Output:
* return int 0 - OK. The extracted path is in pc->path->name.
* 1 - Error. A description of the error will
* have been left in pc->err.
*/
static int pca_extract_dir(PathCache *pc, const char *path, const char **nextp)
{
const char *pptr; /* A pointer into path[] */
const char *sptr; /* The path following tilde expansion */
int escaped = 0; /* True if the last character was a backslash */
/*
* If there is a tilde expression at the beginning of the specified path,
* place the corresponding home directory into pc->path. Otherwise
* just clear pc->path.
*/
if(pca_expand_tilde(pc, path, strlen(path), 0, &pptr))
return 1;
/*
* Keep a record of the current location in the path.
*/
sptr = pptr;
/*
* Locate the end of the directory name in the pathname string, stopping
* when either the end of the string is reached, or an un-escaped colon
* separator is seen.
*/
while(*pptr && (escaped || *pptr != ':'))
escaped = !escaped && *pptr++ == '\\';
/*
* Append the rest of the directory path to the pathname buffer.
*/
if(_pn_append_to_path(pc->path, sptr, pptr - sptr, 1) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record directory name",
END_ERR_MSG);
return 1;
};
/*
* To facilitate subsequently appending filenames to the directory
* path name, make sure that the recorded directory name ends in a
* directory separator.
*/
{
int dirlen = strlen(pc->path->name);
if(dirlen < FS_DIR_SEP_LEN ||
strncmp(pc->path->name + dirlen - FS_DIR_SEP_LEN, FS_DIR_SEP,
FS_DIR_SEP_LEN) != 0) {
if(_pn_append_to_path(pc->path, FS_DIR_SEP, FS_DIR_SEP_LEN, 0) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record directory name",
END_ERR_MSG);
return 1;
};
};
};
/*
* Skip the separator unless we have reached the end of the path.
*/
if(*pptr==':')
pptr++;
/*
* Return the unprocessed tail of the path-list string.
*/
*nextp = pptr;
return 0;
}
/*.......................................................................
* Read a username, stopping when a directory separator is seen, a colon
* separator is seen, the end of the string is reached, or the username
* buffer overflows.
*
* Input:
* pc PathCache * The cache of filenames.
* string char * The string who's prefix contains the name.
* slen int The max number of characters to read from string[].
* literal int If true, treat backslashes as literal characters
* instead of escapes.
* Input/Output:
* nextp char ** A pointer to the next unprocessed character
* in string[] will be assigned to *nextp.
* Output:
* return int 0 - OK. The username can be found in pc->usrnam.
* 1 - Error. A description of the error message
* can be found in pc->err.
*/
static int pca_read_username(PathCache *pc, const char *string, int slen,
int literal, const char **nextp)
{
int usrlen; /* The number of characters in pc->usrnam[] */
const char *sptr; /* A pointer into string[] */
int escaped = 0; /* True if the last character was a backslash */
/*
* Extract the username.
*/
for(sptr=string,usrlen=0; usrlen < USR_LEN && (sptr-string) < slen; sptr++) {
/*
* Stop if the end of the string is reached, or a directory separator
* or un-escaped colon separator is seen.
*/
if(!*sptr || strncmp(sptr, FS_DIR_SEP, FS_DIR_SEP_LEN)==0 ||
(!escaped && *sptr == ':'))
break;
/*
* Escape the next character?
*/
if(!literal && !escaped && *sptr == '\\') {
escaped = 1;
} else {
escaped = 0;
pc->usrnam[usrlen++] = *sptr;
};
};
/*
* Did the username overflow the buffer?
*/
if(usrlen >= USR_LEN) {
_err_record_msg(pc->err, "Username too long", END_ERR_MSG);
return 1;
};
/*
* Terminate the string.
*/
pc->usrnam[usrlen] = '\0';
/*
* Indicate where processing of the input string should continue.
*/
*nextp = sptr;
return 0;
}
/*.......................................................................
* Create a new CacheMem object.
*
* Output:
* return CacheMem * The new object, or NULL on error.
*/
static CacheMem *new_CacheMem(void)
{
CacheMem *cm; /* The object to be returned */
/*
* Allocate the container.
*/
cm = (CacheMem *)malloc(sizeof(CacheMem));
if(!cm) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_CacheMem().
*/
cm->sg = NULL;
cm->files_dim = 0;
cm->files = NULL;
cm->nfiles = 0;
/*
* Allocate a list of string segments for storing filenames.
*/
cm->sg = _new_StringGroup(_pu_pathname_dim());
if(!cm->sg)
return del_CacheMem(cm);
/*
* Allocate an array of pointers to filenames.
* This will be extended later if needed.
*/
cm->files_dim = FILES_BLK_FACT;
cm->files = (char **) malloc(sizeof(*cm->files) * cm->files_dim);
if(!cm->files) {
errno = ENOMEM;
return del_CacheMem(cm);
};
return cm;
}
/*.......................................................................
* Delete a CacheMem object.
*
* Input:
* cm CacheMem * The object to be deleted.
* Output:
* return CacheMem * The deleted object (always NULL).
*/
static CacheMem *del_CacheMem(CacheMem *cm)
{
if(cm) {
/*
* Delete the memory that was used to record filename strings.
*/
cm->sg = _del_StringGroup(cm->sg);
/*
* Delete the array of pointers to filenames.
*/
cm->files_dim = 0;
if(cm->files) {
free(cm->files);
cm->files = NULL;
};
/*
* Delete the container.
*/
free(cm);
};
return NULL;
}
/*.......................................................................
* Re-initialize the memory used to allocate filename strings.
*
* Input:
* cm CacheMem * The memory cache to be cleared.
*/
static void rst_CacheMem(CacheMem *cm)
{
_clr_StringGroup(cm->sg);
cm->nfiles = 0;
return;
}
/*.......................................................................
* Append a new directory node to the list of directories read from the
* path.
*
* Input:
* pc PathCache * The filename cache.
* dirname const char * The name of the new directory.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int add_PathNode(PathCache *pc, const char *dirname)
{
PathNode *node; /* The new directory list node */
int relative; /* True if dirname[] is a relative pathname */
/*
* Have we been passed a relative pathname or an absolute pathname?
*/
relative = strncmp(dirname, FS_ROOT_DIR, FS_ROOT_DIR_LEN) != 0;
/*
* If it's an absolute pathname, ignore it if the corresponding
* directory doesn't exist.
*/
if(!relative && !_pu_path_is_dir(dirname))
return 0;
/*
* Allocate a new list node to record the specifics of the new directory.
*/
node = (PathNode *) _new_FreeListNode(pc->node_mem);
if(!node) {
_err_record_msg(pc->err, "Insufficient memory to cache new directory.",
END_ERR_MSG);
return 1;
};
/*
* Initialize the node.
*/
node->next = NULL;
node->relative = relative;
node->mem = relative ? pc->rel_mem : pc->abs_mem;
node->dir = NULL;
node->nfile = 0;
node->files = NULL;
/*
* Make a copy of the directory pathname.
*/
node->dir = _sg_store_string(pc->abs_mem->sg, dirname, 0);
if(!node->dir) {
_err_record_msg(pc->err, "Insufficient memory to store directory name.",
END_ERR_MSG);
return 1;
};
/*
* Scan absolute directories for files of interest, recording their names
* in node->mem->sg and appending pointers to these names to the
* node->mem->files[] array.
*/
if(!node->relative) {
int nfile = node->nfile = pca_scan_dir(pc, node->dir, node->mem);
if(nfile < 1) { /* No files matched or an error occurred */
node = (PathNode *) _del_FreeListNode(pc->node_mem, node);
return nfile < 0;
};
};
/*
* Append the new node to the list.
*/
if(pc->head) {
pc->tail->next = node;
pc->tail = node;
} else {
pc->head = pc->tail = node;
};
return 0;
}
/*.......................................................................
* Scan a given directory for files of interest, record their names
* in mem->sg and append pointers to them to the mem->files[] array.
*
* Input:
* pc PathCache * The filename cache.
* dirname const char * The pathname of the directory to be scanned.
* mem CacheMem * The memory in which to store filenames of
* interest.
* Output:
* return int The number of files recorded, or -1 if a
* memory error occurs. Note that the
* inability to read the contents of the
* directory is not counted as an error.
*/
static int pca_scan_dir(PathCache *pc, const char *dirname, CacheMem *mem)
{
int nfile = 0; /* The number of filenames recorded */
const char *filename; /* The name of the file being looked at */
/*
* Attempt to open the directory. If the directory can't be read then
* there are no accessible files of interest in the directory.
*/
if(_dr_open_dir(pc->dr, dirname, NULL))
return 0;
/*
* Record the names of all files in the directory in the cache.
*/
while((filename = _dr_next_file(pc->dr))) {
char *copy; /* A copy of the filename */
/*
* Make a temporary copy of the filename with an extra byte prepended.
*/
_pn_clear_path(pc->path);
if(_pn_append_to_path(pc->path, " ", 1, 0) == NULL ||
_pn_append_to_path(pc->path, filename, -1, 1) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record filename",
END_ERR_MSG);
return -1;
};
/*
* Store the filename.
*/
copy = _sg_store_string(mem->sg, pc->path->name, 0);
if(!copy) {
_err_record_msg(pc->err, "Insufficient memory to cache file name.",
END_ERR_MSG);
return -1;
};
/*
* Mark the filename as unchecked.
*/
copy[0] = PCA_F_ENIGMA;
/*
* Make room to store a pointer to the copy in mem->files[].
*/
if(mem->nfiles + 1 > mem->files_dim) {
int needed = mem->files_dim + FILES_BLK_FACT;
char **files = (char **) realloc(mem->files, sizeof(*mem->files)*needed);
if(!files) {
_err_record_msg(pc->err,
"Insufficient memory to extend filename cache.",
END_ERR_MSG);
return 1;
};
mem->files = files;
mem->files_dim = needed;
};
/*
* Record a pointer to the copy of the filename at the end of the files[]
* array.
*/
mem->files[mem->nfiles++] = copy;
/*
* Keep a record of the number of files matched so far.
*/
nfile++;
};
/*
* Sort the list of files into lexical order.
*/
qsort(mem->files + mem->nfiles - nfile, nfile, sizeof(*mem->files),
pca_cmp_matches);
/*
* Return the number of files recorded in mem->files[].
*/
return nfile;
}
/*.......................................................................
* A qsort() comparison function for comparing the cached filename
* strings pointed to by two (char **) array elements. Note that
* this ignores the initial cache-status byte of each filename.
*
* Input:
* v1, v2 void * Pointers to the pointers of two strings to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int pca_cmp_matches(const void *v1, const void *v2)
{
const char **s1 = (const char **) v1;
const char **s2 = (const char **) v2;
return strcmp(*s1+1, *s2+1);
}
/*.......................................................................
* Given the simple name of a file, search the cached list of files
* in the order in which they where found in the list of directories
* previously presented to pca_scan_path(), and return the pathname
* of the first file which has this name. If a pathname to a file is
* given instead of a simple filename, this is returned without being
* looked up in the cache, but with any initial ~username expression
* expanded, and optionally, unescaped backslashes removed.
*
* Input:
* pc PathCache * The cached list of files.
* name const char * The name of the file to lookup.
* name_len int The length of the filename string at the
* beginning of name[], or -1 to indicate that
* the filename occupies the whole of the
* string.
* literal int If this argument is zero, lone backslashes
* in name[] are ignored during comparison
* with filenames in the cache, under the
* assumption that they were in the input line
* soley to escape the special significance of
* characters like spaces. To have them treated
* as normal characters, give this argument a
* non-zero value, such as 1.
* Output:
* return char * The pathname of the first matching file,
* or NULL if not found. Note that the returned
* pointer points to memory owned by *pc, and
* will become invalid on the next call to any
* function in the PathCache module.
*/
char *pca_lookup_file(PathCache *pc, const char *name, int name_len,
int literal)
{
PathNode *node; /* A node in the list of directories in the path */
char **match; /* A pointer to a matching filename string in the cache */
/*
* Check the arguments.
*/
if(!pc || !name || name_len==0)
return NULL;
/*
* If no length was specified, determine the length of the string to
* be looked up.
*/
if(name_len < 0)
name_len = strlen(name);
/*
* If the word starts with a ~username expression, the root directory,
* of it contains any directory separators, then treat it isn't a simple
* filename that can be looked up in the cache, but rather appears to
* be the pathname of a file. If so, return a copy of this pathname with
* escapes removed, if requested, and any initial ~username expression
* expanded.
*/
if(cpa_cmd_contains_path(name, name_len)) {
const char *nptr;
if(pca_expand_tilde(pc, name, name_len, literal, &nptr) ||
_pn_append_to_path(pc->path, nptr, name_len - (nptr-name),
!literal) == NULL)
return NULL;
return pc->path->name;
};
/*
* Look up the specified filename in each of the directories of the path,
* in the same order that they were listed in the path, and stop as soon
* as an instance of the file is found.
*/
for(node=pc->head; node; node=node->next) {
/*
* If the directory of the latest node is a relative pathname,
* scan it for files of interest.
*/
if(node->relative) {
rst_CacheMem(node->mem);
if(pca_scan_dir(pc, node->dir, node->mem) < 1)
continue;
node->files = node->mem->files;
node->nfile = node->mem->nfiles;
};
/*
* Copy the filename into a temporary buffer, while interpretting
* escape characters if needed.
*/
_pn_clear_path(pc->path);
if(_pn_append_to_path(pc->path, name, name_len, !literal) == NULL)
return NULL;
/*
* Perform a binary search for the requested filename.
*/
match = (char **)bsearch(pc->path->name, node->files, node->nfile,
sizeof(*node->files), pca_cmp_file);
if(match) {
/*
* Prepend the pathname in which the directory was found, which we have
* guaranteed to end in a directory separator, to the located filename.
*/
if(_pn_prepend_to_path(pc->path, node->dir, -1, 0) == NULL)
return NULL;
/*
* Return the matching pathname unless it is rejected by the application.
*/
if(!pc->check_fn || (*match)[0] == PCA_F_WANTED ||
((*match)[0]==PCA_F_ENIGMA && pc->check_fn(pc->data, pc->path->name))){
(*match)[0] = PCA_F_WANTED;
return pc->path->name;
} else {
*(match)[0] = PCA_F_IGNORE;
};
};
};
/*
* File not found.
*/
return NULL;
}
/*.......................................................................
* A qsort() comparison function for comparing a filename string to
* a cached filename string pointed to by a (char **) array element.
* This ignores the initial code byte at the start of the cached filename
* string.
*
* Input:
* v1, v2 void * Pointers to the pointers of two strings to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int pca_cmp_file(const void *v1, const void *v2)
{
const char *file_name = (const char *) v1;
const char **cache_name = (const char **) v2;
return strcmp(file_name, *cache_name + 1);
}
/*.......................................................................
* The PcaPathConf structure may have options added to it in the future.
* To allow your application to be linked against a shared version of the
* tecla library, without these additions causing your application to
* crash, you should use new_PcaPathConf() to allocate such structures.
* This will set all of the configuration options to their default values,
* which you can then change before passing the structure to
* pca_path_completions().
*
* Input:
* pc PathCache * The filename cache in which to look for
* file name completions.
* Output:
* return PcaPathConf * The new configuration structure, or NULL
* on error. A descripition of the error
* can be found by calling pca_last_error(pc).
*/
PcaPathConf *new_PcaPathConf(PathCache *pc)
{
PcaPathConf *ppc; /* The object to be returned */
/*
* Check the arguments.
*/
if(!pc)
return NULL;
/*
* Allocate the container.
*/
ppc = (PcaPathConf *)malloc(sizeof(PcaPathConf));
if(!ppc) {
_err_record_msg(pc->err, "Insufficient memory.", END_ERR_MSG);
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_PcaPathConf().
*/
if(pca_init_PcaPathConf(ppc, pc))
return del_PcaPathConf(ppc);
return ppc;
}
/*.......................................................................
* Initialize a PcaPathConf configuration structure with defaults.
*
* Input:
* ppc PcaPathConf * The structre to be initialized.
* pc PathCache * The cache in which completions will be looked up.
* Output:
* return int 0 - OK.
* 1 - Error. A description of the error can be
* obtained by calling pca_last_error(pc).
*/
static int pca_init_PcaPathConf(PcaPathConf *ppc, PathCache *pc)
{
/*
* Check the arguments.
*/
if(!pc)
return 1;
/*
* Set the default options.
*/
ppc->id = PPC_ID_CODE;
ppc->pc = pc;
ppc->escaped = 1;
ppc->file_start = -1;
return 0;
}
/*.......................................................................
* Delete a PcaPathConf object.
*
* Input:
* ppc PcaPathConf * The object to be deleted.
* Output:
* return PcaPathConf * The deleted object (always NULL).
*/
PcaPathConf *del_PcaPathConf(PcaPathConf *ppc)
{
if(ppc) {
ppc->pc = NULL; /* It is up to the caller to delete the cache */
/*
* Delete the container.
*/
free(ppc);
};
return NULL;
}
/*.......................................................................
* pca_path_completions() is a completion callback function for use
* directly with cpl_complete_word() or gl_customize_completions(), or
* indirectly from your own completion callback function. It requires
* that a CpaPathArgs object be passed via its 'void *data' argument.
*/
CPL_MATCH_FN(pca_path_completions)
{
PcaPathConf *ppc; /* The configuration arguments */
PathCache *pc; /* The cache in which to look for completions */
PathNode *node; /* A node in the list of directories in the path */
const char *filename; /* The name of the file being looked at */
const char *start_path; /* The pointer to the start of the pathname */
/* in line[]. */
int word_start; /* The index in line[] corresponding to start_path */
const char *prefix; /* The file-name prefix being searched for */
size_t prefix_len; /* The length of the prefix being completed */
int bot; /* The lowest index of the array not searched yet */
int top; /* The highest index of the array not searched yet */
/*
* Check the arguments.
*/
if(!cpl)
return 1;
if(!line || word_end < 0 || !data) {
cpl_record_error(cpl, "pca_path_completions: Invalid arguments.");
return 1;
};
/*
* Get the configuration arguments.
*/
ppc = (PcaPathConf *) data;
/*
* Check that the callback data is a PcaPathConf structure returned
* by new_PcaPathConf().
*/
if(ppc->id != PPC_ID_CODE) {
cpl_record_error(cpl,
"Invalid callback data passed to pca_path_completions()");
return 1;
};
/*
* Get the filename cache.
*/
pc = ppc->pc;
/*
* Get the start of the file name. If not specified by the caller,
* identify it by searching backwards in the input line for an
* unescaped space or the start of the line.
*/
if(ppc->file_start < 0) {
start_path = _pu_start_of_path(line, word_end);
if(!start_path) {
cpl_record_error(cpl, "Unable to find the start of the file name.");
return 1;
};
} else {
start_path = line + ppc->file_start;
};
/*
* Get the index of the start of the word being completed.
*/
word_start = start_path - line;
/*
* Work out the length of the prefix that is bein completed.
*/
prefix_len = word_end - word_start;
/*
* If the word starts with a ~username expression or the root directory,
* of it contains any directory separators, then completion must be
* delegated to cpl_file_completions().
*/
if(cpa_cmd_contains_path(start_path, prefix_len)) {
cfc_file_start(pc->cfc, word_start);
return cpl_file_completions(cpl, pc->cfc, line, word_end);
};
/*
* Look up the specified file name in each of the directories of the path,
* in the same order that they were listed in the path, and stop as soon
* as an instance of the file is found.
*/
for(node=pc->head; node; node=node->next) {
/*
* If the directory of the latest node is a relative pathname,
* scan it for files of interest.
*/
if(node->relative) {
rst_CacheMem(node->mem);
if(pca_scan_dir(pc, node->dir, node->mem) < 1)
continue;
node->files = node->mem->files;
node->nfile = node->mem->nfiles;
};
/*
* If needed, make a copy of the file-name being matched, with
* escapes removed. Note that we need to do this anew every loop
* iteration, because the above call to pca_scan_dir() uses
* pc->path.
*/
prefix = pca_prepare_prefix(pc, start_path, prefix_len, ppc->escaped);
if(!prefix)
return 1;
/*
* The directory entries are sorted, so we can perform a binary
* search for an instance of the prefix being searched for.
*/
bot = 0;
top = node->nfile - 1;
while(top >= bot) {
int mid = (top + bot)/2;
int test = strncmp(node->files[mid]+1, prefix, prefix_len);
if(test > 0)
top = mid - 1;
else if(test < 0)
bot = mid + 1;
else {
top = bot = mid;
break;
};
};
/*
* If we found a match, look to see if any of its neigbors also match.
*/
if(top == bot) {
while(--bot >= 0 && strncmp(node->files[bot]+1, prefix, prefix_len) == 0)
;
while(++top < node->nfile &&
strncmp(node->files[top]+1, prefix, prefix_len) == 0)
;
/*
* We will have gone one too far in each direction.
*/
bot++;
top--;
/*
* Add the completions to the list after checking them against the
* callers requirements.
*/
for( ; bot<=top; bot++) {
char *match = node->files[bot];
/*
* Form the full pathname of the file.
*/
_pn_clear_path(pc->path);
if(_pn_append_to_path(pc->path, node->dir, -1, 0) == NULL ||
_pn_append_to_path(pc->path, match+1, -1, 0) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to complete file name",
END_ERR_MSG);
return 1;
};
/*
* Should the file be included in the list of completions?
*/
if(!pc->check_fn || match[0] == PCA_F_WANTED ||
(match[0]==PCA_F_ENIGMA && pc->check_fn(pc->data, pc->path->name))) {
match[0] = PCA_F_WANTED;
/*
* Copy the completion suffix into the work pathname pc->path->name,
* adding backslash escapes if needed.
*/
if(pca_prepare_suffix(pc, match + 1 + prefix_len,
ppc->escaped))
return 1;
/*
* Record the completion.
*/
if(cpl_add_completion(cpl, line, word_start, word_end, pc->path->name,
"", " "))
return 1;
/*
* The file was rejected by the application.
*/
} else {
match[0] = PCA_F_IGNORE;
};
};
};
};
/*
* We now need to search for subdirectories of the current directory which
* have matching prefixes. First, if needed, make a copy of the word being
* matched, with escapes removed.
*/
prefix = pca_prepare_prefix(pc, start_path, prefix_len, ppc->escaped);
if(!prefix)
return 1;
/*
* Now open the current directory.
*/
if(_dr_open_dir(pc->dr, FS_PWD, NULL))
return 0;
/*
* Scan the current directory for sub-directories whos names start with
* the prefix that we are completing.
*/
while((filename = _dr_next_file(pc->dr))) {
/*
* Does the latest filename match the prefix, and is it a directory?
*/
if(strncmp(filename, prefix, prefix_len) == 0 && _pu_path_is_dir(filename)){
/*
* Record the completion.
*/
if(pca_prepare_suffix(pc, filename + prefix_len, ppc->escaped) ||
cpl_add_completion(cpl, line, word_start, word_end, pc->path->name,
FS_DIR_SEP, FS_DIR_SEP))
return 1;
/*
* The prefix in pc->path->name will have been overwritten by
* pca_prepare_suffix(). Restore it here.
*/
prefix = pca_prepare_prefix(pc, start_path, prefix_len, ppc->escaped);
if(!prefix)
return 1;
};
};
_dr_close_dir(pc->dr);
return 0;
}
/*.......................................................................
* Using the work buffer pc->path, make a suitably escaped copy of a
* given completion suffix, ready to be passed to cpl_add_completion().
*
* Input:
* pc PathCache * The filename cache resource object.
* suffix char * The suffix to be copied.
* add_escapes int If true, escape special characters.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int pca_prepare_suffix(PathCache *pc, const char *suffix,
int add_escapes)
{
const char *sptr; /* A pointer into suffix[] */
int nbsl; /* The number of backslashes to add to the suffix */
int i;
/*
* How long is the suffix?
*/
int suffix_len = strlen(suffix);
/*
* Clear the work buffer.
*/
_pn_clear_path(pc->path);
/*
* Count the number of backslashes that will have to be added to
* escape spaces, tabs, backslashes and wildcard characters.
*/
nbsl = 0;
if(add_escapes) {
for(sptr = suffix; *sptr; sptr++) {
switch(*sptr) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
nbsl++;
break;
};
};
};
/*
* Arrange for the output path buffer to have sufficient room for the
* both the suffix and any backslashes that have to be inserted.
*/
if(_pn_resize_path(pc->path, suffix_len + nbsl) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to complete file name",
END_ERR_MSG);
return 1;
};
/*
* If the suffix doesn't need any escapes, copy it directly into the
* work buffer.
*/
if(nbsl==0) {
strlcpy(pc->path->name, suffix, pc->path->dim);
} else {
/*
* Make a copy with special characters escaped?
*/
if(nbsl > 0) {
const char *src = suffix;
char *dst = pc->path->name;
for(i=0; i<suffix_len; i++) {
switch(*src) {
case ' ': case '\t': case '\\': case '*': case '?': case '[':
*dst++ = '\\';
};
*dst++ = *src++;
};
*dst = '\0';
};
};
return 0;
}
/*.......................................................................
* Return non-zero if the specified string appears to start with a pathname.
*
* Input:
* prefix const char * The filename prefix to check.
* prefix_len int The length of the prefix.
* Output:
* return int 0 - Doesn't start with a path name.
* 1 - Does start with a path name.
*/
static int cpa_cmd_contains_path(const char *prefix, int prefix_len)
{
int i;
/*
* If the filename starts with a ~, then this implies a ~username
* expression, which constitutes a pathname.
*/
if(*prefix == '~')
return 1;
/*
* If the filename starts with the root directory, then it obviously
* starts with a pathname.
*/
if(prefix_len >= FS_ROOT_DIR_LEN &&
strncmp(prefix, FS_ROOT_DIR, FS_ROOT_DIR_LEN) == 0)
return 1;
/*
* Search the prefix for directory separators, returning as soon as
* any are found, since their presence indicates that the filename
* starts with a pathname specification (valid or otherwise).
*/
for(i=0; i<prefix_len; i++) {
if(prefix_len - i >= FS_DIR_SEP_LEN &&
strncmp(prefix + i, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0)
return 1;
};
/*
* The file name doesn't appear to start with a pathname specification.
*/
return 0;
}
/*.......................................................................
* If needed make a new copy of the prefix being matched, in pc->path->name,
* but with escapes removed. If no escapes are to be removed, simply return
* the original prefix string.
*
* Input:
* pc PathCache * The cache being searched.
* prefix const char * The prefix to be processed.
* prefix_len size_t The length of the prefix.
* escaped int If true, return a copy with escapes removed.
* Output:
* return const char * The prepared prefix, or NULL on error, in
* which case an error message will have been
* left in pc->err.
*/
static const char *pca_prepare_prefix(PathCache *pc, const char *prefix,
size_t prefix_len, int escaped)
{
/*
* Make a copy with escapes removed?
*/
if(escaped) {
_pn_clear_path(pc->path);
if(_pn_append_to_path(pc->path, prefix, prefix_len, 1) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to complete filename",
END_ERR_MSG);
return NULL;
};
return pc->path->name;
};
return prefix;
}
/*.......................................................................
* If backslashes in the filename should be treated as literal
* characters, call the following function with literal=1. Otherwise
* the default is to treat them as escape characters, used for escaping
* spaces etc..
*
* Input:
* ppc PcaPathConf * The pca_path_completions() configuration object
* to be configured.
* literal int Pass non-zero here to enable literal interpretation
* of backslashes. Pass 0 to turn off literal
* interpretation.
*/
void ppc_literal_escapes(PcaPathConf *ppc, int literal)
{
if(ppc)
ppc->escaped = !literal;
}
/*.......................................................................
* Call this function if you know where the index at which the
* filename prefix starts in the input line. Otherwise by default,
* or if you specify start_index to be -1, the filename is taken
* to start after the first unescaped space preceding the cursor,
* or the start of the line, which ever comes first.
*
* Input:
* ppc PcaPathConf * The pca_path_completions() configuration object
* to be configured.
* start_index int The index of the start of the filename in
* the input line, or -1 to select the default.
*/
void ppc_file_start(PcaPathConf *ppc, int start_index)
{
if(ppc)
ppc->file_start = start_index;
}
/*.......................................................................
* Expand any ~user expression found at the start of a path, leaving
* either an empty string in pc->path if there is no ~user expression,
* or the corresponding home directory.
*
* Input:
* pc PathCache * The filename cache.
* path const char * The path to expand.
* pathlen int The max number of characters to look at in path[].
* literal int If true, treat backslashes as literal characters
* instead of escapes.
* Input/Output:
* endp const char * A pointer to the next unprocessed character in
* path[] will be assigned to *endp.
* Output:
* return int 0 - OK
* 1 - Error (a description will have been placed
* in pc->err).
*/
static int pca_expand_tilde(PathCache *pc, const char *path, int pathlen,
int literal, const char **endp)
{
const char *pptr = path; /* A pointer into path[] */
const char *homedir=NULL; /* A home directory */
/*
* Clear the pathname buffer.
*/
_pn_clear_path(pc->path);
/*
* If the first character is a tilde, then perform home-directory
* interpolation.
*/
if(*pptr == '~') {
/*
* Skip the tilde character and attempt to read the username that follows
* it, into pc->usrnam[].
*/
if(pca_read_username(pc, ++pptr, pathlen-1, literal, &pptr))
return 1;
/*
* Attempt to lookup the home directory of the user.
*/
homedir = _hd_lookup_home_dir(pc->home, pc->usrnam);
if(!homedir) {
_err_record_msg(pc->err, _hd_last_home_dir_error(pc->home), END_ERR_MSG);
return 1;
};
/*
* Append the home directory to the pathname string.
*/
if(_pn_append_to_path(pc->path, homedir, -1, 0) == NULL) {
_err_record_msg(pc->err,
"Insufficient memory for home directory expansion",
END_ERR_MSG);
return 1;
};
};
/*
* ~user and ~ are usually followed by a directory separator to
* separate them from the file contained in the home directory.
* If the home directory is the root directory, then we don't want
* to follow the home directory by a directory separator, so we should
* skip over it so that it doesn't get copied into the output pathname
*/
if(homedir && strcmp(homedir, FS_ROOT_DIR) == 0 &&
(pptr-path) + FS_DIR_SEP_LEN < pathlen &&
strncmp(pptr, FS_DIR_SEP, FS_DIR_SEP_LEN) == 0) {
pptr += FS_DIR_SEP_LEN;
};
/*
* Return a pointer to the next unprocessed character.
*/
*endp = pptr;
return 0;
}
/*.......................................................................
* Clear the filename status codes that are recorded before each filename
* in the cache.
*
* Input:
* pc PathCache * The filename cache.
*/
static void pca_remove_marks(PathCache *pc)
{
PathNode *node; /* A node in the list of directories in the path */
int i;
/*
* Traverse the absolute directories of the path, clearing the
* filename status marks that precede each filename.
*/
for(node=pc->head; node; node=node->next) {
if(!node->relative) {
for(i=0; i<node->nfile; i++)
*node->files[i] = PCA_F_ENIGMA;
};
};
return;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "freelist.h"
#include "stringrp.h"
/*
* StringSegment objects store lots of small strings in larger
* character arrays. Since the total length of all of the strings can't
* be known in advance, an extensible list of large character arrays,
* called string-segments are used.
*/
typedef struct StringSegment StringSegment;
struct StringSegment {
StringSegment *next; /* A pointer to the next segment in the list */
char *block; /* An array of characters to be shared between strings */
int unused; /* The amount of unused space at the end of block[] */
};
/*
* StringGroup is typedef'd in stringrp.h.
*/
struct StringGroup {
FreeList *node_mem; /* The StringSegment free-list */
int block_size; /* The dimension of each character array block */
StringSegment *head; /* The list of character arrays */
};
/*
* Specify how many StringSegment's to allocate at a time.
*/
#define STR_SEG_BLK 20
/*.......................................................................
* Create a new StringGroup object.
*
* Input:
* segment_size int The length of each of the large character
* arrays in which multiple strings will be
* stored. This sets the length of longest
* string that can be stored, and for efficiency
* should be at least 10 times as large as
* the average string that will be stored.
* Output:
* return StringGroup * The new object, or NULL on error.
*/
StringGroup *_new_StringGroup(int segment_size)
{
StringGroup *sg; /* The object to be returned */
/*
* Check the arguments.
*/
if(segment_size < 1) {
errno = EINVAL;
return NULL;
};
/*
* Allocate the container.
*/
sg = (StringGroup *) malloc(sizeof(StringGroup));
if(!sg) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_StringGroup().
*/
sg->node_mem = NULL;
sg->head = NULL;
sg->block_size = segment_size;
/*
* Allocate the free list that is used to allocate list nodes.
*/
sg->node_mem = _new_FreeList(sizeof(StringSegment), STR_SEG_BLK);
if(!sg->node_mem)
return _del_StringGroup(sg);
return sg;
}
/*.......................................................................
* Delete a StringGroup object.
*
* Input:
* sg StringGroup * The object to be deleted.
* Output:
* return StringGroup * The deleted object (always NULL).
*/
StringGroup *_del_StringGroup(StringGroup *sg)
{
if(sg) {
StringSegment *node;
/*
* Delete the character arrays.
*/
for(node=sg->head; node; node=node->next) {
if(node->block)
free(node->block);
node->block = NULL;
};
/*
* Delete the list nodes that contained the string segments.
*/
sg->node_mem = _del_FreeList(sg->node_mem, 1);
sg->head = NULL; /* Already deleted by deleting sg->node_mem */
/*
* Delete the container.
*/
free(sg);
};
return NULL;
}
/*.......................................................................
* Make a copy of a string in the specified string group, and return
* a pointer to the copy.
*
* Input:
* sg StringGroup * The group to store the string in.
* string const char * The string to be recorded.
* remove_escapes int If true, omit backslashes which escape
* other characters when making the copy.
* Output:
* return char * The pointer to the copy of the string,
* or NULL if there was insufficient memory.
*/
char *_sg_store_string(StringGroup *sg, const char *string, int remove_escapes)
{
char *copy; /* The recorded copy of string[] */
size_t len;
/*
* Check the arguments.
*/
if(!sg || !string)
return NULL;
/*
* Get memory for the string.
*/
len = strlen(string);
copy = _sg_alloc_string(sg, len);
if(copy) {
/*
* If needed, remove backslash escapes while copying the input string
* into the cache string.
*/
if(remove_escapes) {
int escaped = 0; /* True if the next character should be */
/* escaped. */
const char *src = string; /* A pointer into the input string */
char *dst = copy; /* A pointer into the cached copy of the */
/* string. */
while(*src) {
if(!escaped && *src == '\\') {
escaped = 1;
src++;
} else {
escaped = 0;
*dst++ = *src++;
};
};
*dst = '\0';
/*
* If escapes have already been removed, copy the input string directly
* into the cache.
*/
} else {
strlcpy(copy, string, len + 1);
};
};
/*
* Return a pointer to the copy of the string (or NULL if the allocation
* failed).
*/
return copy;
}
/*.......................................................................
* Allocate memory for a string of a given length.
*
* Input:
* sg StringGroup * The group to store the string in.
* length int The required length of the string.
* Output:
* return char * The pointer to the copy of the string,
* or NULL if there was insufficient memory.
*/
char *_sg_alloc_string(StringGroup *sg, int length)
{
StringSegment *node; /* A node of the list of string segments */
char *copy; /* The allocated string */
/*
* If the string is longer than block_size, then we can't record it.
*/
if(length > sg->block_size || length < 0)
return NULL;
/*
* See if there is room to record the string in one of the existing
* string segments. Do this by advancing the node pointer until we find
* a node with length+1 bytes unused, or we get to the end of the list.
*/
for(node=sg->head; node && node->unused <= length; node=node->next)
;
/*
* If there wasn't room, allocate a new string segment.
*/
if(!node) {
node = (StringSegment *) _new_FreeListNode(sg->node_mem);
if(!node)
return NULL;
/*
* Initialize the segment.
*/
node->next = NULL;
node->block = NULL;
node->unused = sg->block_size;
/*
* Attempt to allocate the string segment character array.
*/
node->block = (char *) malloc(sg->block_size);
if(!node->block)
return NULL;
/*
* Prepend the node to the list.
*/
node->next = sg->head;
sg->head = node;
};
/*
* Get memory for the string.
*/
copy = node->block + sg->block_size - node->unused;
node->unused -= length + 1;
/*
* Return a pointer to the string memory.
*/
return copy;
}
/*.......................................................................
* Delete all of the strings that are currently stored by a specified
* StringGroup object.
*
* Input:
* sg StringGroup * The group of strings to clear.
*/
void _clr_StringGroup(StringGroup *sg)
{
StringSegment *node; /* A node in the list of string segments */
/*
* Mark all of the string segments as unoccupied.
*/
for(node=sg->head; node; node=node->next)
node->unused = sg->block_size;
return;
}
#ifndef stringrp_h
#define stringrp_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* StringGroup objects provide memory for modules that need to
* allocate lots of small strings without needing to free any of them
* individually, but rather is happy to free them all at the same
* time. Taking advantage of these properties, StringGroup objects
* avoid the heap fragmentation that tends to occur when lots of small
* strings are allocated directly from the heap and later free'd. They
* do this by allocating a list of large character arrays in each of
* which multiple strings are stored. Thus instead of allocating lots
* of small strings, a few large character arrays are allocated. When
* the strings are free'd on mass, this list of character arrays is
* maintained, ready for subsequent use in recording another set of
* strings.
*/
typedef struct StringGroup StringGroup;
/*
* The following constructor allocates a string-allocation object.
* The segment_size argument specifies how long each string segment
* array should be. This should be at least 10 times the length of
* the average string to be recorded in the string group, and
* sets the length of the longest string that can be stored.
*/
StringGroup *_new_StringGroup(int segment_size);
/*
* Delete all of the strings that are currently stored by a specified
* StringGroup object.
*/
void _clr_StringGroup(StringGroup *sg);
/*
* Make a copy of the specified string, returning a pointer to
* the copy, or NULL if there was insufficient memory. If the
* remove_escapes argument is non-zero, backslashes that escape
* other characters will be removed.
*/
char *_sg_store_string(StringGroup *sg, const char *string, int remove_escapes);
/*
* Allocate memory for a string of a given length.
*/
char *_sg_alloc_string(StringGroup *sg, int length);
/*
* Delete a StringGroup object (and all of the strings that it
* contains).
*/
StringGroup *_del_StringGroup(StringGroup *sg);
#endif
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "strngmem.h"
#include "freelist.h"
struct StringMem {
unsigned long nmalloc; /* The number of strings allocated with malloc */
FreeList *fl; /* The free-list */
};
/*.......................................................................
* Create a string free-list container and the first block of its free-list.
*
* Input:
* blocking_factor int The blocking_factor argument specifies how
* many strings of length SM_STRLEN
* bytes (see stringmem.h) are allocated in each
* free-list block.
* For example if blocking_factor=64 and
* SM_STRLEN=16, then each new
* free-list block will take 1K of memory.
* Output:
* return StringMem * The new free-list container, or NULL on
* error.
*/
StringMem *_new_StringMem(unsigned blocking_factor)
{
StringMem *sm; /* The container to be returned. */
/*
* Check arguments.
*/
if(blocking_factor < 1) {
errno = EINVAL;
return NULL;
};
/*
* Allocate the container.
*/
sm = (StringMem *) malloc(sizeof(StringMem));
if(!sm) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize
* the container at least up to the point at which it can safely
* be passed to _del_StringMem().
*/
sm->nmalloc = 0;
sm->fl = NULL;
/*
* Allocate the free-list.
*/
sm->fl = _new_FreeList(SM_STRLEN, blocking_factor);
if(!sm->fl)
return _del_StringMem(sm, 1);
/*
* Return the free-list container.
*/
return sm;
}
/*.......................................................................
* Delete a string free-list.
*
* Input:
* sm StringMem * The string free-list to be deleted, or NULL.
* force int If force==0 then _del_StringMem() will complain
* and refuse to delete the free-list if any
* of nodes have not been returned to the free-list.
* If force!=0 then _del_StringMem() will not check
* whether any nodes are still in use and will
* always delete the list.
* Output:
* return StringMem * Always NULL (even if the list couldn't be
* deleted).
*/
StringMem *_del_StringMem(StringMem *sm, int force)
{
if(sm) {
/*
* Check whether any strings have not been returned to the free-list.
*/
if(!force && (sm->nmalloc > 0 || _busy_FreeListNodes(sm->fl) > 0)) {
errno = EBUSY;
return NULL;
};
/*
* Delete the free-list.
*/
sm->fl = _del_FreeList(sm->fl, force);
/*
* Delete the container.
*/
free(sm);
};
return NULL;
}
/*.......................................................................
* Allocate an array of 'length' chars.
*
* Input:
* sm StringMem * The string free-list to allocate from.
* length size_t The length of the new string (including '\0').
* Output:
* return char * The new string or NULL on error.
*/
char *_new_StringMemString(StringMem *sm, size_t length)
{
char *string; /* The string to be returned */
int was_malloc; /* True if malloc was used to allocate the string */
/*
* Check arguments.
*/
if(!sm)
return NULL;
if(length < 1)
length = 1;
/*
* Allocate the new node from the free list if possible.
*/
if(length < SM_STRLEN) {
string = (char *)_new_FreeListNode(sm->fl);
if(!string)
return NULL;
was_malloc = 0;
} else {
string = (char *) malloc(length+1); /* Leave room for the flag byte */
if(!string)
return NULL;
/*
* Count malloc allocations.
*/
was_malloc = 1;
sm->nmalloc++;
};
/*
* Use the first byte of the string to record whether the string was
* allocated with malloc or from the free-list. Then return the rest
* of the string for use by the user.
*/
string[0] = (char) was_malloc;
return string + 1;
}
/*.......................................................................
* Free a string that was previously returned by _new_StringMemString().
*
* Input:
* sm StringMem * The free-list from which the string was originally
* allocated.
* s char * The string to be returned to the free-list, or NULL.
* Output:
* return char * Always NULL.
*/
char *_del_StringMemString(StringMem *sm, char *s)
{
int was_malloc; /* True if the string originally came from malloc() */
/*
* Is there anything to be deleted?
*/
if(s && sm) {
/*
* Retrieve the true string pointer. This is one less than the one
* returned by _new_StringMemString() because the first byte of the
* allocated memory is reserved by _new_StringMemString as a flag byte
* to say whether the memory was allocated from the free-list or directly
* from malloc().
*/
s--;
/*
* Get the origination flag.
*/
was_malloc = s[0];
if(was_malloc) {
free(s);
s = NULL;
sm->nmalloc--;
} else {
s = (char *) _del_FreeListNode(sm->fl, s);
};
};
return NULL;
}
#ifndef stringmem_h
#define stringmem_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
typedef struct StringMem StringMem;
/*
* Applications that dynamically allocate lots of small strings
* run the risk of significantly fragmenting the heap. This module
* aims to reduce this risk by allocating large arrays of small fixed
* length strings, arranging them as a free-list and allowing
* callers to allocate from the list. Strings that are too long
* to be allocated from the free-list are allocated from the heap.
* Since typical implementations of malloc() eat up a minimum of
* 16 bytes per call to malloc() [because of alignment and space
* management constraints] it makes sense to set the free-list
* string size to 16 bytes. Note that unlike malloc() which typically
* keeps 8 bytes per allocation for its own use, our allocator will
* return all but one of the 16 bytes for use. One hidden byte of overhead
* is reserved for flagging whether the string was allocated directly
* from malloc or from the free-list.
*/
/*
* Set the length of each free-list string. The longest string that
* will be returned without calling malloc() will be one less than
* this number.
*/
#define SM_STRLEN 16
/*
* Create a string free-list container and the first block of its free-list.
*/
StringMem *_new_StringMem(unsigned blocking_factor);
/*
* Delete a string free-list.
*/
StringMem *_del_StringMem(StringMem *sm, int force);
/*
* Allocate an array of 'length' chars.
*/
char *_new_StringMemString(StringMem *sm, size_t size);
/*
* Free a string that was previously returned by _new_StringMemString().
*/
char *_del_StringMemString(StringMem *sm, char *s);
#endif
#include "libtecla.h"
/*.......................................................................
* Return the version number of the tecla library.
*
* Input:
* major int * The major version number of the library
* will be assigned to *major. This number is
* only incremented when a change to the library is
* made that breaks binary (shared library) and/or
* compilation backwards compatibility.
* minor int * The minor version number of the library
* will be assigned to *minor. This number is
* incremented whenever new functions are added to
* the public API.
* micro int * The micro version number of the library will be
* assigned to *micro. This number is incremented
* whenever internal changes are made that don't
* change the public API, such as bug fixes and
* performance enhancements.
*/
void libtecla_version(int *major, int *minor, int *micro)
{
if(major)
*major = TECLA_MAJOR_VER;
if(minor)
*minor = TECLA_MINOR_VER;
if(micro)
*micro = TECLA_MICRO_VER;
}
#ifndef libtecla_h
#define libtecla_h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h> /* FILE * */
#include <stdlib.h> /* size_t */
#include <time.h> /* time_t */
#include <signal.h> /* struct sigaction */
/*
* The following are the three components of the libtecla version number.
* Note that it is better to use the libtecla_version() function than these
* macros since the macros only tell you which version of the library your
* code was compiled against, whereas the libtecla_version() function
* tells you which version of the shared tecla library your program is
* actually linked to.
*/
#define TECLA_MAJOR_VER 1
#define TECLA_MINOR_VER 6
#define TECLA_MICRO_VER 0
/*.......................................................................
* Query the version number of the tecla library.
*
* Input:
* major int * The major version number of the library
* will be assigned to *major. This number is
* only incremented when a change to the library is
* made that breaks binary (shared library) and/or
* compilation backwards compatibility.
* minor int * The minor version number of the library
* will be assigned to *minor. This number is
* incremented whenever new functions are added to
* the public API.
* micro int * The micro version number of the library will be
* assigned to *micro. This number is incremented
* whenever internal changes are made that don't
* change the public API, such as bug fixes and
* performance enhancements.
*/
void libtecla_version(int *major, int *minor, int *micro);
/*-----------------------------------------------------------------------
* The getline module provides interactive command-line input, recall and
* editing by users at terminals. See the gl_get_line(3TECLA) man page for
* more details.
*-----------------------------------------------------------------------*/
/*
* Provide an opaque handle for the resource object that is defined in
* getline.h.
*/
typedef struct GetLine GetLine;
/*
* The following two functions are used to create and delete the
* resource objects that are used by the gl_get_line() function.
*/
GetLine *new_GetLine(size_t linelen, size_t histlen);
GetLine *del_GetLine(GetLine *gl);
/*
* Read a line into an internal buffer of gl.
*/
char *gl_get_line(GetLine *gl, const char *prompt, const char *start_line,
int start_pos);
/*.......................................................................
* Prompt the user for a single-character reply.
*
* Input:
* gl GetLine * A resource object returned by new_GetLine().
* prompt char * The prompt to prefix the query with, or NULL
* to reuse the previous prompt.
* defchar char The character to substitute if the
* user simply hits return, or '\n' if you don't
* need to substitute anything.
* Output:
* return int The character that was read, or EOF if the read
* had to be aborted (in which case you can call
* gl_return_status() to find out why).
*/
int gl_query_char(GetLine *gl, const char *prompt, char defchar);
/*.......................................................................
* Read a single uninterpretted character from the user, without
* displaying anything.
*
* Input:
* gl GetLine * A resource object previously returned by
* new_GetLine().
* Output:
* return int The character that was read, or EOF if the read
* had to be aborted (in which case you can call
* gl_return_status() to find out why).
*/
int gl_read_char(GetLine *gl);
/*
* Configure the application specific and/or user-specific behavior of
* gl_get_line().
*/
int gl_configure_getline(GetLine *gl, const char *app_string,
const char *app_file, const char *user_file);
/*
* The following enumerators specify the origin of a key binding, and
* are listed in order of decreasing priority, such that user-specified
* key-bindings take precedence over application default bindings.
*/
typedef enum {
GL_USER_KEY, /* A key-binding specified by the user */
GL_APP_KEY /* A key-binding specified by the application */
} GlKeyOrigin;
/*
* Bind a key sequence to a given action. If action==NULL, unbind the
* key-sequence.
*/
int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin, const char *keyseq,
const char *action);
/*-----------------------------------------------------------------------
* The file-expansion module provides facilities for expanding ~user/ and
* $envvar expressions, and for expanding glob-style wildcards.
* See the ef_expand_file(3) man page for more details.
*-----------------------------------------------------------------------*/
/*
* ExpandFile objects contain the resources needed to expand pathnames.
*/
typedef struct ExpandFile ExpandFile;
/*
* The following functions are used to create and delete the resource
* objects that are used by the ef_expand_file() function.
*/
ExpandFile *new_ExpandFile(void);
ExpandFile *del_ExpandFile(ExpandFile *ef);
/*
* A container of the following type is returned by ef_expand_file().
*/
typedef struct {
int exists; /* True if the files in files[] currently exist. */
/* This only time that this may not be true is if */
/* the input filename didn't contain any wildcards */
/* and thus wasn't matched against existing files. */
/* In this case the single entry in 'nfile' may not */
/* refer to an existing file. */
int nfile; /* The number of files in files[] */
char **files; /* An array of 'nfile' filenames. */
} FileExpansion;
/*
* The ef_expand_file() function expands a specified pathname, converting
* ~user/ and ~/ patterns at the start of the pathname to the
* corresponding home directories, replacing $envvar with the value of
* the corresponding environment variable, and then, if there are any
* wildcards, matching these against existing filenames.
*
* If no errors occur, a container is returned containing the array of
* files that resulted from the expansion. If there were no wildcards
* in the input pathname, this will contain just the original pathname
* after expansion of ~ and $ expressions. If there were any wildcards,
* then the array will contain the files that matched them. Note that
* if there were any wildcards but no existing files match them, this
* is counted as an error and NULL is returned.
*
* The supported wildcards and their meanings are:
* * - Match any sequence of zero or more characters.
* ? - Match any single character.
* [chars] - Match any single character that appears in 'chars'.
* If 'chars' contains an expression of the form a-b,
* then any character between a and b, including a and b,
* matches. The '-' character looses its special meaning
* as a range specifier when it appears at the start
* of the sequence of characters.
* [^chars] - The same as [chars] except that it matches any single
* character that doesn't appear in 'chars'.
*
* Wildcard expressions are applied to individual filename components.
* They don't match across directory separators. A '.' character at
* the beginning of a filename component must also be matched
* explicitly by a '.' character in the input pathname, since these
* are UNIX's hidden files.
*
* Input:
* fe ExpandFile * The pathname expansion resource object.
* path const char * The path name to be expanded.
* pathlen int The length of the suffix of path[] that
* constitutes the filename to be expanded,
* or -1 to specify that the whole of the
* path string should be used.
* Output:
* return FileExpansion * A pointer to a results container within the
* given ExpandFile object. This contains an
* array of the pathnames that resulted from
* expanding ~ and $ expressions and from
* matching any wildcards, sorted into lexical
* order.
*
* This container and its contents will be
* recycled on subsequent calls, so if you need
* to keep the results of two successive runs,
* you will either have to allocate a private
* copy of the array, or use two ExpandFile
* objects.
*
* On error, NULL is returned. A description
* of the error can be acquired by calling the
* ef_last_error() function.
*/
FileExpansion *ef_expand_file(ExpandFile *ef, const char *path, int pathlen);
/*.......................................................................
* Print out an array of matching files.
*
* Input:
* result FileExpansion * The container of the sorted array of
* expansions.
* fp FILE * The output stream to write to.
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int ef_list_expansions(FileExpansion *result, FILE *fp, int term_width);
/*
* The ef_last_error() function returns a description of the last error
* that occurred in a call ef_expand_file(). Note that this message is
* contained in an array which is allocated as part of *ef, and its
* contents thus potentially change on every call to ef_expand_file().
*/
const char *ef_last_error(ExpandFile *ef);
/*-----------------------------------------------------------------------
* The WordCompletion module is used for completing incomplete words, such
* as filenames. Programs can use functions within this module to register
* their own customized completion functions.
*-----------------------------------------------------------------------*/
/*
* Ambiguous completion matches are recorded in objects of the
* following type.
*/
typedef struct WordCompletion WordCompletion;
/*
* Create a new completion object.
*/
WordCompletion *new_WordCompletion(void);
/*
* Delete a redundant completion object.
*/
WordCompletion *del_WordCompletion(WordCompletion *cpl);
/*.......................................................................
* Callback functions declared and prototyped using the following macro
* are called upon to return an array of possible completion suffixes
* for the token that precedes a specified location in the given
* input line. It is up to this function to figure out where the token
* starts, and to call cpl_add_completion() to register each possible
* completion before returning.
*
* Input:
* cpl WordCompletion * An opaque pointer to the object that will
* contain the matches. This should be filled
* via zero or more calls to cpl_add_completion().
* data void * The anonymous 'data' argument that was
* passed to cpl_complete_word() or
* gl_customize_completion()).
* line const char * The current input line.
* word_end int The index of the character in line[] which
* follows the end of the token that is being
* completed.
* Output
* return int 0 - OK.
* 1 - Error.
*/
#define CPL_MATCH_FN(fn) int (fn)(WordCompletion *cpl, void *data, \
const char *line, int word_end)
typedef CPL_MATCH_FN(CplMatchFn);
/*.......................................................................
* Optional callback functions declared and prototyped using the
* following macro are called upon to return non-zero if a given
* file, specified by its pathname, is to be included in a list of
* completions.
*
* Input:
* data void * The application specified pointer which
* was specified when this callback function
* was registered. This can be used to have
* anything you like passed to your callback.
* pathname const char * The pathname of the file to be checked to
* see if it should be included in the list
* of completions.
* Output
* return int 0 - Ignore this file.
* 1 - Do include this file in the list
* of completions.
*/
#define CPL_CHECK_FN(fn) int (fn)(void *data, const char *pathname)
typedef CPL_CHECK_FN(CplCheckFn);
/*
* You can use the following CplCheckFn callback function to only
* have executables included in a list of completions.
*/
CPL_CHECK_FN(cpl_check_exe);
/*
* cpl_file_completions() is the builtin filename completion callback
* function. This can also be called by your own custom CPL_MATCH_FN()
* callback functions. To do this pass on all of the arguments of your
* custom callback function to cpl_file_completions(), with the exception
* of the (void *data) argument. The data argument should either be passed
* NULL to request the default behaviour of the file-completion function,
* or be passed a pointer to a CplFileConf structure (see below). In the
* latter case the contents of the structure modify the behavior of the
* file-completer.
*/
CPL_MATCH_FN(cpl_file_completions);
/*
* Objects of the following type can be used to change the default
* behavior of the cpl_file_completions() callback function.
*/
typedef struct CplFileConf CplFileConf;
/*
* If you want to change the behavior of the cpl_file_completions()
* callback function, call the following function to allocate a
* configuration object, then call one or more of the subsequent
* functions to change any of the default configuration parameters
* that you don't want. This function returns NULL when there is
* insufficient memory.
*/
CplFileConf *new_CplFileConf(void);
/*
* If backslashes in the prefix being passed to cpl_file_completions()
* should be treated as literal characters, call the following function
* with literal=1. Otherwise the default is to treat them as escape
* characters which remove the special meanings of spaces etc..
*/
void cfc_literal_escapes(CplFileConf *cfc, int literal);
/*
* Before calling cpl_file_completions(), call this function if you
* know the index at which the filename prefix starts in the input line.
* Otherwise by default, or if you specify start_index to be -1, the
* filename is taken to start after the first unescaped space preceding
* the cursor, or the start of the line, which ever comes first.
*/
void cfc_file_start(CplFileConf *cfc, int start_index);
/*
* If you only want certain types of files to be included in the
* list of completions, use the following function to specify a
* callback function which will be called to ask whether a given file
* should be included. The chk_data argument is will be passed to the
* callback function whenever it is called and can be anything you want.
*/
void cfc_set_check_fn(CplFileConf *cfc, CplCheckFn *chk_fn, void *chk_data);
/*
* The following function deletes a CplFileConf objects previously
* returned by new_CplFileConf(). It always returns NULL.
*/
CplFileConf *del_CplFileConf(CplFileConf *cfc);
/*
* The following configuration structure is deprecated. Do not change
* its contents, since this will break any programs that still use it,
* and don't use it in new programs. Instead use opaque CplFileConf
* objects as described above. cpl_file_completions() figures out
* what type of structure you pass it, by virtue of a magic int code
* placed at the start of CplFileConf object by new_CplFileConf().
*/
typedef struct {
int escaped; /* Opposite to the argument of cfc_literal_escapes() */
int file_start; /* Equivalent to the argument of cfc_file_start() */
} CplFileArgs;
/*
* This initializes the deprecated CplFileArgs structures.
*/
void cpl_init_FileArgs(CplFileArgs *cfa);
/*.......................................................................
* When an error occurs while performing a completion, custom completion
* callback functions should register a terse description of the error
* by calling cpl_record_error(). This message will then be returned on
* the next call to cpl_last_error() and used by getline to display an
* error message to the user.
*
* Input:
* cpl WordCompletion * The string-completion resource object that was
* originally passed to the callback.
* errmsg const char * The description of the error.
*/
void cpl_record_error(WordCompletion *cpl, const char *errmsg);
/*.......................................................................
* This function can be used to replace the builtin filename-completion
* function with one of the user's choice. The user's completion function
* has the option of calling the builtin filename-completion function
* if it believes that the token that it has been presented with is a
* filename (see cpl_file_completions() above).
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * This is passed to match_fn() whenever it is
* called. It could, for example, point to a
* symbol table that match_fn() would look up
* matches in.
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* report matching symbols.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_customize_completion(GetLine *gl, void *data, CplMatchFn *match_fn);
/*.......................................................................
* This function allows you to install alternate completion action
* functions or completion listing functions, or to change the
* completion function of an existing action of the same type. This
* should preferably be called before the first call to gl_get_line()
* so that the name of the action becomes defined before the user's
* configuration file is read.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * This is passed to match_fn() whenever it is
* called. It could, for example, point to a
* symbol table that match_fn() would look up
* matches in.
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* report matching symbols.
* list_only int If non-zero, install an action that only lists
* possible completions, rather than attempting
* to perform the completion.
* name const char * The name with which users can refer to the
* binding in tecla configuration files.
* keyseq const char * The key sequence with which to invoke
* the binding. This should be specified in the
* same manner as key-sequences in tecla
* configuration files (eg. "M-^I").
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
int list_only, const char *name, const char *keyseq);
/*.......................................................................
* Change the terminal (or stream) that getline interacts with.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* input_fp FILE * The stdio stream to read from.
* output_fp FILE * The stdio stream to write to.
* term const char * The terminal type. This can be NULL if
* either or both of input_fp and output_fp don't
* refer to a terminal. Otherwise it should refer
* to an entry in the terminal information database.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
const char *term);
/*.......................................................................
* The following functions can be used to save and restore the contents
* of the history buffer.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* filename const char * The name of the new file to write to.
* comment const char * Extra information such as timestamps will
* be recorded on a line started with this
* string, the idea being that the file can
* double as a command file. Specify "" if
* you don't care. Be sure to specify the
* same string to both functions.
* max_lines int The maximum number of lines to save, or -1
* to save all of the lines in the history
* list.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_save_history(GetLine *gl, const char *filename, const char *comment,
int max_lines);
int gl_load_history(GetLine *gl, const char *filename, const char *comment);
/*
* Enumerate file-descriptor events that can be waited for.
*/
typedef enum {
GLFD_READ, /* Watch for data waiting to be read from a file descriptor */
GLFD_WRITE, /* Watch for ability to write to a file descriptor */
GLFD_URGENT /* Watch for urgent out-of-band data on the file descriptor */
} GlFdEvent;
/*
* The following enumeration is used for the return status of file
* descriptor event callbacks.
*/
typedef enum {
GLFD_ABORT, /* Cause gl_get_line() to abort with an error */
GLFD_REFRESH, /* Redraw the input line and continue waiting for input */
GLFD_CONTINUE /* Continue to wait for input, without redrawing the line */
} GlFdStatus;
/*.......................................................................
* On systems that have the select() system call, while gl_get_line()
* is waiting for terminal input, it can also be asked to listen for
* activity on arbitrary file descriptors. Callback functions of the
* following type can be registered to be called when activity is
* seen. If your callback needs to write to the terminal or use
* signals, please see the gl_get_line(3) man page.
*
* Input:
* gl GetLine * The gl_get_line() resource object. You can use
* this safely to call gl_watch_fd() or
* gl_inactivity_timeout(). The effect of calling other
* functions that take a gl argument is undefined,
* and must be avoided.
* data void * A pointer to arbitrary callback data, as originally
* registered with gl_watch_fd().
* fd int The file descriptor that has activity.
* event GlFdEvent The activity seen on the file descriptor. The
* inclusion of this argument allows the same
* callback to be registered for multiple events.
* Output:
* return GlFdStatus GLFD_ABORT - Cause gl_get_line() to abort with
* an error (set errno if you need it).
* GLFD_REFRESH - Redraw the input line and continue
* waiting for input. Use this if you
* wrote something to the terminal.
* GLFD_CONTINUE - Continue to wait for input, without
* redrawing the line.
*/
#define GL_FD_EVENT_FN(fn) GlFdStatus (fn)(GetLine *gl, void *data, int fd, \
GlFdEvent event)
typedef GL_FD_EVENT_FN(GlFdEventFn);
/*.......................................................................
* Where possible, register a function and associated data to be called
* whenever a specified event is seen on a file descriptor.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* fd int The file descriptor to watch.
* event GlFdEvent The type of activity to watch for.
* callback GlFdEventFn * The function to call when the specified
* event occurs. Setting this to 0 removes
* any existing callback.
* data void * A pointer to arbitrary data to pass to the
* callback function.
* Output:
* return int 0 - OK.
* 1 - Either gl==NULL, or this facility isn't
* available on the the host system
* (ie. select() isn't available). No
* error message is generated in the latter
* case.
*/
int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
GlFdEventFn *callback, void *data);
/*
* Enumerators from the following list are returned by activity
* timeout callbacks registered by gl_inactivity_timeout(). They tell
* gl_get_line() whether and how to procede.
*/
typedef enum {
GLTO_ABORT, /* Cause gl_get_line() to abort with an error */
GLTO_REFRESH, /* Redraw the input line and continue waiting for input */
GLTO_CONTINUE /* Continue to wait for input, without redrawing the line */
} GlAfterTimeout;
/*.......................................................................
* On systems that have the select() system call, the application has
* the option of providing a callback function of the following type,
* which is called whenever no terminal input or other I/O activity is
* seen for the timeout duration specified in the last call to
* gl_inactivity_timeout().
*
* Input:
* gl GetLine * The gl_get_line() resource object. You can use
* this safely to call gl_watch_fd() or
* gl_inactivity_timeout(). The effect of calling other
* functions that take a gl argument is undefined,
* and must be avoided.
* data void * A pointer to arbitrary callback data, as
* originally registered with gl_inactivity_timeout().
* Output:
* return GlAfterTimeout GLTO_ABORT - Cause gl_get_line() to
* abort with an error (set
* errno if you need it).
* GLTO_REFRESH - Redraw the input line and
* continue waiting for
* input. Use this if you
* wrote something to the
* terminal.
* GLTO_CONTINUE - Continue to wait for
* input, without redrawing
* the line.
*/
#define GL_TIMEOUT_FN(fn) GlAfterTimeout (fn)(GetLine *gl, void *data)
typedef GL_TIMEOUT_FN(GlTimeoutFn);
/*.......................................................................
* On systems with the select() system call, the gl_inactivity_timeout()
* function provides the option of setting (or cancelling) an
* inactivity timeout. Inactivity, in this case, refers both to
* terminal input received from the user, and to I/O on any file
* descriptors registered by calls to gl_watch_fd(). If at any time,
* no activity is seen for the requested time period, the specified
* timeout callback function is called. On returning, this callback
* returns a code which tells gl_get_line() what to do next. Note that
* each call to gl_inactivity_timeout() replaces any previously installed
* timeout callback, and that specifying a callback of 0, turns off
* inactivity timing.
*
* Beware that although the timeout argument includes a nano-second
* component, few computer clocks presently have resolutions finer
* than a few milliseconds, so asking for less than a few milliseconds
* is equivalent to zero on a lot of systems.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* callback GlTimeoutFn * The function to call when the inactivity
* timeout is exceeded. To turn off
* inactivity timeouts altogether, send 0.
* data void * A pointer to arbitrary data to pass to the
* callback function.
* sec unsigned long The number of whole seconds in the timeout.
* nsec unsigned long The fractional number of seconds in the
* timeout, expressed in nano-seconds (see
* the caveat above).
* Output:
* return int 0 - OK.
* 1 - Either gl==NULL, or this facility isn't
* available on the the host system
* (ie. select() isn't available). No
* error message is generated in the latter
* case.
*/
int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *timeout_fn, void *data,
unsigned long sec, unsigned long nsec);
/*.......................................................................
* Switch history streams. History streams represent separate history
* lists recorded within a single history buffer. Different streams
* are distinguished by integer identifiers chosen by the calling
* appplicaton. Initially new_GetLine() sets the stream identifier to
* 0. Whenever a new line is appended to the history list, the current
* stream identifier is recorded with it, and history lookups only
* consider lines marked with the current stream identifier.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* id unsigned The new history stream identifier.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_group_history(GetLine *gl, unsigned id);
/*.......................................................................
* Display the contents of the history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* fp FILE * The stdio output stream to write to.
* fmt const char * A format string. This containing characters to be
* written verbatim, plus any of the following
* format directives:
* %D - The date, formatted like 2001-11-20
* %T - The time of day, formatted like 23:59:59
* %N - The sequential entry number of the
* line in the history buffer.
* %G - The number of the history group that
* the line belongs to.
* %% - A literal % character.
* %H - The history line itself.
* Note that a '\n' newline character is not
* appended by default.
* all_groups int If true, display history lines from all
* history groups. Otherwise only display
* those of the current history group.
* max_lines int If max_lines is < 0, all available lines
* are displayed. Otherwise only the most
* recent max_lines lines will be displayed.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_show_history(GetLine *gl, FILE *fp, const char *fmt, int all_groups,
int max_lines);
/*.......................................................................
* Resize or delete the history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* bufsize size_t The number of bytes in the history buffer, or 0
* to delete the buffer completely.
* Output:
* return int 0 - OK.
* 1 - Insufficient memory (the previous buffer
* will have been retained). No error message
* will be displayed.
*/
int gl_resize_history(GetLine *gl, size_t bufsize);
/*.......................................................................
* Set an upper limit to the number of lines that can be recorded in the
* history list, or remove a previously specified limit.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* max_lines int The maximum number of lines to allow, or -1 to
* cancel a previous limit and allow as many lines
* as will fit in the current history buffer size.
*/
void gl_limit_history(GetLine *gl, int max_lines);
/*.......................................................................
* Discard either all historical lines, or just those associated with the
* current history group.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* all_groups int If true, clear all of the history. If false,
* clear only the stored lines associated with the
* currently selected history group.
*/
void gl_clear_history(GetLine *gl, int all_groups);
/*.......................................................................
* Temporarily enable or disable the gl_get_line() history mechanism.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* enable int If true, turn on the history mechanism. If
* false, disable it.
*/
void gl_toggle_history(GetLine *gl, int enable);
/*
* Objects of the following type are returned by gl_terminal_size().
*/
typedef struct {
int nline; /* The terminal has nline lines */
int ncolumn; /* The terminal has ncolumn columns */
} GlTerminalSize;
/*.......................................................................
* Update if necessary, and return the current size of the terminal.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* def_ncolumn int If the number of columns in the terminal
* can't be determined, substitute this number.
* def_nline int If the number of lines in the terminal can't
* be determined, substitute this number.
* Output:
* return GlTerminalSize The current terminal size.
*/
GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline);
/*.......................................................................
* Tell gl_get_line() the current terminal size. Note that this is only
* necessary on systems where changes in terminal size aren't reported
* via SIGWINCH.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* ncolumn int The number of columns in the terminal.
* nline int The number of rows in the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_set_term_size(GetLine *gl, int ncolumn, int nline);
/*
* The gl_lookup_history() function returns information in an
* argument of the following type.
*/
typedef struct {
const char *line; /* The requested history line */
unsigned group; /* The history group to which the */
/* line belongs. */
time_t timestamp; /* The date and time at which the */
/* line was originally entered. */
} GlHistoryLine;
/*.......................................................................
* Lookup a history line by its sequential number of entry in the
* history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* id unsigned long The identification number of the line to
* be returned, where 0 denotes the first line
* that was entered in the history list, and
* each subsequently added line has a number
* one greater than the previous one. For
* the range of lines currently in the list,
* see the gl_range_of_history() function.
* Input/Output:
* line GlHistoryLine * A pointer to the variable in which to
* return the details of the line.
* Output:
* return int 0 - The line is no longer in the history
* list, and *line has not been changed.
* 1 - The requested line can be found in
* *line. Note that the string in
* line->line is part of the history
* buffer and will change, so a private
* copy should be made if you wish to
* use it after subsequent calls to any
* functions that take gl as an argument.
*/
int gl_lookup_history(GetLine *gl, unsigned long id, GlHistoryLine *line);
/*
* The gl_state_of_history() function returns information in an argument
* of the following type.
*/
typedef struct {
int enabled; /* True if history is enabled */
unsigned group; /* The current history group */
int max_lines; /* The current upper limit on the number of lines */
/* in the history list, or -1 if unlimited. */
} GlHistoryState;
/*.......................................................................
* Query the state of the history list. Note that any of the input/output
* pointers can be specified as NULL.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* state GlHistoryState * A pointer to the variable in which to record
* the return values.
*/
void gl_state_of_history(GetLine *gl, GlHistoryState *state);
/*
* The gl_range_of_history() function returns information in an argument
* of the following type.
*/
typedef struct {
unsigned long oldest; /* The sequential entry number of the oldest */
/* line in the history list. */
unsigned long newest; /* The sequential entry number of the newest */
/* line in the history list. */
int nlines; /* The number of lines in the history list */
} GlHistoryRange;
/*.......................................................................
* Query the number and range of lines in the history buffer.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* range GlHistoryRange * A pointer to the variable in which to record
* the return values. If range->nline=0, the
* range of lines will be given as 0-0.
*/
void gl_range_of_history(GetLine *gl, GlHistoryRange *range);
/*
* The gl_size_of_history() function returns information in an argument
* of the following type.
*/
typedef struct {
size_t size; /* The size of the history buffer (bytes) */
size_t used; /* The number of bytes of the history buffer */
/* that are currently occupied. */
} GlHistorySize;
/*.......................................................................
* Return the size of the history buffer and the amount of the
* buffer that is currently in use.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* GlHistorySize size * A pointer to the variable in which to return
* the results.
*/
void gl_size_of_history(GetLine *gl, GlHistorySize *size);
/*.......................................................................
* Enable or disable the automatic addition of newly entered lines to the
* history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* enable int If true, subsequently entered lines will
* automatically be added to the history list
* before they are returned to the caller of
* gl_get_line(). If 0, the choice of how and
* when to archive lines in the history list,
* is left up to the calling application, which
* can do so via calls to gl_append_history().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_automatic_history(GetLine *gl, int enable);
/*.......................................................................
* Append a specified line to the history list.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* line const char * The line to be added.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_append_history(GetLine *gl, const char *line);
/*.......................................................................
* Specify whether text that users type should be displayed or hidden.
* In the latter case, only the prompt is displayed, and the final
* input line is not archived in the history list.
*
* Input:
* gl GetLine * The input-line history maintenance object.
* enable int 0 - Disable echoing.
* 1 - Enable echoing.
* -1 - Just query the mode without changing it.
* Output:
* return int The echoing disposition that was in effect
* before this function was called:
* 0 - Echoing was disabled.
* 1 - Echoing was enabled.
*/
int gl_echo_mode(GetLine *gl, int enable);
/*.......................................................................
* This function can be called from gl_get_line() callbacks to have
* the prompt changed when they return. It has no effect if gl_get_line()
* is not currently being invoked.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* prompt const char * The new prompt.
*/
void gl_replace_prompt(GetLine *gl, const char *prompt);
/*
* Enumerate the available prompt formatting styles.
*/
typedef enum {
GL_LITERAL_PROMPT, /* Display the prompt string literally */
GL_FORMAT_PROMPT /* The prompt string can contain any of the */
/* following formatting directives: */
/* %B - Display subsequent characters */
/* with a bold font. */
/* %b - Stop displaying characters */
/* with the bold font. */
/* %U - Underline subsequent characters. */
/* %u - Stop underlining characters. */
/* %S - Highlight subsequent characters */
/* (also known as standout mode). */
/* %s - Stop highlighting characters */
/* %% - Display a single % character. */
} GlPromptStyle;
/*.......................................................................
* Specify whether to heed text attribute directives within prompt
* strings.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* style GlPromptStyle The style of prompt (see the definition of
* GlPromptStyle in libtecla.h for details).
*/
void gl_prompt_style(GetLine *gl, GlPromptStyle style);
/*.......................................................................
* Remove a signal from the list of signals that gl_get_line() traps.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* signo int The number of the signal to be ignored.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_ignore_signal(GetLine *gl, int signo);
/*
* A bitwise union of the following enumerators is passed to
* gl_trap_signal() to specify the environment in which the
* application's signal handler is to be called.
*/
typedef enum {
GLS_RESTORE_SIG=1, /* Restore the caller's signal environment */
/* while handling the signal. */
GLS_RESTORE_TTY=2, /* Restore the caller's terminal settings */
/* while handling the signal. */
GLS_RESTORE_LINE=4, /* Move the cursor to the start of the next line */
GLS_REDRAW_LINE=8, /* Redraw the input line when the signal handler */
/* returns. */
GLS_UNBLOCK_SIG=16, /* Normally a signal who's delivery is found to */
/* be blocked by the calling application is not */
/* trapped by gl_get_line(). Including this flag */
/* causes it to be temporarily unblocked and */
/* trapped while gl_get_line() is executing. */
GLS_DONT_FORWARD=32,/* Don't forward the signal to the signal handler */
/* of the calling program. */
GLS_RESTORE_ENV = GLS_RESTORE_SIG | GLS_RESTORE_TTY | GLS_REDRAW_LINE,
GLS_SUSPEND_INPUT = GLS_RESTORE_ENV | GLS_RESTORE_LINE
} GlSignalFlags;
/*
* The following enumerators are passed to gl_trap_signal() to tell
* it what to do after the application's signal handler has been called.
*/
typedef enum {
GLS_RETURN, /* Return the line as though the user had pressed the */
/* return key. */
GLS_ABORT, /* Cause gl_get_line() to return NULL */
GLS_CONTINUE /* After handling the signal, resume command line editing */
} GlAfterSignal;
/*.......................................................................
* Tell gl_get_line() how to respond to a given signal. This can be used
* both to override the default responses to signals that gl_get_line()
* normally catches and to add new signals to the list that are to be
* caught.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* signo int The number of the signal to be caught.
* flags unsigned A bitwise union of GlSignalFlags enumerators.
* after GlAfterSignal What to do after the application's signal
* handler has been called.
* errno_value int The value to set errno to.
* Output:
* return int 0 - OK.
* 1 - Insufficient memory to record the
* new signal disposition.
*/
int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
GlAfterSignal after, int errno_value);
/*.......................................................................
* By default, gl_get_line() doesn't trap signals that are blocked
* when it is called. This default can be changed either on a
* per-signal basis by calling gl_trap_signal(), or on a global basis
* by calling this function. What this function does is add the
* GLS_UNBLOCK_SIG flag to all signals that are currently configured
* to be trapped by gl_get_line(), such that when subsequent calls to
* gl_get_line() wait for I/O, these signals are temporarily
* unblocked. This behavior is useful in non-blocking server-I/O mode,
* where it is used to avoid race conditions related to handling these
* signals externally to gl_get_line(). See the demonstration code in
* demo3.c, or the gl_handle_signal() man page for further
* information.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
*/
void gl_catch_blocked(GetLine *gl);
/*.......................................................................
* In server-I/O mode the terminal is left in raw mode between calls
* to gl_get_line(), so it is necessary for the application to install
* terminal restoring signal handlers for signals that could terminate
* or suspend the process, plus a terminal reconfiguration handler to
* be called when a process resumption signal is received, and finally
* a handler to be called when a terminal-resize signal is received.
*
* Since there are many signals that by default terminate or suspend
* processes, and different systems support different sub-sets of
* these signals, this function provides a convenient wrapper around
* sigaction() for assigning the specified handlers to all appropriate
* signals. It also arranges that when any one of these signals is
* being handled, all other catchable signals are blocked. This is
* necessary so that the specified signal handlers can safely call
* gl_raw_io(), gl_normal_io() and gl_update_size() without reentrancy
* issues.
*
* Input:
* term_handler void (*)(int) The signal handler to invoke when
* a process terminating signal is
* received.
* susp_handler void (*)(int) The signal handler to invoke when
* a process suspending signal is
* received.
* cont_handler void (*)(int) The signal handler to invoke when
* a process resumption signal is
* received (ie. SIGCONT).
* size_handler void (*)(int) The signal handler to invoke when
* a terminal-resize signal (ie. SIGWINCH)
* is received.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_tty_signals(void (*term_handler)(int), void (*susp_handler)(int),
void (*cont_handler)(int), void (*size_handler)(int));
/*.......................................................................
* Return the last signal that was caught by the most recent call to
* gl_get_line(), or -1 if no signals were caught. This is useful if
* gl_get_line() returns errno=EINTR and you need to find out what signal
* caused it to abort.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int The last signal caught by the most recent
* call to gl_get_line(), or -1 if no signals
* were caught.
*/
int gl_last_signal(GetLine *gl);
/*.......................................................................
* Return the signal mask used by gl_get_line(). This is the set of
* signals that gl_get_line() is currently configured to trap.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* set sigset_t * The set of signals will be returned in *set,
* in the form of a signal process mask, as
* used by sigaction(), sigprocmask(),
* sigpending(), sigsuspend(), sigsetjmp() and
* other standard POSIX signal-aware
* functions.
* Output:
* return int 0 - OK.
* 1 - Error (examine errno for reason).
*/
int gl_list_signals(GetLine *gl, sigset_t *set);
/*.......................................................................
* Respond to signals who's default effects have important
* consequences to gl_get_line(). This is intended for use in
* non-blocking server mode, where the external event loop is
* responsible for catching signals. Signals that are handled include
* those that by default terminate or suspend the process, and the
* signal that indicates that the terminal size has changed. Note that
* this function is not signal safe and should thus not be called from
* a signal handler itself. See the gl_io_mode() man page for how it
* should be used.
*
* In the case of signals that by default terminate or suspend
* processes, command-line editing will be suspended, the terminal
* returned to a usable state, then the default disposition of the
* signal restored and the signal resent, in order to suspend or
* terminate the process. If the process subsequently resumes,
* command-line editing is resumed.
*
* In the case of signals that indicate that the terminal has been
* resized, the new size will be queried, and any input line that is
* being edited will be redrawn to fit the new dimensions of the
* terminal.
*
* Input:
* signo int The number of the signal to respond to.
* gl GetLine * The first element of an array of 'ngl' GetLine
* objects.
* ngl int The number of elements in the gl[] array. Normally
* this will be one.
*/
void gl_handle_signal(int signo, GetLine *gl, int ngl);
/*.......................................................................
* Return extra information (ie. in addition to that provided by errno)
* about the last error to occur in either gl_get_line() or its
* associated public functions.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Input/Output:
* buff char * An optional output buffer. Note that if the
* calling application calls any gl_*()
* functions from signal handlers, it should
* provide a buffer here, so that a copy of
* the latest error message can safely be made
* while signals are blocked.
* n size_t The allocated size of buff[].
* Output:
* return const char * A pointer to the error message. This will
* be the buff argument, unless buff==NULL, in
* which case it will be a pointer to an
* internal error buffer. In the latter case,
* note that the contents of the returned buffer
* will change on subsequent calls to any gl_*()
* functions.
*/
const char *gl_error_message(GetLine *gl, char *buff, size_t n);
/*.......................................................................
* Clear the terminal and leave the cursor at the home position. In
* server I/O mode, arrange for the input line to be redrawn from scratch
* when gl_get_line() is next called.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_erase_terminal(GetLine *gl);
/*.......................................................................
* Display a left-justified string over multiple terminal lines,
* taking account of the current width of the terminal. Optional
* indentation and an optional prefix string can be specified to be
* displayed at the start of each new terminal line used. Similarly,
* an optional suffix can be specified to be displayed at the end of
* each terminal line. If needed, a single paragraph can be broken
* across multiple calls. Note that literal newlines in the input
* string can be used to force a newline at any point and that you
* should use this feature to explicitly end all paragraphs, including
* at the end of the last string that you write. Note that when a new
* line is started between two words that are separated by spaces,
* those spaces are not output, whereas when a new line is started
* because a newline character was found in the string, only the
* spaces before the newline character are discarded.
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* indentation int The number of spaces of indentation to write
* at the beginning of each new terminal line.
* prefix const char * An optional prefix string to write after the
* indentation margin at the start of each new
* terminal line. You can specify NULL if no
* prefix is required.
* suffix const char * An optional suffix string to draw at the end
* of the terminal line. Spaces will be added
* where necessary to ensure that the suffix ends
* in the last column of the terminal line. If
* no suffix is desired, specify NULL.
* fill_char int The padding character to use when indenting
* the line or padding up to the suffix.
* def_width int If the terminal width isn't known, such as when
* writing to a pipe or redirecting to a file,
* this number specifies what width to assume.
* start int The number of characters already written to
* the start of the current terminal line. This
* is primarily used to allow individual
* paragraphs to be written over multiple calls
* to this function, but can also be used to
* allow you to start the first line of a
* paragraph with a different prefix or
* indentation than those specified above.
* string const char * The string to be written.
* Output:
* return int On error -1 is returned. Otherwise the
* return value is the terminal column index at
* which the cursor was left after writing the
* final word in the string. Successful return
* values can thus be passed verbatim to the
* 'start' arguments of subsequent calls to
* gl_display_text() to allow the printing of a
* paragraph to be broken across multiple calls
* to gl_display_text().
*/
int gl_display_text(GetLine *gl, int indentation, const char *prefix,
const char *suffix, int fill_char, int def_width,
int start, const char *string);
/*
* Enumerate the I/O modes supported by gl_get_line().
*/
typedef enum {
GL_NORMAL_MODE, /* Normal line-at-a-time mode using gl_get_line()'s */
/* internal event loop. */
GL_SERVER_MODE /* Non-blocking server mode, driven by an external */
/* event loop. */
} GlIOMode;
/*.......................................................................
* Select the I/O mode to be used by gl_get_line().
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* mode GlIOMode The I/O mode to establish. Note that
* when server mode, the terminal is placed
* in raw mode, as though gl_raw_io() had
* been called.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_io_mode(GetLine *gl, GlIOMode mode);
/*.......................................................................
* In server mode, this function configures the terminal for non-blocking
* raw terminal I/O. In normal I/O mode it does nothing.
*
* Callers of this function must be careful to trap all signals that
* terminate or suspend the program, and call gl_normal_io()
* from the corresponding signal handlers in order to restore the
* terminal to its original settings before the program is terminated
* or suspended. They should also trap the SIGCONT signal to detect
* when the program resumes, and ensure that its signal handler
* call gl_raw_io() to redisplay the line and resume editing.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_raw_io(GetLine *gl);
/*.......................................................................
* Restore the terminal to the state that it had when gl_raw_io() was
* last called. After calling gl_raw_io(), this function must be called
* before terminating or suspending the program, and before attempting
* other uses of the terminal from within the program. See gl_raw_io()
* for more details.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_normal_io(GetLine *gl);
/*.......................................................................
* When in non-blocking server mode, this function can be used to abandon
* the current incompletely entered input line, and prepare to start
* editing a new line on the next call to gl_get_line().
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
void gl_abandon_line(GetLine *gl);
/*
* Enumerators of the following type are used to report why
* gl_get_line() returned. This is most useful in non-blocking
* server mode, since in that mode a NULL return value can mean
* either that an error occurred, or that I/O blocked.
*/
typedef enum {
GLR_NEWLINE, /* A new input line was returned */
GLR_BLOCKED, /* The terminal was in non-blocking mode, and input */
/* or output would have blocked. */
GLR_SIGNAL, /* A signal caused gl_get_line() to return. */
GLR_TIMEOUT, /* An application timeout callback returned GLTO_ABORT */
GLR_FDABORT, /* An application I/O callack returned GLFD_ABORT */
GLR_EOF, /* End of file reached */
GLR_ERROR /* An unexpected error caused gl_get_line() to abort */
} GlReturnStatus;
/*.......................................................................
* Ask gl_get_line() what caused it to return.
*
* Input:
* gl GetLine * The line editor resource object.
* Output:
* return GlReturnStatus The return status of the last call to
* gl_get_line().
*/
GlReturnStatus gl_return_status(GetLine *gl);
/*
* Enumerate the types of I/O that gl_get_line() can be waiting for
* in non-blocking sedrver I/O mode.
*/
typedef enum {
GLP_READ, /* gl_get_line() is waiting to write to the terminal */
GLP_WRITE /* gl_get_line() is waiting to read from the terminal */
} GlPendingIO;
/*.......................................................................
* In non-blocking server-I/O mode, this function should be called
* from the application's external event loop to see what type of
* terminal I/O is being waited for by gl_get_line(), and thus what
* direction of I/O to wait for with select() or poll().
*
* Input:
* gl GetLine * The resource object of gl_get_line().
* Output:
* return GlPendingIO The type of pending I/O being waited for.
*/
GlPendingIO gl_pending_io(GetLine *gl);
/*
* The following enumerators are returned by externally defined action
* functions to tell gl_get_line() how to procede after the action
* function returns.
*/
typedef enum {
GLA_ABORT, /* Cause gl_get_line() to return NULL */
GLA_RETURN, /* Return the line as though the user had pressed the */
/* return key. */
GLA_CONTINUE /* Resume command-line editing */
} GlAfterAction;
/*.......................................................................
* Functions of the following form implement external
* application-specific action functions, which can then be bound to
* sequences of terminal keys.
*
* Input:
* gl GetLine * The line editor resource object.
* data void * The anonymous 'data' argument that was
* passed to gl_external_action() when the
* callback function was registered.
* count int A positive repeat count specified by the user,
* or 1 if not specified. Action functions should
* ignore this if repeating the action multiple
* times isn't appropriate. Alternatively they
* can interpret it as a general numeric
* argument.
* curpos size_t The position of the cursor within the input
* line, expressed as the index of the
* corresponding character within the line[]
* array.
* line const char * A read-only copy of the current input line.
* Output
* return GlAfterAction What should gl_get_line() do when the action
* function returns?
* GLA_ABORT - Cause gl_get_line() to
* abort with an error (set
* errno if you need it).
* GLA_RETURN - Return the input line as
* though the user had typed
* the return key.
* GLA_CONTINUE - Resume waiting for keyboard
* input.
*/
#define GL_ACTION_FN(fn) GlAfterAction (fn)(GetLine *gl, void *data, \
int count, size_t curpos, const char *line)
typedef GL_ACTION_FN(GlActionFn);
/*.......................................................................
* Register an application-provided function as an action function.
* This should preferably be called before the first call to gl_get_line()
* so that the name of the action becomes defined before the user's
* configuration file is read.
*
* Input:
* gl GetLine * The resource object of the command-line input
* module.
* data void * Arbitrary application-specific callback
* data to be passed to the callback
* function, fn().
* fn GlActionFn * The application-specific function that
* implements the action. This will be invoked
* whenever the user presses any
* key-sequence which is bound to this action.
* name const char * The name with which users can refer to the
* binding in tecla configuration files.
* keyseq const char * The key sequence with which to invoke
* the binding. This should be specified in the
* same manner as key-sequences in tecla
* configuration files (eg. "M-^I").
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
const char *name, const char *keyseq);
/*.......................................................................
* This function is designed to be called by CPL_MATCH_FN() callback
* functions. It adds one possible completion of the token that is being
* completed to an array of completions. If the completion needs any
* special quoting to be valid when displayed in the input line, this
* quoting must be included in the string.
*
* Input:
* cpl WordCompletion * The argument of the same name that was passed
* to the calling CPL_MATCH_FN() callback function.
* line const char * The input line, as received by the callback
* function.
* word_start int The index within line[] of the start of the
* word that is being completed. If an empty
* string is being completed, set this to be
* the same as word_end.
* word_end int The index within line[] of the character which
* follows the incomplete word, as received by the
* callback function.
* suffix const char * The appropriately quoted string that could
* be appended to the incomplete token to complete
* it. A copy of this string will be allocated
* internally.
* type_suffix const char * When listing multiple completions, gl_get_line()
* appends this string to the completion to indicate
* its type to the user. If not pertinent pass "".
* Otherwise pass a literal or static string.
* cont_suffix const char * If this turns out to be the only completion,
* gl_get_line() will append this string as
* a continuation. For example, the builtin
* file-completion callback registers a directory
* separator here for directory matches, and a
* space otherwise. If the match were a function
* name you might want to append an open
* parenthesis, etc.. If not relevant pass "".
* Otherwise pass a literal or static string.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int cpl_add_completion(WordCompletion *cpl, const char *line,
int word_start, int word_end, const char *suffix,
const char *type_suffix, const char *cont_suffix);
/*
* Each possible completion string is recorded in an array element of
* the following type.
*/
typedef struct {
char *completion; /* The matching completion string */
char *suffix; /* The pointer into completion[] at which the */
/* string was extended. */
const char *type_suffix; /* A suffix to be added when listing completions */
/* to indicate the type of the completion. */
} CplMatch;
/*
* Completions are returned in a container of the following form.
*/
typedef struct {
char *suffix; /* The common initial part of all of the */
/* completion suffixes. */
const char *cont_suffix; /* Optional continuation string to be appended to */
/* the sole completion when nmatch==1. */
CplMatch *matches; /* The array of possible completion strings, */
/* sorted into lexical order. */
int nmatch; /* The number of elements in matches[] */
} CplMatches;
/*.......................................................................
* Given an input line and the point at which completion is to be
* attempted, return an array of possible completions.
*
* Input:
* cpl WordCompletion * The word-completion resource object.
* line const char * The current input line.
* word_end int The index of the character in line[] which
* follows the end of the token that is being
* completed.
* data void * Anonymous 'data' to be passed to match_fn().
* match_fn CplMatchFn * The function that will identify the prefix
* to be completed from the input line, and
* record completion suffixes.
* Output:
* return CplMatches * The container of the array of possible
* completions. The returned pointer refers
* to a container owned by the parent Completion
* object, and its contents thus potentially
* change on every call to cpl_complete_word().
*/
CplMatches *cpl_complete_word(WordCompletion *cpl, const char *line,
int word_end, void *data,
CplMatchFn *match_fn);
/*.......................................................................
* Recall the return value of the last call to cpl_complete_word().
*
* Input:
* cpl WordCompletion * The completion resource object.
* Output:
* return CplMatches * The container of the array of possible
* completions, as returned by the last call to
* cpl_complete_word(). The returned pointer refers
* to a container owned by the parent WordCompletion
* object, and its contents thus potentially
* change on every call to cpl_complete_word().
* On error, either in the execution of this
* function, or in the last call to
* cpl_complete_word(), NULL is returned, and a
* description of the error can be acquired by
* calling cpl_last_error(cpl).
*/
CplMatches *cpl_recall_matches(WordCompletion *cpl);
/*.......................................................................
* Print out an array of matching completions.
*
* Input:
* result CplMatches * The container of the sorted array of
* completions.
* fp FILE * The output stream to write to.
* term_width int The width of the terminal.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
int cpl_list_completions(CplMatches *result, FILE *fp, int term_width);
/*.......................................................................
* Return a description of the error that occurred on the last call to
* cpl_complete_word() or cpl_add_completion().
*
* Input:
* cpl WordCompletion * The string-completion resource object.
* Output:
* return const char * The description of the last error.
*/
const char *cpl_last_error(WordCompletion *cpl);
/*
* PathCache objects encapsulate the resources needed to record
* files of interest from comma-separated lists of directories.
*/
typedef struct PathCache PathCache;
/*.......................................................................
* Create an object who's function is to maintain a cache of filenames
* found within a list of directories, and provide quick lookup and
* completion of selected files in this cache.
*
* Output:
* return PathCache * The new, initially empty cache, or NULL
* on error.
*/
PathCache *new_PathCache(void);
/*.......................................................................
* Delete a given cache of files, returning the resources that it
* was using to the system.
*
* Input:
* pc PathCache * The cache to be deleted (can be NULL).
* Output:
* return PathCache * The deleted object (ie. allways NULL).
*/
PathCache *del_PathCache(PathCache *pc);
/*.......................................................................
* Return a description of the last path-caching error that occurred.
*
* Input:
* pc PathCache * The filename cache that suffered the error.
* Output:
* return char * The description of the last error.
*/
const char *pca_last_error(PathCache *pc);
/*.......................................................................
* Build the list of files of interest contained in a given
* colon-separated list of directories.
*
* Input:
* pc PathCache * The cache in which to store the names of
* the files that are found in the list of
* directories.
* path const char * A colon-separated list of directory
* paths. Under UNIX, when searching for
* executables, this should be the return
* value of getenv("PATH").
* Output:
* return int 0 - OK.
* 1 - An error occurred.
*/
int pca_scan_path(PathCache *pc, const char *path);
/*.......................................................................
* If you want subsequent calls to pca_lookup_file() and
* pca_path_completions() to only return the filenames of certain
* types of files, for example executables, or filenames ending in
* ".ps", call this function to register a file-selection callback
* function. This callback function takes the full pathname of a file,
* plus application-specific data, and returns 1 if the file is of
* interest, and zero otherwise.
*
* Input:
* pc PathCache * The filename cache.
* check_fn CplCheckFn * The function to call to see if the name of
* a given file should be included in the
* cache. This determines what type of files
* will reside in the cache. To revert to
* selecting all files, regardless of type,
* pass 0 here.
* data void * You can pass a pointer to anything you
* like here, including NULL. It will be
* passed to your check_fn() callback
* function, for its private use.
*/
void pca_set_check_fn(PathCache *pc, CplCheckFn *check_fn, void *data);
/*.......................................................................
* Given the simple name of a file, search the cached list of files
* in the order in which they where found in the list of directories
* previously presented to pca_scan_path(), and return the pathname
* of the first file which has this name.
*
* Input:
* pc PathCache * The cached list of files.
* name const char * The name of the file to lookup.
* name_len int The length of the filename substring at the
* beginning of name[], or -1 to assume that the
* filename occupies the whole of the string.
* literal int If this argument is zero, lone backslashes
* in name[] are ignored during comparison
* with filenames in the cache, under the
* assumption that they were in the input line
* soley to escape the special significance of
* characters like spaces. To have them treated
* as normal characters, give this argument a
* non-zero value, such as 1.
* Output:
* return char * The pathname of the first matching file,
* or NULL if not found. Note that the returned
* pointer points to memory owned by *pc, and
* will become invalid on the next call.
*/
char *pca_lookup_file(PathCache *pc, const char *name, int name_len,
int literal);
/*
* Objects of the following type can be used to change the default
* behavior of the pca_path_completions() callback function.
*/
typedef struct PcaPathConf PcaPathConf;
/*
* pca_path_completions() is a completion callback function for use directly
* with cpl_complete_word() or gl_customize_completions(), or indirectly
* from your own completion callback function. It requires that a PcaPathConf
* object be passed via its 'void *data' argument (see below).
*/
CPL_MATCH_FN(pca_path_completions);
/*.......................................................................
* Allocate and initialize a pca_path_completions() configuration object.
*
* Input:
* pc PathCache * The filename cache in which to look for
* file name completions.
* Output:
* return PcaPathConf * The new configuration structure, or NULL
* on error.
*/
PcaPathConf *new_PcaPathConf(PathCache *pc);
/*.......................................................................
* Deallocate memory, previously allocated by new_PcaPathConf().
*
* Input:
* ppc PcaPathConf * Any pointer previously returned by
* new_PcaPathConf() [NULL is allowed].
* Output:
* return PcaPathConf * The deleted structure (always NULL).
*/
PcaPathConf *del_PcaPathConf(PcaPathConf *ppc);
/*
* If backslashes in the prefix being passed to pca_path_completions()
* should be treated as literal characters, call the following function
* with literal=1. Otherwise the default is to treat them as escape
* characters which remove the special meanings of spaces etc..
*/
void ppc_literal_escapes(PcaPathConf *ppc, int literal);
/*
* Before calling pca_path_completions, call this function if you know
* the index at which the filename prefix starts in the input line.
* Otherwise by default, or if you specify start_index to be -1, the
* filename is taken to start after the first unescaped space preceding
* the cursor, or the start of the line, whichever comes first.
*/
void ppc_file_start(PcaPathConf *ppc, int start_index);
#ifdef __cplusplus
}
#endif
#endif
|