summaryrefslogtreecommitdiffstats
path: root/libtecla-1.4.1/getline.c
blob: 242fae34fc730a11f51f06fa797afa6f9fefedd5 (plain) (blame)
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
/*
 * Copyright (c) 2000, 2001 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.
 */

/*
 * Standard headers.
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <setjmp.h>

/*
 * UNIX headers.
 */
#include <sys/ioctl.h>
#ifdef HAVE_SELECT
#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
/*
 * 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 FILE *tputs_fp = NULL;
/*
 * 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
static int gl_tputs_putchar(char c) {return putc(c, tputs_fp);}
#elif defined(__APPLE__) && defined(__MACH__)
static void gl_tputs_putchar(int c) {(void) putc(c, tputs_fp);}
#else
static int gl_tputs_putchar(int c) {return putc(c, tputs_fp);}
#endif
#endif

/*
 * POSIX headers.
 */
#include <unistd.h>
#include <termios.h>

/*
 * Does the system provide the signal and ioctl query facility used
 * to inform the process of terminal window size changes?
 */
#if defined(SIGWINCH) && defined(TIOCGWINSZ)
#define USE_SIGWINCH 1
#endif

/*
 * Provide typedefs for standard POSIX structures.
 */
typedef struct sigaction SigAction;
typedef struct termios Termios;

/*
 * Local headers.
 */
#include "pathutil.h"
#include "libtecla.h"
#include "keytab.h"
#include "history.h"
#include "freelist.h"
#include "stringrp.h"
#include "getline.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;

/*
 * 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 {
  KtKeyFn *fn;               /* 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_character() */
                             /*  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

/*
 * Listen for and handle file-descriptor events.
 */
static int gl_event_handler(GetLine *gl);

static int gl_call_fd_handler(GetLine *gl, GlFdHandler *gfh, int fd,
			      GlFdEvent event);
#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

/*
 * Define the contents of the GetLine object.
 * Note that the typedef for this object can be found in libtecla.h.
 */
struct GetLine {
  GlHistory *glh;            /* The line-history buffer */
  WordCompletion *cpl;       /* String completion resource object */
  CplMatchFn(*cpl_fn);       /* The tab completion callback function */
  void *cpl_data;            /* Callback data to pass to cpl_fn() */
  ExpandFile *ef;            /* ~user/, $envvar and wildcard expansion */
                             /*  resource object. */
  StringGroup *capmem;       /* Memory for recording terminal capability */
                             /*  strings. */
  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 */
  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[] */
  const 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 *sig_mem;         /* Memory for nodes of the signal list */
  GlSignalNode *sigs;        /* The head of the list of signals */
  sigset_t old_signal_set;   /* The signal set on entry to gl_get_line() */
  sigset_t new_signal_set;   /* The set of signals that we are trapping */
  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 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[] */
  KtKeyFn *current_fn;       /* The action function that is currently being */
                             /*  invoked. */
  int current_count;         /* The repeat count passed to current_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 oper_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. */
  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 */
#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

/*
 * 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 errno_value;      /* What to set errno to */
} gl_signal_list[] = {
  {SIGABRT,   GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
  {SIGINT,    GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
  {SIGTERM,   GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
  {SIGALRM,   GLS_RESTORE_ENV, GLS_CONTINUE, 0},
  {SIGCONT,   GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#if defined(SIGHUP)
#ifdef ENOTTY
  {SIGHUP,    GLS_SUSPEND_INPUT, GLS_ABORT, ENOTTY},
#else
  {SIGHUP,    GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
#endif
#endif
#if defined(SIGPIPE)
#ifdef EPIPE
  {SIGPIPE,   GLS_SUSPEND_INPUT, GLS_ABORT, EPIPE},
#else
  {SIGPIPE,   GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
#endif
#endif
#ifdef SIGPWR
  {SIGPWR,    GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#endif
#ifdef SIGQUIT
  {SIGQUIT,   GLS_SUSPEND_INPUT, GLS_ABORT, EINTR},
#endif
#ifdef SIGTSTP
  {SIGTSTP,   GLS_SUSPEND_INPUT, GLS_CONTINUE, 0},
#endif
#ifdef SIGTTIN
  {SIGTTIN,   GLS_SUSPEND_INPUT, GLS_CONTINUE, 0},
#endif
#ifdef SIGTTOU
  {SIGTTOU,   GLS_SUSPEND_INPUT, GLS_CONTINUE, 0},
#endif
#ifdef SIGUSR1
  {SIGUSR1,   GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#endif
#ifdef SIGUSR2
  {SIGUSR2,   GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#endif
#ifdef SIGVTALRM
  {SIGVTALRM, GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#endif
#ifdef SIGWINCH
  {SIGWINCH,  GLS_RESTORE_ENV, GLS_CONTINUE, 0},
#endif
#ifdef SIGXCPU
  {SIGXCPU,   GLS_RESTORE_ENV, GLS_CONTINUE, 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);

/*
 * Define a tab to be a string of 8 spaces.
 */
#define TAB_WIDTH 8

/*
 * Does the system send us SIGWINCH signals when the terminal size
 * changes?
 */
#ifdef USE_SIGWINCH
static int gl_resize_terminal(GetLine *gl, int redisplay);
#endif

/*
 * 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);

/*
 * 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);

/*
 * Read a line from the user in raw mode.
 */
static int gl_get_input_line(GetLine *gl, const char *start_line,
			     int start_pos);

/*
 * Set the largest key-sequence that can be handled.
 */
#define GL_KEY_MAX 64

/*
 * 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_output_raw_string(GetLine *gl, const char *string);

/*
 * Output a terminal control sequence.
 */
static int gl_output_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_output_char(GetLine *gl, char c, char pad);
static int gl_output_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);

/*
 * Read a single character from the terminal.
 */
static int gl_read_character(GetLine *gl, char *c);


/*
 * 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);

/*
 * Return the terminal cursor position that corresponds to a given
 * line buffer cursor position.
 */
static int gl_buff_curpos_to_term_curpos(GetLine *gl, int buff_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);

/*
 * 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(KeyTab *bindings, 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);

/*
 * 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 the return the current input line to the caller of gl_get_line().
 */
static int gl_line_ended(GetLine *gl, int newline_char, int archive);

/*
 * 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);
static KT_KEY_FN(gl_expand_filename);
static KT_KEY_FN(gl_del_char_or_list_or_eof);
static KT_KEY_FN(gl_list_or_eof);
static KT_KEY_FN(gl_read_from_file);
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_list_glob);
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_read_init_files);
static KT_KEY_FN(gl_list_history);

/*
 * 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},
  {"expand-filename",            gl_expand_filename},
  {"del-char-or-list-or-eof",    gl_del_char_or_list_or_eof},
  {"read-from-file",             gl_read_from_file},
  {"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},
  {"list-glob",                  gl_list_glob},
  {"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},
  {"read-init-files",            gl_read_init_files},
  {"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"},
  {"^X*",          "expand-filename"},
  {"^X^F",         "read-from-file"},
  {"^X^R",         "read-init-files"},
  {"^Xg",          "list-glob"},
  {"^XG",          "list-glob"},
  {"^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"},
  {"^G",           "list-glob"},
  {"^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"},
  {"^X^F",         "read-from-file"},
  {"^X^R",         "read-init-files"},
  {"^X*",          "expand-filename"},
  {"^?",           "backward-delete-char"},
  {"M- ",          "cursor-right"},
  {"M-$",          "end-of-line"},
  {"M-*",          "expand-filename"},
  {"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"},
  {"M-^X^R",       "read-init-files"},
  {"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) {
    fprintf(stderr, "new_GetLine: Line length too small.\n");
    return NULL;
  };
/*
 * Allocate the container.
 */
  gl = (GetLine *) malloc(sizeof(GetLine));
  if(!gl) {
    fprintf(stderr, "new_GetLine: Insufficient memory.\n");
    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->glh = NULL;
  gl->cpl = NULL;
  gl->cpl_fn = cpl_file_completions;
  gl->cpl_data = NULL;
  gl->ef = NULL;
  gl->capmem = NULL;
  gl->term = NULL;
  gl->is_term = 0;
  gl->input_fd = -1;
  gl->output_fd = -1;
  gl->input_fp = NULL;
  gl->output_fp = NULL;
  gl->file_fp = NULL;
  gl->linelen = linelen;
  gl->line = NULL;
  gl->cutbuf = NULL;
  gl->linelen = linelen;
  gl->prompt = "";
  gl->prompt_len = 0;
  gl->prompt_changed = 0;
  gl->prompt_style = GL_LITERAL_PROMPT;
  gl->vi.undo.line = NULL;
  gl->vi.undo.buff_curpos = 0;
  gl->vi.undo.ntotal = 0;
  gl->vi.undo.saved = 0;
  gl->vi.repeat.fn = 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->sig_mem = NULL;
  gl->sigs = NULL;
  sigemptyset(&gl->old_signal_set);
  sigemptyset(&gl->new_signal_set);
  gl->bindings = NULL;
  gl->ntotal = 0;
  gl->buff_curpos = 0;
  gl->term_curpos = 0;
  gl->buff_mark = 0;
  gl->insert_curpos = 0;
  gl->insert = 1;
  gl->number = -1;
  gl->endline = 0;
  gl->current_fn = 0;
  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->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;
#endif
/*
 * 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.
 */
  gl->ef = new_ExpandFile();
  if(!gl->ef)
    return del_GetLine(gl);
/*
 * 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 a line buffer, leaving 2 extra characters for the terminating
 * '\n' and '\0' characters
 */
  gl->line = (char *) malloc(linelen + 2);
  if(!gl->line) {
    fprintf(stderr,
	    "new_GetLine: Insufficient memory to allocate line buffer.\n");
    return del_GetLine(gl);
  };
  gl->line[0] = '\0';
/*
 * Allocate a cut buffer.
 */
  gl->cutbuf = (char *) malloc(linelen + 2);
  if(!gl->cutbuf) {
    fprintf(stderr,
	    "new_GetLine: Insufficient memory to allocate cut buffer.\n");
    return del_GetLine(gl);
  };
  gl->cutbuf[0] = '\0';
/*
 * Allocate a vi undo buffer.
 */
  gl->vi.undo.line = (char *) malloc(linelen + 2);
  if(!gl->vi.undo.line) {
    fprintf(stderr,
	    "new_GetLine: Insufficient memory to allocate undo buffer.\n");
    return del_GetLine(gl);
  };
  gl->vi.undo.line[0] = '\0';
/*
 * Allocate a freelist from which to allocate nodes for the list
 * of signals.
 */
  gl->sig_mem = _new_FreeList("new_GetLine", sizeof(GlSignalNode),
			      GLS_FREELIST_BLOCKING);
  if(!gl->sig_mem)
    return del_GetLine(gl);
/*
 * Install 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))
      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) {
    fprintf(stderr, "new_GetLine: Insufficient memory for termcap buffers.\n");
    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("new_GetLine", 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) {
    gl->glh = _del_GlHistory(gl->glh);
    gl->cpl = del_WordCompletion(gl->cpl);
    gl->ef = del_ExpandFile(gl->ef);
    gl->capmem = _del_StringGroup(gl->capmem);
    if(gl->line)
      free(gl->line);
    if(gl->cutbuf)
      free(gl->cutbuf);
    if(gl->vi.undo.line)
      free(gl->vi.undo.line);
    gl->sig_mem = _del_FreeList(NULL, gl->sig_mem, 1);
    gl->sigs = NULL;       /* Already freed by freeing sig_mem */
    gl->bindings = _del_KeyTab(gl->bindings);
#ifdef USE_TERMCAP
    if(gl->tgetent_buf)
      free(gl->tgetent_buf);
    if(gl->tgetstr_buf)
      free(gl->tgetstr_buf);
#endif
    if(gl->file_fp)
      fclose(gl->file_fp);
    if(gl->term)
      free(gl->term);
#ifdef HAVE_SELECT
    gl->fd_node_mem = _del_FreeList(NULL, gl->fd_node_mem, 1);
#endif
    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.
 */
  return _kt_set_keybinding(gl->bindings, binder, keyseq, action);
}

/*.......................................................................
 * 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)
{
  int waserr = 0;    /* True if an error occurs */
/*
 * Check the arguments.
 */
  if(!gl || !prompt) {
    fprintf(stderr, "gl_get_line: NULL argument(s).\n");
    return NULL;
  };
/*
 * 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;
  };
/*
 * If input is temporarily being taken from a file, return lines
 * from the file until the file is exhausted, then revert to
 * the normal input stream.
 */
  if(gl->file_fp) {
    if(fgets(gl->line, gl->linelen, gl->file_fp))
      return gl->line;
    gl_revert_input(gl);
  };
/*
 * Is input coming from a non-interactive source?
 */
  if(!gl->is_term)
    return fgets(gl->line, gl->linelen, gl->input_fp);
/*
 * Record the new prompt and its displayed width.
 */
  gl_replace_prompt(gl, prompt);
/*
 * 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_terminal_mode(gl);
/*
 * Attempt to read the line.
 */
  waserr = waserr || gl_get_input_line(gl, start_line, start_pos);
/*
 * Restore terminal settings.
 */
  gl_restore_terminal_attributes(gl);
/*
 * Restore the signal handlers.
 */
  gl_restore_signal_handlers(gl);
/*
 * Having restored the program terminal and signal environment,
 * re-submit any signals that were received.
 */
  if(gl_pending_signal != -1) {
    raise(gl_pending_signal);
    waserr = 1;
  };
/*
 * If gl_get_input_line() aborted input due to the user asking to
 * temporarily read lines from a file, read the first line from
 * this file.
 */
  if(!waserr && gl->file_fp)
    return gl_get_line(gl, prompt, NULL, 0);
/*
 * Return the new input line.
 */
  return waserr ? NULL : gl->line;
}

/*.......................................................................
 * 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;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
/*
 * Get the process signal mask so that we can see which signals the
 * calling program currently has blocked, and so that we can restore this
 * mask before returning to the calling program.
 */
  if(sigprocmask(SIG_SETMASK, NULL, &gl->old_signal_set) == -1) {
    fprintf(stderr, "gl_get_line(): sigprocmask error: %s\n", strerror(errno));
    return 1;
  };
/*
 * Form a new process signal mask from the list of signals that we have
 * been asked to trap.
 */
  sigemptyset(&gl->new_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->new_signal_set, sig->signo) == -1) {
	fprintf(stderr, "gl_get_line(): sigaddset error: %s\n",
		strerror(errno));
	return 1;
      };
    };
  };
/*
 * Before installing our signal handlers, block all of the signals
 * that we are going to be trapping.
 */
  if(sigprocmask(SIG_BLOCK, &gl->new_signal_set, NULL) == -1) {
    fprintf(stderr, "gl_get_line(): sigprocmask error: %s\n", strerror(errno));
    return 1;
  };
/*
 * Override the actions of the signals that we are trapping.
 */
  for(sig=gl->sigs; sig; sig=sig->next) {
    if(sigismember(&gl->new_signal_set, sig->signo) &&
       sigaction(sig->signo, &act, &sig->original)) {
      fprintf(stderr, "gl_get_line(): sigaction error: %s\n", strerror(errno));
      return 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.
 */
#ifdef USE_SIGWINCH
  if(gl_resize_terminal(gl, 0))
    return 1;
#endif
  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->new_signal_set, sig->signo) &&
       sigaction(sig->signo, &sig->original, NULL)) {
      fprintf(stderr, "gl_get_line(): sigaction error: %s\n", strerror(errno));
      return 1;
    };
  };
/*
 * Restore the original signal mask.
 */
  if(sigprocmask(SIG_SETMASK, &gl->old_signal_set, NULL) == -1) {
    fprintf(stderr, "gl_get_line(): sigprocmask error: %s\n", strerror(errno));
    return 1;
  };
  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 */
/*
 * Record the current terminal attributes.
 */
  if(tcgetattr(gl->input_fd, &gl->oldattr)) {
    fprintf(stderr, "getline(): tcgetattr error: %s\n", strerror(errno));
    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] = 1;
  newattr.c_cc[VTIME] = 0;
/*
 * Install the new terminal modes.
 */
  while(tcsetattr(gl->input_fd, TCSADRAIN, &newattr)) {
    if (errno != EINTR) {
      fprintf(stderr, "getline(): tcsetattr error: %s\n", strerror(errno));
      return 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;
/*
 * 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) {
      fprintf(stderr, "gl_get_line(): tcsetattr error: %s\n", strerror(errno));
      waserr = 1;
      break;
    };
  };
  return waserr;
}

/*.......................................................................
 * Read a new input line from the user.
 *
 * Input:
 *  gl         GetLine *  The resource object of this library.
 *  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 *start_line, int start_pos)
{
  char c;       /* The character being read */
/*
 * Reset the properties of the line.
 */
  gl->ntotal = 0;
  gl->buff_curpos = 0;
  gl->term_curpos = 0;
  gl->insert_curpos = 0;
  gl->number = -1;
  gl->endline = 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.fn = 0;
  gl->last_signal = -1;
/*
 * Reset the history search pointers.
 */
  if(_glh_cancel_search(gl->glh))
    return 1;
/*
 * Draw the prompt at the start of the line.
 */
  if(gl_display_prompt(gl))
    return 1;
/*
 * Present an initial line?
 */
  if(start_line) {
    char *cptr;      /* A pointer into gl->line[] */
/*
 * Load the line into the buffer, and display it.
 */
    if(start_line != gl->line)
      strncpy(gl->line, start_line, gl->linelen);
    gl->line[gl->linelen] = '\0';
    gl->ntotal = strlen(gl->line);
/*
 * 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--)
      ;
    if(gl->ntotal < 0)
      gl->ntotal = 0;
    gl->line[gl->ntotal] = '\0';
/*
 * Display the string that remains.
 */
    if(gl_output_string(gl, gl->line, '\0'))
      return 1;
/*
 * 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;
    };
  } else {
    gl->line[0] = '\0';
  };
/*
 * Preload a 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)) {
	gl->ntotal = strlen(gl->line);
	gl->buff_curpos = strlen(gl->line);
      };
      gl->preload_id = 0;
    }; 
    gl_redisplay(gl, 1);
  };
/*
 * Read one character at a time.
 */
  while(gl_read_character(gl, &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, isprint((int)(unsigned char) c) ? c : '\n',
			   gl->echo && (c=='\n' || c=='\r'));
  };
/*
 * To get here, gl_read_character() must have returned non-zero. See
 * if this was because a signal was caught that requested that the
 * current line be returned.
 */
  if(gl->endline)
    return gl_line_ended(gl, '\n', gl->echo);
  return 1;
}

/*.......................................................................
 * 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) {
      memmove(gl->line + buff_curpos + 1, gl->line + buff_curpos,
	      gl->ntotal - buff_curpos);
    };
/*
 * Copy the character into the buffer.
 */
    gl->line[buff_curpos] = c;
    gl->buff_curpos++;
/*
 * If the line was extended, update the record of the string length
 * and terminate the extended string.
 */
    gl->ntotal++;
    gl->line[gl->ntotal] = '\0';
/*
 * 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_output_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 widths of the character to be overwritten and the character
 * that is going to replace it.
 */
    int old_width = gl_displayed_char_width(gl, gl->line[buff_curpos],
					    term_curpos);
/*
 * Overwrite the character in the buffer.
 */
    gl->line[buff_curpos] = c;
/*
 * 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_output_string(gl, gl->line + buff_curpos, '\0'))
	return 1;
/*
 * Clear to the end of the terminal.
 */
      if(gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
	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_output_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->line[buff_curpos] = c;
      gl->buff_curpos++;
/*
 * Overwrite the original character.
 */
      if(gl_output_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) {
    memmove(gl->line + gl->buff_curpos + buff_slen, gl->line + gl->buff_curpos,
	    gl->ntotal - gl->buff_curpos);
  };
/*
 * Copy the string into the buffer.
 */
  memcpy(gl->line + gl->buff_curpos, s, buff_slen);
  gl->ntotal += buff_slen;
  gl->buff_curpos += buff_slen;
/*
 * Maintain the buffer properly terminated.
 */
  gl->line[gl->ntotal] = '\0';
/*
 * 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_output_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.
 * 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_character(GetLine *gl, char *c)
{
/*
 * Before waiting for a new character to be input, flush unwritten
 * characters to the terminal.
 */
  if(gl_flush_output(gl))
    return 1;
/*
 * We may have to repeat the read if window change signals are received.
 */
  for(;;) {
/*
 * If the endline flag becomes set, don't wait for another character.
 */
    if(gl->endline)
      return 1;
/*
 * Since the code in this function can block, trap signals.
 */
    if(sigsetjmp(gl_setjmp_buffer, 1)==0) {
/*
 * Unblock the signals that we are trapping.
 */
      if(sigprocmask(SIG_UNBLOCK, &gl->new_signal_set, NULL) == -1) {
	fprintf(stderr, "getline(): sigprocmask error: %s\n", strerror(errno));
	return 1;
      };
/*
 * If select() is available, watch for activity on any file descriptors
 * that the user has registered, and for data available on the terminal
 * file descriptor.
 */
#ifdef HAVE_SELECT
      if(gl_event_handler(gl))
	return 1;
#endif
/*
 * Read one character from the terminal. This could take more
 * than one call if an interrupt that we aren't trapping is
 * received.
 */
      while(read(gl->input_fd, (void *)c, 1) != 1) {
	if(errno != EINTR) {
#ifdef EAGAIN
	  if(!errno)          /* This can happen with SysV O_NDELAY */
	    errno = EAGAIN;
#endif
	  return 1;
	};
      };
/*
 * Block all of the signals that we are trapping.
 */
      if(sigprocmask(SIG_BLOCK, &gl->new_signal_set, NULL) == -1) {
	fprintf(stderr, "getline(): sigprocmask error: %s\n", strerror(errno));
	return 1;
      };
      return 0;
    };
/*
 * 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.
 */
    if(gl_check_caught_signal(gl))
      return 1;
  };
}

/*.......................................................................
 * 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 */
/*
 * Was no signal caught?
 */
  if(gl_pending_signal == -1)
    return 0;
/*
 * Record the signal that was caught, so that the user can query it later.
 */
  gl->last_signal = gl_pending_signal;
/*
 * Did we receive a terminal size signal?
 */
#ifdef USE_SIGWINCH
  if(gl_pending_signal == SIGWINCH && gl_resize_terminal(gl, 1))
    return 1;
#endif
/*
 * Lookup the requested disposition of this signal.
 */
  for(sig=gl->sigs; sig && sig->signo != gl_pending_signal; sig=sig->next)
    ;
  if(!sig)
    return 0;
/*
 * Start a fresh line?
 */
  if(sig->flags & GLS_RESTORE_LINE) {
    if(gl_set_term_curpos(gl, gl_buff_curpos_to_term_curpos(gl, gl->ntotal)) ||
       gl_output_raw_string(gl, "\r\n"))
      return 1;
  };
/*
 * Restore terminal settings to how they were before gl_get_line() was
 * called?
 */
  if(sig->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(sig->flags & GLS_RESTORE_SIG) {
    gl_restore_signal_handlers(gl);
  } 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(!(sig->flags & GLS_DONT_FORWARD))
    raise(gl_pending_signal);
  gl_pending_signal = -1;
/*
 * Reinstate our signal handlers.
 */
  if(sig->flags & GLS_RESTORE_SIG) {
    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(sig->flags & GLS_RESTORE_TTY)
    gl_raw_terminal_mode(gl);
/*
 * Redraw the line?
 */
  if(sig->flags & GLS_REDRAW_LINE && gl_redisplay(gl, 1))
    return 1;
/*
 * Set errno.
 */
  errno = sig->errno_value;
/*
 * What next?
 */
  switch(sig->after) {
  case GLS_RETURN:
    return gl_newline(gl, 1);
    break;
  case GLS_ABORT:
    return 1;
    break;
  case GLS_CONTINUE:
    return 0;
    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
  if(!term || setupterm((char *)term, gl->input_fd, NULL) == 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) {
    fprintf(stderr, "Bad terminal type: \"%s\". Will assume vt100.\n",
	    term ? term : "(null)");
  };
/*
 * 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);
  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_character(gl, &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 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 TAB_WIDTH - ((term_curpos % gl->ncolumn) % TAB_WIDTH);
  if(IS_CTRL_CHAR(c))
    return 2;
  if(!isprint((int)(unsigned char) c)) {
    char string[TAB_WIDTH + 4];
    sprintf(string, "\\%o", (int)(unsigned char)c);
    return strlen(string);
  };
  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 directly to the terminal.
 *
 * Input:
 *  gl     GetLine *   The resource object of this program.
 *  string    char *   The string to be written.
 * Output:
 *  return     int     0 - OK.
 *                     1 - Error.
 */
static int gl_output_raw_string(GetLine *gl, const char *string)
{
  if(gl->echo) {
    int ndone = 0;   /* The number of characters written so far */
/*
 * How long is the string to be written?
 */
    int slen = strlen(string);
/*
 * Attempt to write the string to the terminal, restarting the
 * write if a signal is caught.
 */
    while(ndone < slen) {
      int nnew = fwrite(string + ndone, sizeof(char), slen-ndone,
			gl->output_fp);
      if(nnew > 0)
	ndone += nnew;
      else if(errno != EINTR)
	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_output_control_sequence(GetLine *gl, int nline,
				      const char *string)
{
  if(gl->echo) {
#if defined(USE_TERMINFO) || defined(USE_TERMCAP)
    tputs_fp = gl->output_fp;
    errno = 0;
    tputs((char *)string, nline, gl_tputs_putchar);
    return errno != 0;
#else
    return gl_output_raw_string(gl, string);
#endif
  };
  return 0;
}

/*.......................................................................
 * 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. */
/*
 * 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_output_control_sequence(gl, 1, gl->down))
      return 1;
  };
/*
 * Move up to the previous line.
 */
  for(; cur_row > new_row; cur_row--) {
    if(gl_output_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_output_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_output_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_output_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_output_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_output_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_char_width(gl, '\t', 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)) {
    sprintf(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_output_raw_string(gl, string))
    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;
/*
 * 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_output_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_output_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_output_char(gl, *cptr, nextc ? nextc : pad))
      return 1;
  };
  return 0;
}

/*.......................................................................
 * Given a character position within gl->line[], work out the
 * corresponding gl->term_curpos position on the terminal.
 *
 * Input:
 *  gl      GetLine *   The resource object of this library.
 *  buff_curpos int     The position within gl->line[].
 *  
 * Output:
 *  return      int     The gl->term_curpos position on the terminal.
 */
static int gl_buff_curpos_to_term_curpos(GetLine *gl, int buff_curpos)
{
  return gl->prompt_len + gl_displayed_string_width(gl, gl->line, buff_curpos,
						    gl->prompt_len);
}

/*.......................................................................
 * 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.
 */
  strcpy(gl->cutbuf, gl->line);
/*
 * Clear the buffer.
 */
  gl->ntotal = 0;
  gl->line[0] = '\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_output_control_sequence(gl, gl->nline, gl->clear_eod))
    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.
 */
  strcpy(gl->cutbuf, gl->line + gl->buff_curpos);
/*
 * Terminate the buffered line at the current cursor position.
 */
  gl->ntotal = gl->buff_curpos;
  gl->line[gl->ntotal] = '\0';
/*
 * Clear the part of the line that follows the cursor.
 */
  if(gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
    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)
      memcpy(gl->line + gl->buff_curpos, gl->vi.undo.line + gl->buff_curpos,
             nrestore);
/*
 * 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->ntotal = gl->vi.undo.ntotal > gl->buff_curpos ? gl->vi.undo.ntotal :
	gl->buff_curpos;
      gl->line[gl->ntotal] = '\0';
    };
  } else {
/*
 * Copy the remaining part of the line back over the deleted characters.
 */
    memmove(gl->line + gl->buff_curpos, gl->line + gl->buff_curpos + nc,
	    gl->ntotal - gl->buff_curpos - nc + 1);
    gl->ntotal -= nc;
  };
/*
 * Redraw the remaining characters following the cursor.
 */
  if(gl_output_string(gl, gl->line + gl->buff_curpos, '\0'))
    return 1;
/*
 * Clear to the end of the terminal.
 */
  if(gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
    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) ||
    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);
  else
    return gl_backward_delete_char(gl, gl->buff_curpos - count);
}

/*.......................................................................
 * 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);
    else
      return gl_backward_delete_char(gl, ++gl->buff_curpos - curpos + 1);
  };
  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))
    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))
    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))
      *cptr = toupper((int) *cptr);
/*
 * 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_output_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))
      *cptr = tolower((int) *cptr);
/*
 * 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_output_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))
	  *cptr = toupper((int) *cptr);
      } else {
	if(isupper((int)(unsigned char) *cptr))
	  *cptr = tolower((int) *cptr);
      };
      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_output_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;
/*
 * Move the cursor to the start of the terminal line, and clear from there
 * to the end of the display.
 */
  if(gl_set_term_curpos(gl, 0) ||
     gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
    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_output_string(gl, gl->line, '\0'))
    return 1;
/*
 * Restore the cursor position.
 */
  if(gl_place_cursor(gl, buff_curpos))
    return 1;
/*
 * 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)
{
/*
 * Record the current cursor position.
 */
  int buff_curpos = gl->buff_curpos;
/*
 * Home the cursor and clear from there to the end of the display.
 */
  if(gl_output_control_sequence(gl, gl->nline, gl->home) ||
     gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
    return 1;
/*
 * Redisplay the line.
 */
  gl->term_curpos = 0;
  gl->buff_curpos = 0;
  if(gl_redisplay(gl,1))
    return 1;
/*
 * Restore the cursor position.
 */
  return gl_place_cursor(gl, buff_curpos);
}

/*.......................................................................
 * 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->line[gl->buff_curpos] = swap[0];
  gl->line[gl->buff_curpos+1] = swap[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_output_char(gl, swap[0], swap[1]) ||
       gl_output_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_output_string(gl, gl->line + gl->buff_curpos, '\0') ||
       gl_output_control_sequence(gl, gl->nline, gl->clear_eod))
      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))
    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);
/*
 * 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))
    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);
/*
 * 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))
    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;
}

#ifdef USE_SIGWINCH
/*.......................................................................
 * Respond to the receipt of a window change signal.
 *
 * Input:
 *  gl     GetLine *  The resource object of this library.
 *  redisplay  int    If true redisplay the current line after
 *                    getting the new window size.
 * Output:
 *  return     int    0 - OK.
 *                    1 - Error.
 */
static int gl_resize_terminal(GetLine *gl, int redisplay)
{
  int lines_used;       /* The number of lines currently in use */
  struct winsize size;  /* The new size information */
  int i;
/*
 * Record the fact that the sigwinch signal has been noted.
 */
  if(gl_pending_signal == SIGWINCH)
    gl_pending_signal = -1;
/*
 * Query the new terminal window size. Ignore invalid responses.
 */
  if(ioctl(gl->output_fd, TIOCGWINSZ, &size) == 0 &&
     size.ws_row > 0 && size.ws_col > 0) {
/*
 * Redisplay the input line?
 */
    if(redisplay) {
/*
 * How many lines are currently displayed.
 */
      lines_used = (gl_displayed_string_width(gl,gl->line,-1,gl->prompt_len) +
		    gl->prompt_len + gl->ncolumn - 1) / gl->ncolumn;
/*
 * Move to the cursor to the start of the line.
 */
      for(i=1; i<lines_used; i++) {
	if(gl_output_control_sequence(gl, 1, gl->up))
	  return 1;
      };
      if(gl_output_control_sequence(gl, 1, gl->bol))
	return 1;
/*
 * Clear to the end of the terminal.
 */
      if(gl_output_control_sequence(gl, size.ws_row, gl->clear_eod))
	return 1;
/*
 * Record the fact that the cursor is now at the beginning of the line.
 */
      gl->term_curpos = 0;
    };
/*
 * Update the recorded window size.
 */
    gl->nline = size.ws_row;
    gl->ncolumn = size.ws_col;
  };
/*
 * Redisplay the line?
 */
  return redisplay ? gl_redisplay(gl,1) : 0;
}
#endif

/*.......................................................................
 * 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;
/*
 * We don't want a search prefix for this function.
 */
  if(_glh_search_prefix(gl->glh, gl->line, 0))
    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) == NULL)
    return 0;
  while(--count && _glh_find_backwards(gl->glh, gl->line, gl->linelen))
    ;
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange to have the cursor placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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);
/*
 * 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);
    gl->preload_id = 0;
  } else {
/*
 * We don't want a search prefix for this function.
 */
    if(_glh_search_prefix(gl->glh, gl->line, 0))
      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) == NULL)
      return 0;
    while(--count && _glh_find_forwards(gl->glh, gl->line, gl->linelen))
      ;
  };
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange to have the cursor placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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;
/*
 * If the previous thing that the user did wasn't to execute a history
 * search function, set the search prefix equal 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 force a repeat search
 * even if the last command wasn't a history command.
 */
  if(gl->last_search != gl->keyseq_count - 1 && count>=0 &&
     _glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
			(gl->editor==GL_VI_MODE && gl->ntotal>0)))
    return 1;
/*
 * Record the key sequence number in which this search function is
 * being executed, so that the next call to this function or
 * gl_history_search_forward() knows if any other operations
 * were performed in between.
 */
  gl->last_search = gl->keyseq_count;
/*
 * 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) == NULL)
    return 0;
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange to have the cursor placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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);
}

/*.......................................................................
 * 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);
/*
 * If the previous thing that the user did wasn't to execute a history
 * search function, set the search prefix equal 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 force a repeat search
 * even if the last command wasn't a history command.
 */
  if(gl->last_search != gl->keyseq_count - 1 && count>=0 &&
     _glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
			(gl->editor==GL_VI_MODE && gl->ntotal>0)))
    return 1;
/*
 * Record the key sequence number in which this search function is
 * being executed, so that the next call to this function or
 * gl_history_search_backward() knows if any other operations
 * were performed in between.
 */
  gl->last_search = gl->keyseq_count;
/*
 * Search forwards for the next matching line.
 */
  if(_glh_find_forwards(gl->glh, gl->line, gl->linelen) == NULL)
    return 0;
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange for the cursor to be placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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);
}

/*.......................................................................
 * This is the tab completion function that completes the filename that
 * precedes the cursor position.
 */
static KT_KEY_FN(gl_complete_word)
{
  CplMatches *matches;    /* The possible completions */
  int redisplay=0;        /* True if the whole line needs to be redrawn */
  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. */
/*
 * In vi command mode, switch to append mode so that the character below
 * the character 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))
    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, gl->cpl_data,
			      gl->cpl_fn);
  if(!matches) {
    if(gl->echo &&
       fprintf(gl->output_fp, "\r\n%s\n", cpl_last_error(gl->cpl)) < 0)
      return 1;
    gl->term_curpos = 0;
    redisplay = 1;
/*
 * 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(fprintf(gl->output_fp, "\r\n") < 0)
	return 1;
      cpl_list_completions(matches, gl->output_fp, gl->ncolumn);
      redisplay = 1;
    };
/*
 * If the callback called gl_change_prompt(), we will need to redisplay
 * the whole line.
 */
    if(gl->prompt_changed)
      redisplay = 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))
	return 1;
    };
/*
 * Work out the number of characters that are to be added.
 */
    nextra = suffix_len + cont_len;
/*
 * Is there anything to be added?
 */
    if(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.
 */
	memmove(gl->line + gl->buff_curpos + nextra, gl->line + gl->buff_curpos,
		gl->ntotal - gl->buff_curpos);
/*
 * Insert the filename extension.
 */
	memcpy(gl->line + gl->buff_curpos, matches->suffix, suffix_len);
/*
 * Add the terminating characters.
 */
	memcpy(gl->line + gl->buff_curpos + suffix_len, matches->cont_suffix,
	       cont_len);
/*
 * Record the increased length of the line.
 */
	gl->ntotal += nextra;
/*
 * Place the cursor position at the end of the completion.
 */
	gl->buff_curpos += nextra;
/*
 * Terminate the extended line.
 */
	gl->line[gl->ntotal] = '\0';
/*
 * 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(!redisplay) {
	  if(gl_output_control_sequence(gl, gl->nline, gl->clear_eod) ||
	     gl_output_string(gl, gl->line + buff_pos, '\0') ||
	     gl_place_cursor(gl, gl->buff_curpos))
	    return 1;
	};
      } else {
	fprintf(stderr,
		"\r\nInsufficient room in line for file completion.\r\n");
	redisplay = 1;
      };
    };
  };
/*
 * Redisplay the whole line?
 */
  if(redisplay) {
    gl->term_curpos = 0;
    if(gl_redisplay(gl,1))
      return 1;
  };
  return 0;
}

/*.......................................................................
 * 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 redisplay=0;       /* True if the whole line needs to be redrawn */
  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 below
 * the character 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))
    return 1;
/*
 * Locate the start of the filename that precedes the cursor position.
 */
  start_path = _pu_start_of_path(gl->line,
				 gl->buff_curpos > 0 ? gl->buff_curpos : 0);
  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, then redraw
 * the original line.
 */
  if(!result) {
    if(gl->echo &&
       fprintf(gl->output_fp, "\r\n%s\n", ef_last_error(gl->ef)) < 0)
      return 1;
    gl->term_curpos = 0;
    return gl_redisplay(gl,1);
  };
/*
 * If no files matched, report this as well.
 */
  if(result->nfile == 0 || !result->exists) {
    if(gl->echo && fprintf(gl->output_fp, "\r\nNo files match.\n") < 0)
      return 1;
    gl->term_curpos = 0;
    return gl_redisplay(gl,1);
  };
/*
 * 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) {
    fprintf(stderr, "\r\nInsufficient room in line for file expansion.\r\n");
    redisplay = 1;
  } else {
/*
 * Do we need to move the part of the line that followed the unexpanded
 * filename?
 */
    if(nextra != 0) {
      memmove(gl->line + gl->buff_curpos + nextra, gl->line + gl->buff_curpos,
	      gl->ntotal - gl->buff_curpos);
    };
/*
 * 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->line[j++] = '\\';
	};
	gl->line[j++] = c;
      };
      gl->line[j++] = ' ';
    };
/*
 * Record the increased length of the line.
 */
    gl->ntotal += nextra;
/*
 * Place the cursor position at the end of the expansion.
 */
    gl->buff_curpos += nextra;
/*
 * Terminate the extended line.
 */
    gl->line[gl->ntotal] = '\0';
  };
/*
 * Display the whole line on a new line?
 */
  if(redisplay) {
    gl->term_curpos = 0;
    return gl_redisplay(gl,1);
  };
/*
 * Otherwise redisplay the part of the line which follows the start of
 * the original filename.
 */
  if(gl_set_term_curpos(gl, gl_buff_curpos_to_term_curpos(gl, start_path - gl->line)) ||
     gl_output_control_sequence(gl, gl->nline, gl->clear_eod) ||
     gl_output_string(gl, start_path, gl->line[gl->buff_curpos]))
    return 1;
/*
 * Restore the cursor position to the end of the expansion.
 */
  return gl_place_cursor(gl, gl->buff_curpos);
}

/*.......................................................................
 * 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 > 0 ? gl->buff_curpos : 0);
  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.
 */
  if(!result) {
    if(gl->echo &&
       fprintf(gl->output_fp, "\r\n%s\n", ef_last_error(gl->ef)) < 0)
      return 1;
/*
 * If no files matched, report this as well.
 */
  } else if(result->nfile == 0 || !result->exists) {
    if(gl->echo && fprintf(gl->output_fp, "\r\nNo files match.\n") < 0)
      return 1;
/*
 * List the matching expansions.
 */
  } else if(gl->echo) {
    if(fprintf(gl->output_fp, "\r\n") < 0)
      return 1;
    ef_list_expansions(result, gl->output_fp, gl->ncolumn);
  };
/*
 * Redisplay the line being edited.
 */
  gl->term_curpos = 0;
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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)
{
/*
 * Check the arguments.
 */
  if(!gl || !match_fn) {
    fprintf(stderr, "gl_customize_completion: NULL argument(s).\n");
    return 1;
  };
/*
 * Record the new completion function and its callback data.
 */
  gl->cpl_fn = match_fn;
  gl->cpl_data = data;
  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)
{
  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) {
    fprintf(stderr, "\r\ngl_change_terminal: Bad input/output stream(s).\n");
    return 1;
  };
/*
 * If we are displacing a previous terminal, remove it from the list
 * of fds being watched.
 */
#ifdef HAVE_SELECT
  if(gl->input_fd >= 0)
    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);
/*
 * Make sure that the file descriptor will be visible in the set to
 * be watched.
 */
#ifdef HAVE_SELECT
  FD_SET(gl->input_fd, &gl->rfds);
  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) {
      gl->term = (char *) malloc(strlen(term)+1);
      if(gl->term)
	strcpy(gl->term, term);
    };
  };
/*
 * 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)) {
      fprintf(stderr, "\r\ngl_change_terminal: tcgetattr error: %s\n",
	      strerror(errno));
      return 1;
    };
/*
 * Lookup the terminal control string and size information.
 */
    if(gl_control_strings(gl, term))
      return 1;
/*
 * We now have enough info to interact with the terminal.
 */
    gl->is_term = 1;
/*
 * Bind terminal-specific keys.
 */
    if(gl_bind_terminal_keys(gl))
      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"))
    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) {
    return 1;
/*
 * If we are at the end of the line list possible completions.
 */
  } else if(gl->buff_curpos >= gl->ntotal) {
/*
 * Get the list of possible completions.
 */
    CplMatches *matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos,
					    gl->cpl_data, gl->cpl_fn);
    if(!matches) {
      if(gl->echo &&
	 fprintf(gl->output_fp, "\r\n%s\n", cpl_last_error(gl->cpl)) < 0)
	return 1;
      gl->term_curpos = 0;
/*
 * List the matches.
 */
    } else if(matches->nmatch > 0 && gl->echo) {
      if(fprintf(gl->output_fp, "\r\n") < 0)
	return 1;
      cpl_list_completions(matches, gl->output_fp, gl->ncolumn);
    };
/*
 * Redisplay the line unchanged.
 */
    return gl_redisplay(gl,1);
/*
 * 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);
  };
}

/*.......................................................................
 * 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) {
    return 1;
/*
 * Otherwise list possible completions.
 */
  } else {
/*
 * Get the list of possible completions.
 */
    CplMatches *matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos,
					    gl->cpl_data, gl->cpl_fn);
    if(!matches) {
      if(gl->echo &&
	 fprintf(gl->output_fp, "\r\n%s\n", cpl_last_error(gl->cpl)) < 0)
	return 1;
      gl->term_curpos = 0;
/*
 * List the matches.
 */
    } else if(matches->nmatch > 0 && gl->echo) {
      if(fprintf(gl->output_fp, "\r\n") < 0)
	return 1;
      cpl_list_completions(matches, gl->output_fp, gl->ncolumn);
    };
/*
 * Redisplay the line unchanged.
 */
    return gl_redisplay(gl,1);
  };
}

/*.......................................................................
 * 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->bindings, "up", gl->u_arrow, "^[[A", "^[OA") ||
     _gl_rebind_arrow_key(gl->bindings, "down", gl->d_arrow, "^[[B", "^[OB") ||
     _gl_rebind_arrow_key(gl->bindings, "left", gl->l_arrow, "^[[D", "^[OD") ||
     _gl_rebind_arrow_key(gl->bindings, "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:
 *  bindings     KeyTab *   The table of key bindings.
 *  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(KeyTab *bindings, const char *name,
				const char *term_seq, const char *def_seq1,
				const char *def_seq2)
{
  int first,last;  /* The indexes of the first and last matching entries */
/*
 * 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(bindings, name, strlen(name), &first, &last)
     == KT_EXACT_MATCH) {
/*
 * Get the action function.
 */
    KtKeyFn *key_fn = bindings->table[first].keyfn;
/*
 * Bind this to each of the specified key sequences.
 */
    if((term_seq && _kt_set_keyfn(bindings, KTB_TERM, term_seq, key_fn)) ||
       (def_seq1 && _kt_set_keyfn(bindings, KTB_NORM, def_seq1, key_fn)) ||
       (def_seq2 && _kt_set_keyfn(bindings, KTB_NORM, def_seq2, key_fn)))
      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)
{
  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) {
    fprintf(stderr, "_gl_read_config_file: Invalid arguments.\n");
    return 1;
  };
/*
 * Expand the filename.
 */
  expansion = ef_expand_file(gl->ef, filename, -1);
  if(!expansion) {
    fprintf(stderr, "Unable to expand %s (%s).\n", filename,
            ef_last_error(gl->ef));
    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;
}

/*.......................................................................
 * 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) {
    fprintf(stderr, "_gl_read_config_string: Invalid arguments.\n");
    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) {
	fprintf(stderr, "%s:%d: Too many arguments.\n", origin, *lineno);
	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) {
    fprintf(stderr, "%s:%d: Line too long.\n", origin, *lineno);
    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];
    case 2:              /* Note the intentional fallthrough */
      keyseq = argv[1];
/*
 * Attempt to record the new keybinding.
 */
      if(_kt_set_keybinding(gl->bindings, who, keyseq, action)) {
	fprintf(stderr, "The error occurred at line %d of %s.\n", *lineno,
		origin);
      };
      break;
    default:
      fprintf(stderr, "%s:%d: Wrong number of arguments.\n", origin, *lineno);
    };
  } 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 {
      fprintf(stderr, "%s:%d: The argument of editor should be vi or emacs.\n",
	      origin, *lineno);
    };
  } else if(strcmp(argv[0], "nobeep") == 0) {
    gl->silence_bell = 1;
  } else {
    fprintf(stderr, "%s:%d: Unknown command name '%s'.\n", origin, *lineno,
	    argv[0]);
  };
/*
 * Skip any trailing comment.
 */
  while(c != '\n' && c != EOF)
    c = getc_fn(stream);
  (*lineno)++;
  return 0;
}

/*.......................................................................
 * 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;
}

/*.......................................................................
 * 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 */
  int error_reported = 0; /* True after an error has been reported */
/*
 * Locate the start of the filename that precedes the cursor position.
 */
  start_path = _pu_start_of_path(gl->line,
				 gl->buff_curpos > 0 ? gl->buff_curpos : 0);
  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, then redraw
 * the original line.
 */
  if(!result) {
    if(gl->echo &&
       fprintf(gl->output_fp, "\r\n%s\n", ef_last_error(gl->ef)) < 0)
      return 1;
    error_reported = 1;
/*
 * If no files matched, report this as well.
 */
  } else if(result->nfile == 0 || !result->exists) {
    if(gl->echo && fprintf(gl->output_fp, "\r\nNo files match.\n") < 0)
      return 1;
    error_reported = 1;
/*
 * Complain if more than one file matches.
 */
  } else if(result->nfile > 1) {
    if(gl->echo &&
       fprintf(gl->output_fp, "\r\nMore than one file matches.\n") < 0)
      return 1;
    error_reported = 1;
/*
 * 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])) {
    if(gl->echo && fprintf(gl->output_fp, "\r\nNot a normal file.\n") < 0)
      return 1;
    error_reported = 1;
  } else {
/*
 * Attempt to open and install the specified file for reading.
 */
    gl->file_fp = fopen(result->files[0], "r");
    if(!gl->file_fp) {
      if(gl->echo && fprintf(gl->output_fp, "\r\nUnable to open: %s\n",
		 result->files[0]) < 0)
	return 1;
      error_reported = 1;
    };
/*
 * Inform the user what is happening.
 */
    if(gl->echo && fprintf(gl->output_fp, "\r\n<Taking input from %s>\n",
			   result->files[0]) < 0)
      return 1;
  };
/*
 * If an error was reported, redisplay the current line.
 */
  if(error_reported) {
    gl->term_curpos = 0;
    return gl_redisplay(gl,1);
  };
  return 0;
}

/*.......................................................................
 * 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;
}

/*.......................................................................
 * 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;
/*
 * Recall the next oldest line in the history list.
 */
  if(_glh_oldest_line(gl->glh, gl->line, gl->linelen) == NULL)
    return 0;
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange to have the cursor placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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;
/*
 * Recall the next oldest line in the history list.
 */
  if(_glh_current_line(gl->glh, gl->line, gl->linelen) == NULL)
    return 0;
/*
 * Record the number of characters in the new string.
 */
  gl->ntotal = strlen(gl->line);
/*
 * Arrange to have the cursor placed at the end of the new line.
 */
  gl->buff_curpos = strlen(gl->line);
/*
 * Erase and display the new line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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);
/*
 * 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 - Error.
 */
static int gl_flush_output(GetLine *gl)
{
/*
 * Attempt to flush output to the terminal, restarting the output
 * if a signal is caught.
 */
  while(fflush(gl->output_fp) != 0) {
    if(errno!=EINTR)
      return 1;
  };
  return 0;
}

/*.......................................................................
 * 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:
    fprintf(stderr, "gl_change_editor: Unknown editor.\n");
    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))
      *cptr = toupper((int) *cptr);
    else if(isupper((int)(unsigned char) *cptr))
      *cptr = tolower((int) *cptr);
/*
 * 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_output_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) ||
         gl_vi_insert(gl, 0);
         
}

/*.......................................................................
 * 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) ||
         gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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) ||
         gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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_character(gl, &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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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);
  else
    return gl_backward_copy_char(gl, gl->buff_curpos - count);
}

/*.......................................................................
 * 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);
    else
      return gl_backward_copy_char(gl, ++gl->buff_curpos - curpos + 1);
  };
  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_character(gl, &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);
    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_buff_curpos_to_term_curpos(gl, buff_curpos));
}

/*.......................................................................
 * 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) {
    strcpy(gl->vi.undo.line, gl->line);
    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_fn != gl_vi_repeat_change) {
    gl->vi.repeat.fn = gl->current_fn;
    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) {
    strcpy(undo_ptr, line_ptr);
    *line_ptr = '\0';
  } else {
    strcpy(line_ptr, undo_ptr);
    *undo_ptr = '\0';
  };
/*
 * Swap the length information.
 */
  {
    int ntotal = gl->ntotal;
    gl->ntotal = gl->vi.undo.ntotal;
    gl->vi.undo.ntotal = ntotal;
  };
/*
 * 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.fn = gl_vi_undo;
  gl->vi.repeat.count = 1;
/*
 * Display the restored line.
 */
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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);
}

/*.......................................................................
 * 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) || gl_vi_insert(gl, 0);
}

/*.......................................................................
 * 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);
  else
    return gl_vi_backward_change_char(gl, gl->buff_curpos - count);
}

/*.......................................................................
 * 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);
    else
      return gl_vi_backward_change_char(gl, ++gl->buff_curpos - curpos + 1);
  };
  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); /* Vi moves left one 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_output_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.fn)
    return gl_ring_bell(gl, 1);
/*
 * 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.fn(gl, gl->vi.repeat.count);
/*
 * 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);
  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)
{
  KtKeyFn *keyfn;            /* An action function */
  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 editting 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) {
    if(gl->ntotal >= gl->linelen)
      return 0;
    if(c == '\n' || c == '\r')
      return gl_newline(gl, 1);
    gl->line[gl->ntotal++] = c;
    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))
    return gl_digit_argument(gl, c);
/*
 * 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) {
    int first, last;   /* The matching entries in gl->keys */
/*
 * 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, &first, &last)) {
    case KT_EXACT_MATCH:
/*
 * Get the matching action function.
 */
      keyfn = gl->bindings->table[first].keyfn;
/*
 * Get the repeat count, passing the last keystroke if executing the
 * digit-argument action.
 */
      if(keyfn == gl_digit_argument) {
	count = c;
      } else {
	count = gl->number >= 0 ? gl->number : 1;
      };
/*
 * Record the function that is being invoked.
 */
      gl->current_fn = keyfn;
      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 = keyfn(gl, count);
/*
 * Reset the repeat count after running action functions (other
 * than digit-argument).
 */
      if(keyfn != gl_digit_argument)
	gl->number = -1;
      if(ret)
	return 1;
      return 0;
      break;
    case KT_AMBIG_MATCH:             /* Ambiguous match - so look ahead */
      if(gl_read_character(gl, &c))  /* Get the next character */
	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, 0);
      } 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;
      };
      return 0;
      break;
    case KT_BAD_MATCH:
      return 1;
      break;
    };
  };
/*
 * Key sequence too long to match.
 */
  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 new_GetLine(), 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)
{
/*
 * Check the arguments.
 */
  if(!gl) {
    fprintf(stderr, "gl_configure_getline: NULL gl argument.\n");
    return 1;
  };
/*
 * 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)) {
    fprintf(stderr,
	    "Insufficient memory to record tecla configuration file names.\n");
    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) {
    *sptr = (char *) malloc(strlen(string) + 1);
    if(!*sptr)
      return 1;
/*
 * Copy the string.
 */
    strcpy(*sptr, string);
  };
  return 0;
}

/*.......................................................................
 * 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);
}

/*.......................................................................
 * 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)
{
  FileExpansion *expansion; /* The expansion of the filename */
/*
 * Check the arguments.
 */
  if(!gl || !filename || !comment) {
    fprintf(stderr, "gl_save_history: NULL argument(s).\n");
    return 1;
  };
/*
 * Expand the filename.
 */
  expansion = ef_expand_file(gl->ef, filename, -1);
  if(!expansion) {
    fprintf(stderr, "Unable to expand %s (%s).\n", filename,
            ef_last_error(gl->ef));
    return 1;
  };
/*
 * Attempt to save to the specified file.
 */
  return _glh_save_history(gl->glh, expansion->files[0], comment, max_lines);
}

/*.......................................................................
 * 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)
{
  FileExpansion *expansion; /* The expansion of the filename */
/*
 * Check the arguments.
 */
  if(!gl || !filename || !comment) {
    fprintf(stderr, "gl_load_history: NULL argument(s).\n");
    return 1;
  };
/*
 * Expand the filename.
 */
  expansion = ef_expand_file(gl->ef, filename, -1);
  if(!expansion) {
    fprintf(stderr, "Unable to expand %s (%s).\n", filename,
            ef_last_error(gl->ef));
    return 1;
  };
/*
 * Attempt to load from the specified file.
 */
  if(_glh_load_history(gl->glh, expansion->files[0], comment,
		       gl->cutbuf, gl->linelen)) {
    gl->cutbuf[0] = '\0';
    return 1;
  };
  gl->cutbuf[0] = '\0';
  return 0;
}

/*.......................................................................
 * 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)
#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 */
/*
 * Check the arguments.
 */
  if(!gl) {
    fprintf(stderr, "gl_watch_fd: NULL gl argument.\n");
    return 1;
  };
  if(fd < 0) {
    fprintf(stderr, "gl_watch_fd: Error fd < 0.\n");
    return 1;
  };
/*
 * 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) {
      fprintf(stderr, "gl_watch_fd: Insufficient memory.\n");
      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;
}

/*.......................................................................
 * When select() is available, this function is called by
 * gl_read_character() to respond to file-descriptor events registered by
 * the caller.
 *
 * Input:
 *  gl    GetLine *  The resource object of this module.
 * Output:
 *  return    int    0 - A character is waiting to be read from the
 *                       terminal.
 *                   1 - An error occurred.
 */
static int gl_event_handler(GetLine *gl)
{
/*
 * 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) {
/*
 * Get the set of descriptors to be watched.
 */
    fd_set rfds = gl->rfds;
    fd_set wfds = gl->wfds;
    fd_set ufds = gl->ufds;
/*
 * Wait for activity on any of the file descriptors.
 */
    int nready = select(gl->max_fd+1, &rfds, &wfds, &ufds, NULL);
/*
 * If select() returns but none of the file descriptors are reported
 * to have activity, then select() timed out.
 */
    if(nready == 0) {
      fprintf(stdout, "\r\nUnexpected select() timeout\r\n");
      return 1;
/*
 * If nready < 0, this means an error occurred.
 */
    } else if(nready < 0) {
      if(errno != EINTR) {
#ifdef EAGAIN
	if(!errno)          /* This can happen with SysV O_NDELAY */
	  errno = EAGAIN;
#endif
	return 1;
      };
/*
 * If the terminal input file descriptor has data available, return.
 */
    } else if(FD_ISSET(gl->input_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, &rfds)) {
	  if(gl_call_fd_handler(gl, &node->wr, node->fd, GLFD_WRITE))
	    return 1;
	  break;  /* The callback may have changed the list of nodes */
	};
      };
    };
  };
  return 0;
}

/*.......................................................................
 * 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 redisplay = 0;  /* True to have the input line redisplayed */
  int waserr = 0;     /* True after any error */
/*
 * 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.
 */
  if(sigprocmask(SIG_BLOCK, &gl->new_signal_set, NULL) == -1) {
    fprintf(stderr, "getline(): sigprocmask error: %s\n", strerror(errno));
    return 1;
  };
/*
 * 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)) {
    fprintf(stderr, "\r\ngetline(): tcgetattr error: %s\r\n", strerror(errno));
    return 1;
  };
  attr.c_oflag |= OPOST;
  while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
    if (errno != EINTR) {
      fprintf(stderr, "\r\ngetline(): tcsetattr error: %s\r\n",
	      strerror(errno));
      return 1;
    };
  };
/*
 * Invoke the application's callback function.
 */
  switch(gfh->fn(gl, gfh->data, fd, event)) {
  default:
  case GLFD_ABORT:
    waserr = 1;
    break;
  case GLFD_REFRESH:
    redisplay = 1;
    break;
  case GLFD_CONTINUE:
    redisplay = gl->prompt_changed;
    break;
  };
/*
 * Disable conversion of newline characters to carriage-return/linefeed.
 */
  attr.c_oflag &= ~(OPOST);
  while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
    if(errno != EINTR) {
      fprintf(stderr, "\ngetline(): tcsetattr error: %s\n", strerror(errno));
      return 1;
    };
  };
/*
 * If requested, redisplay the input line.
 */
  if(redisplay && gl_redisplay(gl, 1))
    return 1;
/*
 * Unblock the signals that we were trapping before this function
 * was called.
 */
  if(sigprocmask(SIG_UNBLOCK, &gl->new_signal_set, NULL) == -1) {
    fprintf(stderr, "getline(): sigprocmask error: %s\n", strerror(errno));
    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)
{
/*
 * Check the arguments.
 */
  if(!gl) {
    fprintf(stderr, "gl_group_history: NULL argument(s).\n");
    return 1;
  };
/*
 * If the group isn't being changed, do nothing.
 */
  if(_glh_get_group(gl->glh) == id)
    return 0;
/*
 * Establish the new group.
 */
  if(_glh_set_group(gl->glh, id))
    return 1;
/*
 * Prevent history information from the previous group being
 * inappropriately used by the next call to gl_get_line().
 */
  gl->preload_history = 0;
  gl->last_search = -1;
  return 0;
}

/*.......................................................................
 * 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)
{
/*
 * Check the arguments.
 */
  if(!gl || !fp || !fmt) {
    fprintf(stderr, "gl_show_history: NULL argument(s).\n");
    return 1;
  };
  return _glh_show_history(gl->glh, fp, fmt, all_groups, max_lines);
}

/*.......................................................................
 * 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 return value */
  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.
 */
#ifdef USE_SIGWINCH
    (void) gl_resize_terminal(gl, 0);
#endif
/*
 * If gl_resize_terminal() couldn't be used, or it returned non-sensical
 * values for the number of lines, see if the LINES environment variable
 * exists and specifies a believable number. If this doesn't work,
 * look up the default size in the terminal information database,
 * where available.
 */
    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 gl_resize_terminal() couldn't be used, or it returned non-sensical
 * values for the number of columns, see if the COLUMNS environment variable
 * exists and specifies a believable number. If this doesn't work, fall
 * lookup the default size in the terminal information database,
 * where available.
 */
    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.
 */
  size.nline = gl->nline;
  size.ncolumn = gl->ncolumn;
  return size;
}

/*.......................................................................
 * 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)
{
  return gl ? _glh_resize_history(gl->glh, bufsize) : 1;
}

/*.......................................................................
 * 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)
    _glh_limit_history(gl->glh, 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)
{
  if(gl)
    _glh_clear_history(gl->glh, 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)
{
  if(gl)
    _glh_toggle_history(gl->glh, enable);
}

/*.......................................................................
 * 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)
{
  return gl ? _glh_lookup_history(gl->glh, (GlhLineID) id, &line->line,
				  &line->group, &line->timestamp) : 0;
}

/*.......................................................................
 * 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)
    _glh_state_of_history(gl->glh, &state->enabled, &state->group,
			  &state->max_lines);
}

/*.......................................................................
 * 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)
    _glh_range_of_history(gl->glh, &range->oldest, &range->newest,
			  &range->nlines);
}

/*.......................................................................
 * 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)
    _glh_size_of_history(gl->glh, &size->size, &size->used);
}

/*.......................................................................
 * 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(fprintf(gl->output_fp, "\r\n") < 0)
    return 1;
/*
 * List history lines that belong to the current group.
 */
  _glh_show_history(gl->glh, gl->output_fp, "%N  %T   %H\r\n", 0,
		    count<=1 ? -1 : count);
/*
 * Redisplay the line being edited.
 */
  gl->term_curpos = 0;
  return gl_redisplay(gl,1);
}

/*.......................................................................
 * 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) {
    int was_echoing = gl->echo;
    if(enable >= 0)
      gl->echo = enable;
    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_output_control_sequence(gl, 1, gl->bol))
    return 1;
/*
 * Write the prompt, using the currently selected prompt style.
 */
  switch(gl->prompt_style) {
  case GL_LITERAL_PROMPT:
    if(gl_output_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_output_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_output_control_sequence(gl, 1, gl->bold))
	  return 1;
	if(new_attr & GL_TXT_UNDERLINE && !(old_attr & GL_TXT_UNDERLINE) &&
	   gl_output_control_sequence(gl, 1, gl->underline))
	  return 1;
	if(new_attr & GL_TXT_STANDOUT && !(old_attr & GL_TXT_STANDOUT) &&
	   gl_output_control_sequence(gl, 1, gl->standout))
	  return 1;
	if(new_attr & GL_TXT_DIM && !(old_attr & GL_TXT_DIM) &&
	   gl_output_control_sequence(gl, 1, gl->dim))
	  return 1;
	if(new_attr & GL_TXT_REVERSE && !(old_attr & GL_TXT_REVERSE) &&
	   gl_output_control_sequence(gl, 1, gl->reverse))
	  return 1;
	if(new_attr & GL_TXT_BLINK && !(old_attr & GL_TXT_BLINK) &&
	   gl_output_control_sequence(gl, 1, gl->blink))
	  return 1;
	old_attr = new_attr;
      };
/*
 * Display the latest character.
 */
      if(gl_output_char(gl, *pptr, pptr[1]))
	return 1;
    };
/*
 * Turn off all text attributes now that we have finished drawing
 * the prompt.
 */
    if(gl_output_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) {
    gl->prompt = prompt ? prompt : "";
    gl->prompt_len = gl_displayed_prompt_width(gl);
    gl->prompt_changed = 1;
  };
}

/*.......................................................................
 * 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) {
    if(style != gl->prompt_style) {
      gl->prompt_style = style;
      gl->prompt_len = gl_displayed_prompt_width(gl);
      gl->prompt_changed = 1;
    };
  };
}

/*.......................................................................
 * 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)
{
  GlSignalNode *sig;
/*
 * Check the arguments.
 */
  if(!gl) {
    fprintf(stderr, "gl_trap_signal: NULL argument(s).\n");
    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) {
      fprintf(stderr, "gl_trap_signal: sigaddset error: %s\n",
	      strerror(errno));
      sig = (GlSignalNode *) _del_FreeListNode(gl->sig_mem, sig);
      return 1;
    };
  };
/*
 * 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 */
/*
 * Check the arguments.
 */
  if(!gl) {
    fprintf(stderr, "gl_ignore_signal: NULL argument(s).\n");
    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);
  };
  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.
 *  archive          int    True to have the line archived in the
 *                          history buffer.
 * Output:
 *  return           int    0 - OK.
 *                          1 - Error.
 */
static int gl_line_ended(GetLine *gl, int newline_char, int archive)
{
/*
 * If the newline character is printable, display it.
 */
  if(isprint((int)(unsigned char) newline_char)) {
    if(gl_end_of_line(gl, 1) || gl_add_char_to_line(gl, newline_char))
      return 1;
  } else {
/*
 * Otherwise just append it to the input line buffer.
 */
    gl->line[gl->ntotal++] = newline_char;
    gl->line[gl->ntotal] = '\0';
  };
/*
 * Add the line to the history buffer if it was entered with a
 * newline or carriage return character.
 */
  if(archive)
    (void) _glh_add_history(gl->glh, gl->line, 0);
/*
 * Unless 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) {
    if(gl_end_of_line(gl, 1) ||
       gl_output_raw_string(gl, "\r\n"))
      return 1;
  };
  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(const GetLine *gl)
{
  return gl ? gl->last_signal : -1;
}