File: command.c

package info (click to toggle)
rxvt 1%3A2.4.5-16
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,128 kB
  • ctags: 1,296
  • sloc: ansic: 12,852; makefile: 521; sh: 411
file content (3450 lines) | stat: -rw-r--r-- 80,690 bytes parent folder | download
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
/*--------------------------------*-C-*---------------------------------*
 * File:	command.c
 *----------------------------------------------------------------------*
 * Copyright (C) 1997 1998 Oezguer Kesim <kesim@math.fu-berlin.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *----------------------------------------------------------------------* 
 * Originaly written by John Bovey, University of Kent at Canterbury
 * Modifications by
 *    Robert Nation <nation@rocket.sanders.lockheed.com>
 *    Garrett D'Amore <garrett@netcom.com>
 *    Steven Hirsch <hirsch@emba.uvm.edu>
 *    Jakub Jelinek <jj@gnu.ai.mit.edu>
 *    MJ Olesen <olesen@me.queensu.ca>
 *    Raul Garcia Garcia <rgg@tid.es>
 *    Oezguer Kesim <kesim@math.fu-berlin.de>
 *----------------------------------------------------------------------*/

/*{{{ includes: */
#include "rxvt.h"		/* NECESSARY */
/* Debian hack: this is necessary to compile with Greek support.
   (1998/5/24) -BEM */
#ifdef GREEK_SUPPORT
#include "grkelot.h"
#endif

#ifdef OFFIX_DND
#include <X11/Xatom.h>
#define DndFile	2
#define DndDir	5
#define DndLink	7
#endif

#include <X11/keysym.h>
#ifndef NO_XLOCALE
#if (XtSpecificationRelease < 6)
#define NO_XLOCALE
#else
/* Debian hack: Removed the line
#define X_LOCALE
   because it was conflicting with Xlocale.h (thanks to Ilya Ovchinnikov)
   - 2/3/98 BEM */
#include <X11/Xlocale.h>
#endif
#endif				/* NO_XLOCALE */

#ifdef TTY_GID_SUPPORT
#include <grp.h>
#endif

#if defined (__svr4__)
#include <sys/resource.h>	/* for struct rlimit */
#include <sys/stropts.h>	/* for I_PUSH */
#define _NEW_TTY_CTRL		/* to get proper defines in <termios.h> */
#endif

/*}}} */

/* #define DEBUG_TTYMODE */
/* #define DEBUG_CMD */

/*{{{ terminal mode defines: */
/* use the fastest baud-rate */
#ifdef B38400
#define BAUDRATE	B38400
#else
#ifdef B19200
#define BAUDRATE	B19200
#else
#define BAUDRATE	B9600
#endif
#endif

/* Disable special character functions */
#ifdef _POSIX_VDISABLE
#define VDISABLE	_POSIX_VDISABLE
#else
#define VDISABLE	255
#endif

/*----------------------------------------------------------------------*
 * system default characters if defined and reasonable
 */
#ifndef CINTR
#define CINTR		'\003'	/* ^C */
#endif
#ifndef CQUIT
#define CQUIT		'\034'	/* ^\ */
#endif
#ifndef CERASE
#ifdef linux
#define CERASE		'\177'  /* ^? */
#else
#define CERASE		'\010'	/* ^H */
#endif
#endif
#ifndef CKILL
#define CKILL		'\025'	/* ^U */
#endif
#ifndef CEOF
#define CEOF		'\004'	/* ^D */
#endif
#ifndef CSTART
#define CSTART		'\021'	/* ^Q */
#endif
#ifndef CSTOP
#define CSTOP		'\023'	/* ^S */
#endif
#ifndef CSUSP
#define CSUSP		'\032'	/* ^Z */
#endif
#ifndef CDSUSP
#define CDSUSP		'\031'	/* ^Y */
#endif
#ifndef CRPRNT
#define CRPRNT		'\022'	/* ^R */
#endif
#ifndef CFLUSH
#define CFLUSH		'\017'	/* ^O */
#endif
#ifndef CWERASE
#define CWERASE	'\027'		/* ^W */
#endif
#ifndef CLNEXT
#define CLNEXT		'\026'	/* ^V */
#endif

#ifndef VDISCRD
#ifdef VDISCARD
#define VDISCRD	VDISCARD
#endif
#endif

#ifndef VWERSE
#ifdef VWERASE
#define VWERSE	VWERASE
#endif
#endif
/*}}} */

/*{{{ defines: */

#define KBUFSZ		8	/* size of keyboard mapping buffer */
#define STRING_MAX	512	/* max string size for process_xterm_seq() */
#define ESC_ARGS	32	/* max # of args for esc sequences */

/* a large REFRESH_PERIOD causes problems with `cat' */
#define REFRESH_PERIOD	1

#ifndef REFRESH_PERIOD
#define REFRESH_PERIOD	10
#endif

#ifndef MULTICLICK_TIME
#define MULTICLICK_TIME	500
#endif
#ifndef SCROLLBAR_INITIAL_DELAY
#define SCROLLBAR_INITIAL_DELAY		40
#endif
#ifndef SCROLLBAR_CONTINUOUS_DELAY
#define SCROLLBAR_CONTINUOUS_DELAY	2
#endif

/* time factor to slow down a `jumpy' mouse */
#define MOUSE_THRESHOLD		50
#define CONSOLE		"/dev/console"	/* console device */

/*
 * key-strings: if only these keys were standardized <sigh>
 */
#ifdef LINUX_KEYS
#define KS_HOME	"\033[1~"	/* Home == Find */
#define KS_END		"\033[4~"	/* End == Select */
#else
#define KS_HOME	"\033[7~"	/* Home */
#define KS_END		"\033[8~"	/* End */
#endif

/* and this one too! */
#ifdef NO_DELETE_KEY
#undef KS_DELETE		/* use X server definition */
#else
#ifndef KS_DELETE
#define KS_DELETE	"\033[3~"	/* Delete = Execute */
#endif
#endif

/*
 * ESC-Z processing:
 *
 * By stealing a sequence to which other xterms respond, and sending the
 * same number of characters, but having a distinguishable sequence,
 * we can avoid having a timeout (when not under an rxvt) for every login
 * shell to auto-set its DISPLAY.
 *
 * This particular sequence is even explicitly stated as obsolete since
 * about 1985, so only very old software is likely to be confused, a
 * confusion which can likely be remedied through termcap or TERM. Frankly,
 * I doubt anyone will even notice.  We provide a #ifdef just in case they
 * don't care about auto-display setting.  Just in case the ancient
 * software in question is broken enough to be case insensitive to the 'c'
 * character in the answerback string, we make the distinguishing
 * characteristic be capitalization of that character. The length of the
 * two strings should be the same so that identical read(2) calls may be
 * used.
 */
#define VT100_ANS	"\033[?1;2c"	/* vt100 answerback */
#ifndef ESCZ_ANSWER
#define ESCZ_ANSWER	VT100_ANS	/* obsolete ANSI ESC[c */
#endif
/*}}} */

/*{{{ local variables */
static char    *ptydev = NULL, *ttydev = NULL;	/* pty/tty name */
static int      cmd_fd = -1;	/* file descriptor connected to the command */
static pid_t    cmd_pid = -1;	/* process id if child */
static int      Xfd = -1;	/* file descriptor of X server connection */
static unsigned int num_fds = 0;	/* number of file descriptors being used */
static struct stat ttyfd_stat;	/* original status of the tty we will use */

#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
static int      scroll_arrow_delay;
#endif

#ifdef META8_OPTION
static unsigned char meta_char = 033;	/* Alt-key prefix */
#endif

/* DEC private modes */
#define PrivMode_132		(1LU<<0)
#define PrivMode_132OK		(1LU<<1)
#define PrivMode_rVideo		(1LU<<2)
#define PrivMode_relOrigin	(1LU<<3)
#define PrivMode_Screen		(1LU<<4)
#define PrivMode_Autowrap	(1LU<<5)
#define PrivMode_aplCUR		(1LU<<6)
#define PrivMode_aplKP		(1LU<<7)
#define PrivMode_BackSpace	(1LU<<8)
#define PrivMode_ShiftKeys	(1LU<<9)
#define PrivMode_VisibleCursor	(1LU<<10)
#define PrivMode_MouseX10	(1LU<<11)
#define PrivMode_MouseX11	(1LU<<12)
/* too annoying to implement X11 highlight tracking */
/* #define PrivMode_MouseX11Track       (1LU<<13) */
#define PrivMode_scrollBar	(1LU<<14)
#define PrivMode_menuBar	(1LU<<15)
#define PrivMode_TtyOutputInh	(1LU<<16)
#define PrivMode_Keypress	(1LU<<17)

#define PrivMode_mouse_report	(PrivMode_MouseX10|PrivMode_MouseX11)
#define PrivMode(test,bit) do {\
if (test) PrivateModes |= (bit); else PrivateModes &= ~(bit);} while (0)

#define PrivMode_Default \
(PrivMode_Autowrap|PrivMode_aplKP|PrivMode_ShiftKeys|PrivMode_VisibleCursor)

static unsigned long PrivateModes = PrivMode_Default;
static unsigned long SavedModes = PrivMode_Default;

#undef PrivMode_Default

static int      refresh_count = 0, refresh_limit = 1, refresh_type = SLOW_REFRESH;

static Atom     wmDeleteWindow;

/* OffiX Dnd (drag 'n' drop) support */
#ifdef OFFIX_DND
static Atom     DndProtocol, DndSelection;

#endif				/* OFFIX_DND */

#ifndef NO_XLOCALE
static char    *rs_inputMethod = "";	/* XtNinputMethod */
static char    *rs_preeditType = NULL;	/* XtNpreeditType */
static XIC      Input_Context;	/* input context */
#endif				/* NO_XLOCALE */

/* command input buffering */
#ifndef BUFSIZ
#define BUFSIZ		4096
#endif
static unsigned char cmdbuf_base[BUFSIZ], *cmdbuf_ptr, *cmdbuf_endp;

/*}}} */

#ifndef NO_XLOCALE
void            init_xlocale(void);
#else
#define init_xlocale() ((void)0)
#endif

/*for Big Paste Handling */
static int 	v_doPending(void);
static void 	v_writeBig(int f,char *d,int len); 

/*----------------------------------------------------------------------*/
/*}}} */

/*{{{ substitute system functions */
#ifndef _POSIX_VERSION
#if defined (__svr4__)
/* PROTO */
int
getdtablesize(void)
{
    struct rlimit   rlim;

    getrlimit(RLIMIT_NOFILE, &rlim);
    return rlim.rlim_cur;
}
#endif
#endif
/*}}} */

/*{{{ take care of suid/sgid super-user (root) privileges */
/* PROTO */
void
privileges(int mode)
{
#ifdef HAVE_SETEUID
    static uid_t    euid;
    static gid_t    egid;

    switch (mode) {
    case IGNORE:
    /*
     * change effective uid/gid - not real uid/gid - so we can switch
     * back to root later, as required
     */
	seteuid(getuid());
	setegid(getgid());
	break;

    case SAVE:
	euid = geteuid();
	egid = getegid();
	break;

    case RESTORE:
	seteuid(euid);
	setegid(egid);
	break;
    }
#else
    switch (mode) {
    case IGNORE:
	setuid(getuid());
	setgid(getgid());
	break;

    case SAVE:
	break;
    case RESTORE:
	break;
    }
#endif
}
/*}}} */

/*{{{ signal handling, exit handler */
/*
 * Catch a SIGCHLD signal and exit if the direct child has died
 */
/* PROTO */
RETSIGTYPE
Child_signal(int unused)
{
    int             pid, save_errno = errno;

    do {
	errno = 0;
    }
    while ((-1 == (pid = waitpid(-1, NULL, WNOHANG))) &&
	   (errno == EINTR));

    if (pid == cmd_pid)
	exit(EXIT_SUCCESS);
    errno = save_errno;

    signal(SIGCHLD, Child_signal);
}

/*
 * Catch a fatal signal and tidy up before quitting
 */
/* PROTO */
RETSIGTYPE
Exit_signal(int sig)
{
#ifdef DEBUG_CMD
    print_error("signal %d", sig);
#endif
    signal(sig, SIG_DFL);

#ifdef UTMP_SUPPORT
    privileges(RESTORE);
    cleanutent();
    privileges(IGNORE);
#endif

    kill(getpid(), sig);
}

/*
 * Exit gracefully, clearing the utmp entry and restoring tty attributes
 * TODO: this should free up any known resources if we can
 */
/* PROTO */
void
clean_exit(void)
{
#ifdef DEBUG_CMD
    fprintf(stderr, "Restoring \"%s\" to mode %03o, uid %d, gid %d\n",
	    ttydev, ttyfd_stat.st_mode, ttyfd_stat.st_uid, ttyfd_stat.st_gid);
#endif
    scr_release();
    privileges(RESTORE);
    chmod(ttydev, ttyfd_stat.st_mode);
    chown(ttydev, ttyfd_stat.st_uid, ttyfd_stat.st_gid);
#ifdef UTMP_SUPPORT
    cleanutent();
#endif
    privileges(IGNORE);
}

/*}}} */

/*{{{ Acquire a pseudo-teletype from the system. */
/*
 * On failure, returns -1.
 * On success, returns the file descriptor.
 *
 * If successful, ttydev and ptydev point to the names of the
 * master and slave parts
 */
/* PROTO */
int
get_pty(void)
{
    int             fd = -1;

#if defined (__sgi)
    ptydev = ttydev = _getpty(&fd, O_RDWR | O_NDELAY, 0622, 0);
    if (ptydev == NULL)
	goto Failed;
#elif defined (__svr4__)
    {
	extern char    *ptsname();

    /* open the STREAMS, clone device /dev/ptmx (master pty) */
	if ((fd = open("/dev/ptmx", O_RDWR)) < 0) {
	    goto Failed;
	} else {
	    grantpt(fd);	/* change slave permissions */
	    unlockpt(fd);	/* unlock slave */
	    ptydev = ttydev = ptsname(fd);	/* get slave's name */
	}
    }
#elif defined (_AIX)
    if ((fd = open("/dev/ptc", O_RDWR)) < 0)
	goto Failed;
    else
	ptydev = ttydev = ttyname(fd);
#elif defined(ALL_NUMERIC_PTYS) /* SCO OSr5 */
   static char pty_name[] = "/dev/ptyp??\0\0\0";
   static char tty_name[] = "/dev/ttyp??\0\0\0";
   int len = strlen (tty_name);
   char *c1, *c2;
   int idx;

   ptydev = pty_name;
   ttydev = tty_name;

   for (idx = 0; idx < 256; idx++)
   {
         sprintf(ptydev, "%s%d", "/dev/ptyp", idx);
         sprintf(ttydev, "%s%d", "/dev/ttyp", idx);

         if (access(ttydev, F_OK) < 0)
         {
                idx = 256;
                break;
         }

         if ((fd = open (ptydev, O_RDWR)) >= 0)
         {
            if  (access (ttydev, R_OK|W_OK) == 0)
                goto Found;
             close (fd);
         }
   }
   goto Failed;   
#else
    static char     pty_name[] = "/dev/pty??";
    static char     tty_name[] = "/dev/tty??";
    int             len = strlen(tty_name);
    char           *c1, *c2;

    ptydev = pty_name;
    ttydev = tty_name;

#define	PTYCHAR1	"pqrstuvwxyz"
#define	PTYCHAR2	"0123456789abcdef"
    for (c1 = PTYCHAR1; *c1; c1++) {
	ptydev[len - 2] = ttydev[len - 2] = *c1;
	for (c2 = PTYCHAR2; *c2; c2++) {
	    ptydev[len - 1] = ttydev[len - 1] = *c2;
	    if ((fd = open(ptydev, O_RDWR)) >= 0) {
		if (access(ttydev, R_OK | W_OK) == 0)
		    goto Found;
		close(fd);
	    }
	}
    }
    goto Failed;
#endif

  Found:
    fcntl(fd, F_SETFL, O_NDELAY);
    return fd;

  Failed:
    print_error("can't open pseudo-tty");
    return -1;
}
/*}}} */

/*{{{ establish a controlling teletype for new session */
/*
 * On some systems this can be done with ioctl() but on others we
 * need to re-open the slave tty.
 */
/* PROTO */
int
get_tty(void)
{
    int             fd;
    pid_t           pid;

/*
 * setsid() [or setpgrp] must be before open of the terminal,
 * otherwise there is no controlling terminal (Solaris 2.4, HP-UX 9)
 */
#ifndef ultrix
#ifdef NO_SETSID
    pid = setpgrp(0, 0);
#else
    pid = setsid();
#endif
    if (pid < 0)
	perror(rs_name);
#ifdef DEBUG_TTYMODE
    print_error("(%s: line %d): PID = %d\n", __FILE__, __LINE__, pid);
#endif
#endif				/* ultrix */

    if ((fd = open(ttydev, O_RDWR)) < 0) {
	print_error("can't open slave tty %s", ttydev);
	exit(EXIT_FAILURE);
    }
#if defined (__svr4__)
/*
 * Push STREAMS modules:
 *    ptem: pseudo-terminal hardware emulation module.
 *    ldterm: standard terminal line discipline.
 *    ttcompat: V7, 4BSD and XENIX STREAMS compatibility module.
 */
    ioctl(fd, I_PUSH, "ptem");
    ioctl(fd, I_PUSH, "ldterm");
    ioctl(fd, I_PUSH, "ttcompat");
#else				/* __svr4__ */
    {
    /* change ownership of tty to real uid and real group */
	unsigned int    mode = 0622;
	gid_t           gid = getgid();

#ifdef TTY_GID_SUPPORT
	{
	    struct group   *gr = getgrnam("tty");

	    if (gr) {
	    /* change ownership of tty to real uid, "tty" gid */
		gid = gr->gr_gid;
		mode = 0620;
	    }
	}
#endif				/* TTY_GID_SUPPORT */

	privileges(RESTORE);
	fchown(fd, getuid(), gid);	/* fail silently */
	fchmod(fd, mode);
	privileges(IGNORE);
    }
#endif				/* __svr4__ */

/*
 * Close all file descriptors.  If only stdin/out/err are closed,
 * child processes remain alive upon deletion of the window.
 */
    {
	int             i;

	for (i = 0; i < num_fds; i++)
	    if (i != fd)
		close(i);
    }

/* Reopen stdin, stdout and stderr over the tty file descriptor */
    dup(fd);			/* 0: stdin */
    dup(fd);			/* 1: stdout */
    dup(fd);			/* 2: stderr */

    if (fd > 2)
	close(fd);

#ifdef ultrix
    if ((fd = open("/dev/tty", O_RDONLY)) >= 0) {
	ioctl(fd, TIOCNOTTY, 0);
	close(fd);
    } else {
	pid = setpgrp(0, 0);
	if (pid < 0)
	    perror(rs_name);
    }

/* no error, we could run with no tty to begin with */
#else				/* ultrix */

#ifdef TIOCSCTTY
    ioctl(0, TIOCSCTTY, 0);
#endif

/* set process group */
#if defined (_POSIX_VERSION) || defined (__svr4__)
    tcsetpgrp(0, pid);
#elif defined (TIOCSPGRP)
    ioctl(0, TIOCSPGRP, &pid);
#endif

/* svr4 problems: reports no tty, no job control */
/* # if !defined (__svr4__) && defined (TIOCSPGRP) */

    close(open(ttydev, O_RDWR, 0));
/* # endif */
#endif				/* ultrix */

    privileges(IGNORE);

    return fd;
}
/*}}} */

/*{{{ debug_ttymode() */
#ifdef DEBUG_TTYMODE
/* PROTO */
void
debug_ttymode(ttymode_t * ttymode)
{
#ifdef HAVE_TERMIOS_H
/* c_iflag bits */
    fprintf(stderr, "Input flags\n");

/* cpp token stringize doesn't work on all machines <sigh> */
#define FOO(flag,name) \
if ((ttymode->c_iflag) & flag) fprintf (stderr, "%s ", name)

/* c_iflag bits */
    FOO(IGNBRK, "IGNBRK");
    FOO(BRKINT, "BRKINT");
    FOO(IGNPAR, "IGNPAR");
    FOO(PARMRK, "PARMRK");
    FOO(INPCK, "INPCK");
    FOO(ISTRIP, "ISTRIP");
    FOO(INLCR, "INLCR");
    FOO(IGNCR, "IGNCR");
    FOO(ICRNL, "ICRNL");
    FOO(IXON, "IXON");
    FOO(IXOFF, "IXOFF");
#ifdef IUCLC
    FOO(IUCLC, "IUCLC");
#endif
#ifdef IXANY
    FOO(IXANY, "IXANY");
#endif
#ifdef IMAXBEL
    FOO(IMAXBEL, "IMAXBEL");
#endif
    fprintf(stderr, "\n\n");

#undef FOO
#define FOO(entry, name) \
fprintf (stderr, "%s = %#3o\n", name, ttymode->c_cc [entry])
    FOO(VINTR, "VINTR");
    FOO(VQUIT, "VQUIT");
    FOO(VERASE, "VERASE");
    FOO(VKILL, "VKILL");
    FOO(VEOF, "VEOF");
    FOO(VEOL, "VEOL");
#ifdef VEOL2
    FOO(VEOL2, "VEOL2");
#endif
#ifdef VSWTC
    FOO(VSWTC, "VSWTC");
#endif
#ifdef VSWTCH
    FOO(VSWTCH, "VSWTCH");
#endif
    FOO(VSTART, "VSTART");
    FOO(VSTOP, "VSTOP");
    FOO(VSUSP, "VSUSP");
#ifdef VDSUSP
    FOO(VDSUSP, "VDSUSP");
#endif
#ifdef VREPRINT
    FOO(VREPRINT, "VREPRINT");
#endif
#ifdef VDISCRD
    FOO(VDISCRD, "VDISCRD");
#endif
#ifdef VWERSE
    FOO(VWERSE, "VWERSE");
#endif
#ifdef VLNEXT
    FOO(VLNEXT, "VLNEXT");
#endif
    fprintf(stderr, "\n\n");

#undef FOO

#endif				/* HAVE_TERMIOS_H */
}

#endif				/* DEBUG_TTYMODE */
/*}}} */

/*{{{ get_ttymode() */
/* PROTO */
void
get_ttymode(ttymode_t * tio)
{
#ifdef HAVE_TERMIOS_H
/*
 * standard System V termios interface
 */
    if (GET_TERMIOS(0, tio) < 0) {
    /* return error - use system defaults */
	tio->c_cc[VINTR] = CINTR;
	tio->c_cc[VQUIT] = CQUIT;
	tio->c_cc[VERASE] = CERASE;
	tio->c_cc[VKILL] = CKILL;
	tio->c_cc[VSTART] = CSTART;
	tio->c_cc[VSTOP] = CSTOP;
	tio->c_cc[VSUSP] = CSUSP;
#ifdef VDSUSP
	tio->c_cc[VDSUSP] = CDSUSP;
#endif
#ifdef VREPRINT
	tio->c_cc[VREPRINT] = CRPRNT;
#endif
#ifdef VDISCRD
	tio->c_cc[VDISCRD] = CFLUSH;
#endif
#ifdef VWERSE
	tio->c_cc[VWERSE] = CWERASE;
#endif
#ifdef VLNEXT
	tio->c_cc[VLNEXT] = CLNEXT;
#endif
    }
    tio->c_cc[VEOF] = CEOF;
    tio->c_cc[VEOL] = VDISABLE;
#ifdef VEOL2
    tio->c_cc[VEOL2] = VDISABLE;
#endif
#ifdef VSWTC
    tio->c_cc[VSWTC] = VDISABLE;
#endif
#ifdef VSWTCH
    tio->c_cc[VSWTCH] = VDISABLE;
#endif
#if VMIN != VEOF
    tio->c_cc[VMIN] = 1;
#endif
#if VTIME != VEOL
    tio->c_cc[VTIME] = 0;
#endif

/* input modes */
    tio->c_iflag = (BRKINT | IGNPAR | ICRNL | IXON
#ifdef IMAXBEL
		    | IMAXBEL
#endif
	);

/* output modes */
    tio->c_oflag = (OPOST | ONLCR);

/* control modes */
    tio->c_cflag = (CS8 | CREAD);

/* line discipline modes */
    tio->c_lflag = (ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK
#if defined (ECHOCTL) && defined (ECHOKE)
		    | ECHOCTL | ECHOKE
#endif
	);

/*
 * guess an appropriate value for Backspace
 */
#ifdef FORCE_BACKSPACE
    PrivMode(1, PrivMode_BackSpace);
#elif defined (FORCE_DELETE)
    PrivMode(0, PrivMode_BackSpace);
#else
    PrivMode((tio->c_cc[VERASE] == '\b'), PrivMode_BackSpace);
#endif

#else				/* HAVE_TERMIOS_H */

/*
 * sgtty interface
 */

/* get parameters -- gtty */
    if (ioctl(0, TIOCGETP, &(tio->sg)) < 0) {
	tio->sg.sg_erase = CERASE;	/* ^H */
	tio->sg.sg_kill = CKILL;	/* ^U */
    }
    tio->sg.sg_flags = (CRMOD | ECHO | EVENP | ODDP);

/* get special characters */
    if (ioctl(0, TIOCGETC, &(tio->tc)) < 0) {
	tio->tc.t_intrc = CINTR;	/* ^C */
	tio->tc.t_quitc = CQUIT;	/* ^\ */
	tio->tc.t_startc = CSTART;	/* ^Q */
	tio->tc.t_stopc = CSTOP;	/* ^S */
	tio->tc.t_eofc = CEOF;	/* ^D */
	tio->tc.t_brkc = -1;
    }
/* get local special chars */
    if (ioctl(0, TIOCGLTC, &(tio->lc)) < 0) {
	tio->lc.t_suspc = CSUSP;	/* ^Z */
	tio->lc.t_dsuspc = CDSUSP;	/* ^Y */
	tio->lc.t_rprntc = CRPRNT;	/* ^R */
	tio->lc.t_flushc = CFLUSH;	/* ^O */
	tio->lc.t_werasc = CWERASE;	/* ^W */
	tio->lc.t_lnextc = CLNEXT;	/* ^V */
    }
/* get line discipline */
    ioctl(0, TIOCGETD, &(tio->line));
#ifdef NTTYDISC
    tio->line = NTTYDISC;
#endif				/* NTTYDISC */
    tio->local = (LCRTBS | LCRTERA | LCTLECH | LPASS8 | LCRTKIL);

/*
 * guess an appropriate value for Backspace
 */
#ifdef FORCE_BACKSPACE
    PrivMode(1, PrivMode_BackSpace);
#elif defined (FORCE_DELETE)
    PrivMode(0, PrivMode_BackSpace);
#else
    PrivMode((tio->sg.sg_erase == '\b'), PrivMode_BackSpace);
#endif

#endif				/* HAVE_TERMIOS_H */
}
/*}}} */

/*{{{ run_command() */
/*
 * Run the command in a subprocess and return a file descriptor for the
 * master end of the pseudo-teletype pair with the command talking to
 * the slave.
 */
/* PROTO */
int
run_command(char *argv[])
{
    ttymode_t       tio;
    int             ptyfd;

/* Save and then give up any super-user privileges */
    privileges(SAVE);
    privileges(IGNORE);

    ptyfd = get_pty();
    if (ptyfd < 0)
	return -1;

/* store original tty status for restoration clean_exit() -- rgg 04/12/95 */
    lstat(ttydev, &ttyfd_stat);
#ifdef DEBUG_CMD
    fprintf(stderr, "Original settings of %s are mode %o, uid %d, gid %d\n",
	    ttydev, ttyfd_stat.st_mode, ttyfd_stat.st_uid, ttyfd_stat.st_gid);
#endif

/* install exit handler for cleanup */
#ifdef HAVE_ATEXIT
    atexit(clean_exit);
#else
#if defined (__sun__)
    on_exit(clean_exit, NULL);	/* non-ANSI exit handler */
#else
    print_error("no atexit(), UTMP entries can't be cleaned");
#endif
#endif

/*
 * get tty settings before fork()
 * and make a reasonable guess at the value for BackSpace
 */
    get_ttymode(&tio);
/* add Backspace value */
    SavedModes |= (PrivateModes & PrivMode_BackSpace);

/* add value for scrollBar */
    if (scrollbar_visible()) {
	PrivateModes |= PrivMode_scrollBar;
	SavedModes |= PrivMode_scrollBar;
    }
    if (menubar_visible()) {
	PrivateModes |= PrivMode_menuBar;
	SavedModes |= PrivMode_menuBar;
    }
#ifdef DEBUG_TTYMODE
    debug_ttymode(&tio);
#endif

/* spin off the command interpreter */
    signal(SIGHUP, Exit_signal);
#ifndef __svr4__
    signal(SIGINT, Exit_signal);
#endif
    signal(SIGQUIT, Exit_signal);
    signal(SIGTERM, Exit_signal);
    signal(SIGCHLD, Child_signal);

/* need to trap SIGURG for SVR4 (Unixware) rlogin */
/* signal (SIGURG, SIG_DFL); */

    cmd_pid = fork();
    if (cmd_pid < 0) {
	print_error("can't fork");
	return -1;
    }
    if (cmd_pid == 0) {		/* child */
    /* signal (SIGHUP, Exit_signal); */
    /* signal (SIGINT, Exit_signal); */
#ifdef HAVE_UNSETENV
    /* avoid passing old settings and confusing term size */
	unsetenv("LINES");
	unsetenv("COLUMNS");
    /* avoid passing termcap since terminfo should be okay */
	unsetenv("TERMCAP");
#endif				/* HAVE_UNSETENV */
    /* establish a controlling teletype for the new session */
	get_tty();

    /* initialize terminal attributes */
	SET_TTYMODE(0, &tio);

    /* become virtual console, fail silently */
	if (Options & Opt_console) {
#ifdef TIOCCONS
	    unsigned int    on = 1;

	    ioctl(0, TIOCCONS, &on);
#elif defined (SRIOCSREDIR)
	    int             fd = open(CONSOLE, O_WRONLY);

	    if (fd < 0 || ioctl(fd, SRIOCSREDIR, 0) < 0) {
		if (fd >= 0)
		    close(fd);
	    }
#endif				/* SRIOCSREDIR */
	}
	tt_winsize(0);		/* set window size */

    /* reset signals and spin off the command interpreter */
	signal(SIGINT, SIG_DFL);
	signal(SIGQUIT, SIG_DFL);
	signal(SIGCHLD, SIG_DFL);
    /*
     * mimick login's behavior by disabling the job control signals
     * a shell that wants them can turn them back on
     */
#ifdef SIGTSTP
	signal(SIGTSTP, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
#endif				/* SIGTSTP */

    /* command interpreter path */
	if (argv != NULL) {
#ifdef DEBUG_CMD
	    int             i;

	    for (i = 0; argv[i]; i++)
		fprintf(stderr, "argv [%d] = \"%s\"\n", i, argv[i]);
#endif
	    execvp(argv[0], argv);
	    print_error("can't execute \"%s\"", argv[0]);
	} else {
	    const char     *argv0, *shell;

	    if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
		shell = "/bin/sh";

	    argv0 = my_basename(shell);
	    if (Options & Opt_loginShell) {
		char           *p = MALLOC((strlen(argv0) + 2) * sizeof(char));

		p[0] = '-';
		strcpy(&p[1], argv0);
		argv0 = p;
	    }
	    execlp(shell, argv0, NULL);
	    print_error("can't execute \"%s\"", shell);
	}
	exit(EXIT_FAILURE);
    }
#ifdef UTMP_SUPPORT
    privileges(RESTORE);
    if (!(Options & Opt_utmpInhibit))
	makeutent(ttydev, display_name);	/* stamp /etc/utmp */
    privileges(IGNORE);
#endif

    return ptyfd;
}
/*}}} */

/*{{{ init_command() */
/* PROTO */
void
init_command(char *argv[])
{
/*
 * Initialize the command connection.
 * This should be called after the X server connection is established.
 */

/* Enable delete window protocol */
    wmDeleteWindow = XInternAtom(Xdisplay, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(Xdisplay, TermWin.parent, &wmDeleteWindow, 1);

#ifdef OFFIX_DND
/* Enable OffiX Dnd (drag 'n' drop) protocol */
    DndProtocol = XInternAtom(Xdisplay, "DndProtocol", False);
    DndSelection = XInternAtom(Xdisplay, "DndSelection", False);
#endif				/* OFFIX_DND */

    init_xlocale();

/* get number of available file descriptors */
#ifdef _POSIX_VERSION
    num_fds = sysconf(_SC_OPEN_MAX);
#else
    num_fds = getdtablesize();
#endif

#ifdef META8_OPTION
    meta_char = (Options & Opt_meta8 ? 0x80 : 033);
#endif
    if (Options & Opt_scrollTtyOutputInh)
	PrivateModes |= PrivMode_TtyOutputInh;
    if (Options & Opt_scrollKeypress)
	PrivateModes |= PrivMode_Keypress;

#ifdef GREEK_SUPPORT
    greek_init();
#endif

    Xfd = XConnectionNumber(Xdisplay);
    cmdbuf_ptr = cmdbuf_endp = cmdbuf_base;

    if ((cmd_fd = run_command(argv)) < 0) {
	print_error("aborting");
	exit(EXIT_FAILURE);
    }
}
/*}}} */

/*{{{ Xlocale */
/*
 * This is more or less stolen straight from XFree86 xterm.
 * This should support all European type languages.
 */
#ifndef NO_XLOCALE
/* PROTO */
void
init_xlocale(void)
{
    char           *p, *s, buf[32], tmp[1024];
    XIM             xim = NULL;
    XIMStyle        input_style = 0;
    XIMStyles      *xim_styles = NULL;
    int             found;

    Input_Context = NULL;

/* Debian hack: Removed dependence on Kanji or Big5 to use the locales
   specified by the environment (thanks to Ilya Ovchinnikov) - 2/3/98 BEM */
#if defined(KANJI) || defined(BIG5) || 1
    setlocale(LC_CTYPE, "");
#endif

    if (rs_inputMethod == NULL
#ifndef KANJI
	|| !*rs_inputMethod	/* required ? */
#endif
	) {
	if ((p = XSetLocaleModifiers("@im=none")) != NULL && *p)
	    xim = XOpenIM(Xdisplay, NULL, NULL, NULL);
    } else {
	strcpy(tmp, rs_inputMethod);
	for (s = tmp; *s; /*nil */ ) {
	    char           *end, *next_s;

	    while (*s && isspace(*s))
		s++;
	    if (!*s)
		break;
	    end = s;
	    while (*end && (*end != ','))
		end++;
	    next_s = end--;
	    while ((end >= s) && isspace(*end))
		end--;
	    *(end + 1) = '\0';

	    if (*s) {
		strcpy(buf, "@im=");
		strcat(buf, s);
		if ((p = XSetLocaleModifiers(buf)) != NULL && *p &&
		    (xim = XOpenIM(Xdisplay, NULL, NULL, NULL)) != NULL)
		    break;
	    }
	    if (!*next_s)
		break;
	    s = (next_s + 1);
	}
    }

    if (xim == NULL && (p = XSetLocaleModifiers("")) != NULL && *p)
	xim = XOpenIM(Xdisplay, NULL, NULL, NULL);

    if (xim == NULL) {
	print_error("Failed to open input method");
	return;
    }
    if (XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL) || !xim_styles) {
	print_error("input method doesn't support any style");
	XCloseIM(xim);
	return;
    }
    strcpy(tmp, (rs_preeditType ? rs_preeditType : "Root"));
    for (found = 0, s = tmp; *s && !found; /*nil */ ) {
	unsigned short  i;
	char           *end, *next_s;

	while (*s && isspace(*s))
	    s++;
	if (!*s)
	    break;
	end = s;
	while (*end && (*end != ','))
	    end++;
	next_s = end--;
	while ((end >= s) && isspace(*end))
	    *end-- = 0;

	if (!strcmp(s, "OverTheSpot"))
	    input_style = (XIMPreeditPosition | XIMStatusArea);
	else if (!strcmp(s, "OffTheSpot"))
	    input_style = (XIMPreeditArea | XIMStatusArea);
	else if (!strcmp(s, "Root"))
	    input_style = (XIMPreeditNothing | XIMStatusNothing);

	for (i = 0; i < xim_styles->count_styles; i++) {
	    if (input_style == xim_styles->supported_styles[i]) {
		found = 1;
		break;
	    }
	}
	s = next_s;
    }
    XFree(xim_styles);

    if (found == 0) {
	print_error("input method doesn't support my preedit type");
	XCloseIM(xim);
	return;
    }
/*
 * This program only understands the Root preedit_style yet
 * Then misc.preedit_type should default to:
 *          "OverTheSpot,OffTheSpot,Root"
 *  /MaF
 */
    if (input_style != (XIMPreeditNothing | XIMStatusNothing)) {
	print_error("This program only supports the \"Root\" preedit type");
	XCloseIM(xim);
	return;
    }
    Input_Context = XCreateIC(xim, XNInputStyle, input_style,
			      XNClientWindow, TermWin.parent,
			      XNFocusWindow, TermWin.parent,
			      NULL);

    if (Input_Context == NULL) {
	print_error("Failed to create input context");
	XCloseIM(xim);
    }
}
#endif				/* NO_XLOCALE */
/*}}} */

/*{{{ window resizing */
/*
 * Tell the teletype handler what size the window is.
 * Called after a window size change.
 */
/* PROTO */
void
tt_winsize(int fd)
{
    struct winsize  ws;

    if (fd < 0)
	return;

    ws.ws_col = (unsigned short)TermWin.ncol;
    ws.ws_row = (unsigned short)TermWin.nrow;
    ws.ws_xpixel = ws.ws_ypixel = 0;
    ioctl(fd, TIOCSWINSZ, &ws);
}

/* PROTO */
void
tt_resize(void)
{
    tt_winsize(cmd_fd);
}

/*}}} */

/*{{{ Convert the keypress event into a string */
/* PROTO */
void
lookup_key(XEvent * ev)
{
    static int      numlock_state = 0;
#ifdef DEBUG_CMD
    static int      debug_key = 1;	/* accessible by a debugger only */
#endif
#ifdef GREEK_SUPPORT
    static short    greek_mode = 0;
#endif
    static XComposeStatus compose =
    {NULL, 0};
    static unsigned char kbuf[KBUFSZ];
    int             ctrl, meta, shft, len;
    KeySym          keysym;

/*
 * use Num_Lock to toggle Keypad on/off.  If Num_Lock is off, allow an
 * escape sequence to toggle the Keypad.
 *
 * Always permit `shift' to override the current setting
 */
    shft = (ev->xkey.state & ShiftMask);
    ctrl = (ev->xkey.state & ControlMask);
    meta = (ev->xkey.state & Mod1Mask);
    if (numlock_state || (ev->xkey.state & Mod5Mask)) {
	numlock_state = (ev->xkey.state & Mod5Mask);	/* numlock toggle */
	PrivMode((!numlock_state), PrivMode_aplKP);
    }
    keysym = 0;
#ifndef NO_XLOCALE
    if (!XFilterEvent(ev, *(&ev->xkey.window))) {
	if (Input_Context != NULL) {
	    Status          status_return;

	    len = XmbLookupString(Input_Context, &ev->xkey, kbuf,
				  sizeof(kbuf), &keysym,
				  &status_return);
	} else {
	    len = XLookupString(&ev->xkey, kbuf,
				sizeof(kbuf), &keysym,
				&compose);
	}
    } else
	len = 0;
#else				/* NO_XLOCALE */
    len = XLookupString(&ev->xkey, kbuf, sizeof(kbuf), &keysym, &compose);
/*
 * have unmapped Latin[2-4] entries -> Latin1
 * good for installations  with correct fonts, but without XLOCAL
 */
    if (!len && (keysym >= 0x0100) && (keysym < 0x0400)) {
	len = 1;
	kbuf[0] = (keysym & 0xFF);
    }
#endif				/* NO_XLOCALE */

    if (len && (Options & Opt_scrollKeypress))
	TermWin.view_start = 0;

/* for some backwards compatibility */
#if defined (HOTKEY_CTRL) || defined (HOTKEY_META)
#ifdef HOTKEY_CTRL
#define HOTKEY	ctrl
#else
#ifdef HOTKEY_META
#define HOTKEY	meta
#endif
#endif
    if (HOTKEY) {
	if (keysym == ks_bigfont) {
	    change_font(0, FONT_UP);
	    return;
	} else if (keysym == ks_smallfont) {
	    change_font(0, FONT_DN);
	    return;
	}
    }
#undef HOTKEY
#endif

    if (shft) {
    /* Shift + F1 - F10 generates F11 - F20 */
	if (keysym >= XK_F1 && keysym <= XK_F10) {
	    keysym += (XK_F11 - XK_F1);
	    shft = 0;		/* turn off Shift */
	} else if (!ctrl && !meta && (PrivateModes & PrivMode_ShiftKeys)) {
           int lnsppg = TermWin.nrow * 4/5;
#ifdef PAGING_CONTEXT_LINES
             lnsppg = TermWin.nrow - PAGING_CONTEXT_LINES;
#endif
		
	    switch (keysym) {
	    /* normal XTerm key bindings */
	    case XK_Prior:	/* Shift+Prior = scroll back */
		if (TermWin.saveLines) {
		    scr_page(UP, lnsppg);
		    return;
		}
		break;

	    case XK_Next:	/* Shift+Next = scroll forward */
		if (TermWin.saveLines) {
		    scr_page(DN, lnsppg);
		    return;
		}
		break;

	    case XK_Insert:	/* Shift+Insert = paste mouse selection */
		selection_request(ev->xkey.time, ev->xkey.x, ev->xkey.y);
		return;
		break;

	    /* rxvt extras */
	    case XK_KP_Add:	/* Shift+KP_Add = bigger font */
		change_font(0, FONT_UP);
		return;
		break;

	    case XK_KP_Subtract:	/* Shift+KP_Subtract = smaller font */
		change_font(0, FONT_DN);
		return;
		break;
#ifdef XCIN_SUPPORT
/* Added by T.H.Hsieh for xcin support: shift+ctrl */
	    case XK_Control_L:
		{
		    char ch=37;
		    tt_write(&ch, 1, ev);
		}
		return;
		break;
/* End of added */
#endif
	    }
	}
    }
#ifdef UNSHIFTED_SCROLLKEYS
    else if (!ctrl && !meta) {
	switch (keysym) {
	case XK_Prior:
	    if (TermWin.saveLines) {
		scr_page(UP, TermWin.nrow * 4 / 5);
		return;
	    }
	    break;

	case XK_Next:
	    if (TermWin.saveLines) {
		scr_page(DN, TermWin.nrow * 4 / 5);
		return;
	    }
	    break;
	}
    }
#endif

#ifdef XCIN_SUPPORT
/* Added by T.H.Hsieh for xcin support: ctrl+shift */
    if (ctrl && keysym == XK_Shift_L) {
	char ch=50;
	tt_write(&ch, 1, ev);
	return;
    }
/* End of added */
#endif

    switch (keysym) {
    case XK_Print:
#ifdef DEBUG_SELECTION
	debug_selection();
	return;
#else
#ifdef PRINTPIPE
	scr_printscreen(ctrl | shft);
	return;
#endif
#endif
	break;

    case XK_Mode_switch:
#ifdef GREEK_SUPPORT
	greek_mode = !greek_mode;
	if (greek_mode) {
	    xterm_seq(XTerm_title, (greek_getmode() == GREEK_ELOT928 ?
				    "[Greek: iso]" : "[Greek: ibm]"));
	    greek_reset();
	} else
	    xterm_seq(XTerm_title, APL_NAME "-" VERSION);
	return;
#endif
	break;
    }

    if (keysym >= 0xFF00 && keysym <= 0xFFFF) {
#ifdef KEYSYM_RESOURCE
	if (!(shft | ctrl) && KeySym_map[keysym - 0xFF00] != NULL) {
	    const unsigned char *kbuf;
	    unsigned int    len;

	    kbuf = (KeySym_map[keysym - 0xFF00]);
	    len = *kbuf++;

	/* escape prefix */
	    if (meta
#ifdef META8_OPTION
		&& (meta_char == 033)
#endif
		) {
		const unsigned char ch = '\033';

		tt_write(&ch, 1, ev);
	    }
	    tt_write(kbuf, len, ev);
	    return;
	} else
#endif
	    switch (keysym) {
	    case XK_BackSpace:
		len = 1;
		kbuf[0] = (((PrivateModes & PrivMode_BackSpace) ?
			    !(shft | ctrl) : (shft | ctrl)) ? '\b' : '\177');
#ifdef XCIN_SUPPORT
/* Added by T.H.Hsieh for 2-bytes movement. */
		if(cursor_ll()) {
		    len ++;
		    kbuf[1] = kbuf[0];
		}
#endif
		break;

	    case XK_Tab:
		if (shft) {
		    len = 3;
		    strcpy(kbuf, "\033[Z");
		}
		break;

#ifdef XK_KP_Home
	    case XK_KP_Home:
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033Ow");
		    break;
		}
	    /* -> else FALL THROUGH */
#endif
	    case XK_Home:
		len = strlen(strcpy(kbuf, KS_HOME));
		break;

#ifdef XK_KP_Left
	    case XK_KP_Left:	/* \033Ot or standard */
	    case XK_KP_Up:	/* \033Ox or standard */
	    case XK_KP_Right:	/* \033Ov or standard */
	    case XK_KP_Down:	/* \033Ow or standard */
		if ((PrivateModes && PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033OZ");
		    kbuf[2] = ("txvw"[keysym - XK_KP_Left]);
		    break;
		} else {
		/* translate to std. cursor key */
		    keysym = XK_Left + (keysym - XK_KP_Left);
		}
	    /* FALL THROUGH */
#endif
	    case XK_Left:	/* "\033[D" */
	    case XK_Up:	/* "\033[A" */
	    case XK_Right:	/* "\033[C" */
	    case XK_Down:	/* "\033[B" */
		len = 3;
		strcpy(kbuf, "\033[@");
		kbuf[2] = ("DACB"[keysym - XK_Left]);
	    /* do Shift first */
		if (shft) {
		    kbuf[2] = ("dacb"[keysym - XK_Left]);
		} else if (ctrl) {
		    kbuf[1] = 'O';
		    kbuf[2] = ("dacb"[keysym - XK_Left]);
		} else if (PrivateModes & PrivMode_aplCUR) {
		    kbuf[1] = 'O';
		}
#ifdef XCIN_SUPPORT
/* Added by T.H.Hsieh for two bytes movement. */
		if ( (keysym==XK_Right && cursor_rr()) ||
		     (keysym==XK_Left  && cursor_ll()) ) {
		    kbuf[3] = kbuf[0];
		    kbuf[4] = kbuf[1];
		    kbuf[5] = kbuf[2];
		    len += 3;
		}
#endif
		break;

#ifndef UNSHIFTED_SCROLLKEYS
#ifdef XK_KP_Prior
	    case XK_KP_Prior:
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033Oy");
		    break;
		}
	    /* -> else FALL THROUGH */
#endif
	    case XK_Prior:
		len = 4;
		strcpy(kbuf, "\033[5~");
		break;
#ifdef XK_KP_Next
	    case XK_KP_Next:
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033Os");
		    break;
		}
	    /* -> else FALL THROUGH */
#endif
	    case XK_Next:
		len = 4;
		strcpy(kbuf, "\033[6~");
		break;
#endif
#ifdef XK_KP_End
	    case XK_KP_End:
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033Oq");
		    break;
		}
	    /* -> else FALL THROUGH */
#endif
	    case XK_End:
		len = strlen(strcpy(kbuf, KS_END));
		break;

	    case XK_Select:
		len = 4;
		strcpy(kbuf, "\033[4~");
		break;
#ifdef DXK_Remove		/* support for DEC remove like key */
	    case DXK_Remove:	/* drop */
#endif
	    case XK_Execute:
		len = 4;
		strcpy(kbuf, "\033[3~");
		break;
	    case XK_Insert:
		len = 4;
		strcpy(kbuf, "\033[2~");
		break;

	    case XK_Menu:
		len = 5;
		strcpy(kbuf, "\033[29~");
		break;
	    case XK_Find:
		len = 4;
		strcpy(kbuf, "\033[1~");
		break;
	    case XK_Help:
		len = 5;
		strcpy(kbuf, "\033[28~");
		break;

	    case XK_KP_Enter:
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033OM");
		} else {
		    len = 1;
		    kbuf[0] = '\r';
		}
		break;

#ifdef XK_KP_Begin
	    case XK_KP_Begin:
		len = 3;
		strcpy(kbuf, "\033Ou");
		break;

	    case XK_KP_Insert:
		len = 3;
		strcpy(kbuf, "\033Op");
		break;

	    case XK_KP_Delete:
		len = 3;
		strcpy(kbuf, "\033On");
		break;
#endif

	    case XK_KP_F1:	/* "\033OP" */
	    case XK_KP_F2:	/* "\033OQ" */
	    case XK_KP_F3:	/* "\033OR" */
	    case XK_KP_F4:	/* "\033OS" */
		len = 3;
		strcpy(kbuf, "\033OP");
		kbuf[2] += (keysym - XK_KP_F1);
		break;

	    case XK_KP_Multiply:	/* "\033Oj" : "*" */
	    case XK_KP_Add:	/* "\033Ok" : "+" */
	    case XK_KP_Separator:	/* "\033Ol" : "," */
	    case XK_KP_Subtract:	/* "\033Om" : "-" */
	    case XK_KP_Decimal:	/* "\033On" : "." */
	    case XK_KP_Divide:	/* "\033Oo" : "/" */
	    case XK_KP_0:	/* "\033Op" : "0" */
	    case XK_KP_1:	/* "\033Oq" : "1" */
	    case XK_KP_2:	/* "\033Or" : "2" */
	    case XK_KP_3:	/* "\033Os" : "3" */
	    case XK_KP_4:	/* "\033Ot" : "4" */
	    case XK_KP_5:	/* "\033Ou" : "5" */
	    case XK_KP_6:	/* "\033Ov" : "6" */
	    case XK_KP_7:	/* "\033Ow" : "7" */
	    case XK_KP_8:	/* "\033Ox" : "8" */
	    case XK_KP_9:	/* "\033Oy" : "9" */
	    /* allow shift to override */
		if ((PrivateModes & PrivMode_aplKP) ? !shft : shft) {
		    len = 3;
		    strcpy(kbuf, "\033Oj");
		    kbuf[2] += (keysym - XK_KP_Multiply);
		} else {
		    len = 1;
		    kbuf[0] = ('*' + (keysym - XK_KP_Multiply));
		}
		break;

#define FKEY(n,fkey) len = 5;\
sprintf (kbuf,"\033[%02d~", (int)((n) + (keysym - fkey)))

	    case XK_F1:	/* "\033[11~" */
	    case XK_F2:	/* "\033[12~" */
	    case XK_F3:	/* "\033[13~" */
	    case XK_F4:	/* "\033[14~" */
	    case XK_F5:	/* "\033[15~" */
		FKEY(11, XK_F1);
		break;

	    case XK_F6:	/* "\033[17~" */
	    case XK_F7:	/* "\033[18~" */
	    case XK_F8:	/* "\033[19~" */
	    case XK_F9:	/* "\033[20~" */
	    case XK_F10:	/* "\033[21~" */
		FKEY(17, XK_F6);
		break;

	    case XK_F11:	/* "\033[23~" */
	    case XK_F12:	/* "\033[24~" */
	    case XK_F13:	/* "\033[25~" */
	    case XK_F14:	/* "\033[26~" */
		FKEY(23, XK_F11);
		break;

	    case XK_F15:	/* "\033[28~" */
	    case XK_F16:	/* "\033[29~" */
		FKEY(28, XK_F15);
		break;

	    case XK_F17:	/* "\033[31~" */
	    case XK_F18:	/* "\033[32~" */
	    case XK_F19:	/* "\033[33~" */
	    case XK_F20:	/* "\033[34~" */
	    case XK_F21:	/* "\033[35~" */
	    case XK_F22:	/* "\033[36~" */
	    case XK_F23:	/* "\033[37~" */
	    case XK_F24:	/* "\033[38~" */
	    case XK_F25:	/* "\033[39~" */
	    case XK_F26:	/* "\033[40~" */
	    case XK_F27:	/* "\033[41~" */
	    case XK_F28:	/* "\033[42~" */
	    case XK_F29:	/* "\033[43~" */
	    case XK_F30:	/* "\033[44~" */
	    case XK_F31:	/* "\033[45~" */
	    case XK_F32:	/* "\033[46~" */
	    case XK_F33:	/* "\033[47~" */
	    case XK_F34:	/* "\033[48~" */
	    case XK_F35:	/* "\033[49~" */
		FKEY(31, XK_F17);
		break;
#undef FKEY
#ifdef KS_DELETE
	    case XK_Delete:
		len = strlen(strcpy(kbuf, KS_DELETE));
#ifdef XCIN_SUPPORT
/* Added by T.H.Hsieh for 2-bytes movement */
		if (cursor_rr()) {
		    strcat(kbuf, KS_DELETE);
		    len *= 2;
		}
#endif
		break;
#endif
	    }
    /*
     * Pass meta for all function keys, if 'meta' option set
     */
#ifdef META8_OPTION
	if (meta && (meta_char == 0x80) && len > 0) {
	    kbuf[len - 1] |= 0x80;
	}
#endif
    } else if (ctrl && keysym == XK_minus) {
	len = 1;
	kbuf[0] = '\037';	/* Ctrl-Minus generates ^_ (31) */
    } else {
#ifdef META8_OPTION
    /* set 8-bit on */
	if (meta && (meta_char == 0x80)) {
	    unsigned char  *ch;

	    for (ch = kbuf; ch < kbuf + len; ch++)
		*ch |= 0x80;
	    meta = 0;
	}
#endif
#ifdef GREEK_SUPPORT
	if (greek_mode)
	    len = greek_xlat(kbuf, len);
#endif
    /*nil */ ;
    }

    if (len <= 0)
	return;			/* not mapped */

/*
 * these modifications only affect the static keybuffer
 * pass Shift/Control indicators for function keys ending with `~'
 *
 * eg,
 *   Prior = "ESC[5~"
 *   Shift+Prior = "ESC[5~"
 *   Ctrl+Prior = "ESC[5^"
 *   Ctrl+Shift+Prior = "ESC[5@"
 * Meta adds an Escape prefix (with META8_OPTION, if meta == <escape>).
 */
    if (kbuf[0] == '\033' && kbuf[1] == '[' && kbuf[len - 1] == '~')
	kbuf[len - 1] = (shft ? (ctrl ? '@' : '$') : (ctrl ? '^' : '~'));

/* escape prefix */
    if (meta
#ifdef META8_OPTION
	&& (meta_char == 033)
#endif
	) {
	const unsigned char ch = '\033';

	tt_write(&ch, 1, ev);
#ifdef XCIN_SUPPORT
/*  Add by T.H.Hsieh for xcin support. */
	return;
/*  End of change for xcin. */
#endif
    }
#ifdef DEBUG_CMD
    if (debug_key) {		/* Display keyboard buffer contents */
	char           *p;
	int             i;

	fprintf(stderr, "key 0x%04X [%d]: `", (unsigned int)keysym, len);
	for (i = 0, p = kbuf; i < len; i++, p++)
	    fprintf(stderr, (*p >= ' ' && *p < '\177' ? "%c" : "\\%03o"), *p);
	fprintf(stderr, "'\n");
    }
#endif				/* DEBUG_CMD */
    tt_write(kbuf, len, ev);
}
/*}}} */

#if (MENUBAR_MAX)
/*{{{ cmd_write(), cmd_getc() */
/* attempt to `write' COUNT to the input buffer */
/* PROTO */
unsigned int
cmd_write(const unsigned char *str, unsigned int count)
{
    int             n;

    n = (count - (cmdbuf_ptr - cmdbuf_base));
/* need to insert more chars that space available in the front */
    if (n > 0) {
    /* try and get more space from the end */
	unsigned char  *src, *dst;

	dst = (cmdbuf_base + sizeof(cmdbuf_base) - 1);	/* max pointer */

	if ((cmdbuf_ptr + n) > dst)
	    n = (dst - cmdbuf_ptr);	/* max # chars to insert */

	if ((cmdbuf_endp + n) > dst)
	    cmdbuf_endp = (dst - n);	/* truncate end if needed */

    /* equiv: memmove ((cmdbuf_ptr+n), cmdbuf_ptr, n); */
	src = cmdbuf_endp;
	dst = src + n;
    /* FIXME: anything special to avoid possible pointer wrap? */
	while (src >= cmdbuf_ptr)
	    *dst-- = *src--;

    /* done */
	cmdbuf_ptr += n;
	cmdbuf_endp += n;
    }
    while (count-- && cmdbuf_ptr > cmdbuf_base) {
    /* sneak one in */
	cmdbuf_ptr--;
	*cmdbuf_ptr = str[count];
    }

    return 0;
}
#endif				/* MENUBAR_MAX */
/* cmd_getc() - Return next input character */
/*
 * Return the next input character after first passing any keyboard input
 * to the command.
 */
/* PROTO */
unsigned char
cmd_getc(void)
{
#define TIMEOUT_USEC	5000
    static short    refreshed = 0;
    fd_set          readfds;
    int             retval;
    struct itimerval value;

/* If there have been a lot of new lines, then update the screen
 * What the heck I'll cheat and only refresh less than every page-full.
 * the number of pages between refreshes is refresh_limit, which
 * is incremented here because we must be doing flat-out scrolling.
 *
 * refreshing should be correct for small scrolls, because of the
 * time-out */
    if (refresh_count >= (refresh_limit * (TermWin.nrow - 1))) {
	if (refresh_limit < REFRESH_PERIOD)
	    refresh_limit++;
	refresh_count = 0;
	refreshed = 1;
	scr_refresh(refresh_type);
    }
/* characters already read in */
    if (cmdbuf_ptr < cmdbuf_endp)
	goto Return_Char;

    for (;;) {
        v_doPending();  		/* output any pending chars */
	while (XPending(Xdisplay)) {	/* process pending X events */
	    XEvent          ev;

	    refreshed = 0;
	    XNextEvent(Xdisplay, &ev);
	    process_x_event(&ev);

	/* in case button actions pushed chars to cmdbuf */
	    if (cmdbuf_ptr < cmdbuf_endp)
		goto Return_Char;
	}
#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
	if (scrollbar_isUp()) {
	    if (!scroll_arrow_delay-- && scr_page(UP, 1)) {
		scroll_arrow_delay = SCROLLBAR_CONTINUOUS_DELAY;
		refreshed = 0;
		refresh_type |= SMOOTH_REFRESH;
	    }
	} else if (scrollbar_isDn()) {
	    if (!scroll_arrow_delay-- && scr_page(DN, 1)) {
		scroll_arrow_delay = SCROLLBAR_CONTINUOUS_DELAY;
		refreshed = 0;
		refresh_type |= SMOOTH_REFRESH;
	    }
	}
#endif				/* SCROLLBAR_BUTTON_CONTINUAL_SCROLLING */

    /* Nothing to do! */
	FD_ZERO(&readfds);
	FD_SET(cmd_fd, &readfds);
	FD_SET(Xfd, &readfds);
	value.it_value.tv_usec = TIMEOUT_USEC;
	value.it_value.tv_sec = 0;

	retval = select(num_fds, &readfds, NULL, NULL,
			((refreshed
#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
			  && !(scrollbar_isUpDn())
#endif
			 ) ? NULL : &value.it_value));

    /* See if we can read from the application */
	if (FD_ISSET(cmd_fd, &readfds)) {
	    unsigned int    count = BUFSIZ;

	    cmdbuf_ptr = cmdbuf_endp = cmdbuf_base;

	/* while (count > sizeof(cmdbuf_base) / 2) */
	    while (count) {
		int             n = read(cmd_fd, cmdbuf_endp, count);

		if (n <= 0)
		    break;
		cmdbuf_endp += n;
		count -= n;
	    }
	/* some characters read in */
	    if (count != BUFSIZ)
		goto Return_Char;
	}
    /* select statement timed out - better update the screen */
	if (retval == 0) {
	    refresh_count = 0;
	    refresh_limit = 1;
	    if (!refreshed) {
		refreshed = 1;
		scr_refresh(refresh_type);
		scrollbar_show(1);
	    }
	}
    }
    return 0;

  Return_Char:
    refreshed = 0;
    return (*cmdbuf_ptr++);
}
/*}}} */

/*
 * the 'essential' information for reporting Mouse Events
 * pared down from XButtonEvent
 */
static struct {
    int clicks;
    Time time;			/* milliseconds */
    unsigned int state;		/* key or button mask */
    unsigned int button;	/* detail */
} MEvent = { 0, CurrentTime, 0, AnyButton };

/* PROTO */
static void
mouse_report (XButtonEvent * ev)
{
    int             button_number, key_state = 0;
    int             x, y;

    x = ev->x;
    y = ev->y;
    pixel_position (&x, &y);

    button_number = ((MEvent.button == AnyButton) ? 3 :
		     (MEvent.button - Button1));

    if (PrivateModes & PrivMode_MouseX10)
      {
	  /*
	   * do not report ButtonRelease
	   * no state info allowed
	   */
	  key_state = 0;
	  if (button_number == 3)
	    return;
      }
    else
      {
	  /* let's be explicit here ... from <X11/X.h>
	   * #define ShiftMask	(1<<0)
	   * #define ControlMask	(1<<2)
	   * #define Mod1Mask		(1<<3)
	   *
	   * and XTerm mouse reporting needs these values:
	   *   4 = Shift
	   *   8 = Meta
	   *  16 = Control
	   * plus will add in our own Double-Click reporting
	   *  32 = Double Click
	   */
	  key_state = (((MEvent.state & (ShiftMask | ControlMask))
			+ ((MEvent.state & Mod1Mask) ? 2 : 0)
#ifdef MOUSE_REPORT_DOUBLECLICK
			+ (MEvent.clicks > 1 ? 8 : 0)
#endif
			) << 2);
      }

#ifdef DEBUG_MOUSEREPORT
    fprintf (stderr, "Mouse [");
    if (key_state & 16)	fputc ('C', stderr);
    if (key_state & 4)	fputc ('S', stderr);
    if (key_state & 2)	fputc ('A', stderr);
    if (key_state & 32) fputc ('2', stderr);
    fprintf (stderr, "]: <%d>, %d/%d\n",
	     button_number,
	     x + 1,
	     y + 1);
#else
    tt_printf("\033[M%c%c%c",
	      (32 + button_number + key_state),
	      (32 + x + 1),
	      (32 + y + 1));
#endif
}

/*{{{ process an X event */
/* PROTO */
void
process_x_event(XEvent * ev)
{
    static int      bypass_keystate = 0;
    int             reportmode;
    static int csrO = 0;     /* Hops - csr offset in thumb/slider      */
                             /*        to give proper Scroll behaviour */

    switch (ev->type) {
    case KeyPress:
	lookup_key(ev);
	break;

    case ClientMessage:
	if (ev->xclient.format == 32 && ev->xclient.data.l[0] == wmDeleteWindow)
	    exit(EXIT_SUCCESS);
#ifdef OFFIX_DND
    /* OffiX Dnd (drag 'n' drop) protocol */
	if (ev->xclient.message_type == DndProtocol &&
	    ((ev->xclient.data.l[0] == DndFile) ||
	     (ev->xclient.data.l[0] == DndDir) ||
	     (ev->xclient.data.l[0] == DndLink))) {
	/* Get Dnd data */
	    Atom            ActualType;
	    int             ActualFormat;
	    unsigned char  *data;
	    unsigned long   Size, RemainingBytes;

	    XGetWindowProperty(Xdisplay, Xroot,
			       DndSelection,
			       0L, 1000000L,
			       False, AnyPropertyType,
			       &ActualType, &ActualFormat,
			       &Size, &RemainingBytes,
			       &data);
	    XChangeProperty(Xdisplay, Xroot,
			    XA_CUT_BUFFER0, XA_STRING,
			    8, PropModeReplace,
			    data, strlen(data));
	    selection_paste(Xroot, XA_CUT_BUFFER0, True);
	    XSetInputFocus(Xdisplay, Xroot, RevertToNone, CurrentTime);
	}
#endif				/* OFFIX_DND */
	break;

    case MappingNotify:
	XRefreshKeyboardMapping(&(ev->xmapping));
	break;

    /* Here's my conclusiion:
     * If the window is completely unobscured, use bitblt's
     * to scroll. Even then, they're only used when doing partial
     * screen scrolling. When partially obscured, we have to fill
     * in the GraphicsExpose parts, which means that after each refresh,
     * we need to wait for the graphics expose or Noexpose events,
     * which ought to make things real slow!
     */
    case VisibilityNotify:
	switch (ev->xvisibility.state) {
	case VisibilityUnobscured:
	    refresh_type = FAST_REFRESH;
	    break;

	case VisibilityPartiallyObscured:
	    refresh_type = SLOW_REFRESH;
	    break;

	default:
	    refresh_type = NO_REFRESH;
	    break;
	}
	break;

    case FocusIn:
	if (!TermWin.focus) {
	    TermWin.focus = 1;
#ifdef XCIN_SUPPORT
/*  Add by T.H.Hsieh for xcin support */
	    send_FocusIn(Xdisplay, TermWin.parent);
/*  End of change for xcin */
#endif
#ifndef NO_XLOCALE
	    if (Input_Context != NULL)
		XSetICFocus(Input_Context);
#endif
	}
	break;

    case FocusOut:
	if (TermWin.focus) {
	    TermWin.focus = 0;
#ifndef NO_XLOCALE
	    if (Input_Context != NULL)
		XUnsetICFocus(Input_Context);
#endif
	}
	break;

    case ConfigureNotify:
	resize_window();
	menubar_expose();
	break;

    case SelectionClear:
	selection_clear();
	break;

    case SelectionNotify:
	selection_paste(ev->xselection.requestor, ev->xselection.property, True);
	break;

    case SelectionRequest:
	selection_send(&(ev->xselectionrequest));
	break;

    case GraphicsExpose:
    case Expose:
	if (ev->xany.window == TermWin.vt) {
	    scr_expose(ev->xexpose.x, ev->xexpose.y,
		       ev->xexpose.width, ev->xexpose.height);
	} else {
	    XEvent          unused_xevent;

	    while (XCheckTypedWindowEvent(Xdisplay, ev->xany.window,
					  Expose,
					  &unused_xevent)) ;
	    while (XCheckTypedWindowEvent(Xdisplay, ev->xany.window,
					  GraphicsExpose,
					  &unused_xevent)) ;
	    if (isScrollbarWindow(ev->xany.window)) {
		scrollbar_setNone();
		scrollbar_show(0);
	    }
#if (MENUBAR_MAX)
	    if (menubar_visible() && isMenuBarWindow(ev->xany.window))
		menubar_expose();
#endif				/* MENUBAR_MAX */
	    Gr_expose(ev->xany.window);
	}
	break;

    case ButtonPress:
	bypass_keystate = (ev->xbutton.state & (Mod1Mask | ShiftMask));
	reportmode = (bypass_keystate ?
		      0 : (PrivateModes & PrivMode_mouse_report));

	if (ev->xany.window == TermWin.vt) {
	    if (ev->xbutton.subwindow != None)
		Gr_ButtonPress(ev->xbutton.x, ev->xbutton.y);
	    else {
		if (reportmode) {
		    /* mouse report from vt window */
		    /* save the xbutton state (for ButtonRelease) */
		    MEvent.state = ev->xbutton.state;
#ifdef MOUSE_REPORT_DOUBLECLICK
		    if (ev->xbutton.button == MEvent.button
			&& (ev->xbutton.time - MEvent.time < MULTICLICK_TIME))
		      {
			  /* same button, within alloted time */
			  MEvent.clicks++;
			  if (MEvent.clicks > 1)
			    {
				/* only report double clicks */
				MEvent.clicks = 2;
				mouse_report (&(ev->xbutton));

				/* don't report the release */
				MEvent.clicks = 0;
				MEvent.button = AnyButton;
			    }
		      }
			else
		      {
			  /* different button, or time expired */
			  MEvent.clicks = 1;
			  MEvent.button = ev->xbutton.button;
			  mouse_report (&(ev->xbutton));
		    }
#else
		    MEvent.button = ev->xbutton.button;
		    mouse_report(&(ev->xbutton));
#endif	/* MOUSE_REPORT_DOUBLECLICK */
		    MEvent.time = ev->xbutton.time;
		    return;
		} else
		    switch (ev->xbutton.button) {
		    case Button1:
		      if (MEvent.button == Button1
			  && (ev->xbutton.time - MEvent.time < MULTICLICK_TIME))
			MEvent.clicks++;
			else
			MEvent.clicks = 1;
		      selection_click(MEvent.clicks, ev->xbutton.x, ev->xbutton.y);
		      MEvent.button = Button1;
			break;

		    case Button3:
		      if (MEvent.button == Button3
			  && (ev->xbutton.time - MEvent.time < MULTICLICK_TIME))
			    selection_rotate(ev->xbutton.x, ev->xbutton.y);
			else
			    selection_extend(ev->xbutton.x, ev->xbutton.y, 1);
		      MEvent.button = Button3;
			break;
		    }
		MEvent.time = ev->xbutton.time;
		return;
	    }
	}
	if (isScrollbarWindow(ev->xany.window)) {
	    scrollbar_setNone();
	/*
	 * Rxvt-style scrollbar:
	 * move up if mouse is above slider
	 * move dn if mouse is below slider
	 *
	 * XTerm-style scrollbar:
	 * Move display proportional to pointer location
	 * pointer near top -> scroll one line
	 * pointer near bot -> scroll full page
	 */
#ifndef NO_SCROLLBAR_REPORT
	    if (reportmode) {
	    /*
	     * Mouse report disabled scrollbar:
	     * arrow buttons - send up/down
	     * click on scrollbar - send pageup/down
	     */
		if (scrollbar_upButton(ev->xbutton.y))
		    tt_printf("\033[A");
		else if (scrollbar_dnButton(ev->xbutton.y))
		    tt_printf("\033[B");
		else
		    switch (ev->xbutton.button) {
		    case Button2:
			tt_printf("\014");
			break;
		    case Button1:
			tt_printf("\033[6~");
			break;
		    case Button3:
			tt_printf("\033[5~");
			break;
		    }
	    } else
#endif				/* NO_SCROLLBAR_REPORT */
	    {
		if (scrollbar_upButton(ev->xbutton.y)) {
#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
		    scroll_arrow_delay = SCROLLBAR_INITIAL_DELAY;
#endif
		    if (scr_page(UP, 1))
			scrollbar_setUp();
		} else if (scrollbar_dnButton(ev->xbutton.y)) {
#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
		    scroll_arrow_delay = SCROLLBAR_INITIAL_DELAY;
#endif
		    if (scr_page(DN, 1))
			scrollbar_setDn();
		} else
		    switch (ev->xbutton.button) {
		    case Button2:
#ifndef FUNKY_SCROLL_BEHAVIOUR
			    csrO = (scrollBar.bot - scrollBar.top)/2;
			    /* align to thumb center */
#else
#ifndef XTERM_SCROLLBAR
			if (scrollbar_above_slider(ev->xbutton.y) ||
			    scrollbar_below_slider(ev->xbutton.y))
#endif
#endif  /* !FUNKY_SCROLL_BEHAVIOUR */			
			    scr_move_to(scrollbar_position(ev->xbutton.y)-csrO,
					scrollbar_size());
			scrollbar_setMotion();
			break;

		    case Button1:
#ifndef FUNKY_SCROLL_BEHAVIOUR
			csrO = ev->xbutton.y - scrollBar.top;
			                   /* ptr ofset in thumb */
#endif 
		    /*drop */

		    case Button3:
#ifndef XTERM_SCROLLBAR
			if (scrollbar_above_slider(ev->xbutton.y))
#ifdef RXVT_SCROLL_FULL
			    scr_page(UP, TermWin.nrow - 1);
#else
			    scr_page(UP, TermWin.nrow / 4);
#endif
			else if (scrollbar_below_slider(ev->xbutton.y))
#ifdef RXVT_SCROLL_FULL
			    scr_page(DN, TermWin.nrow - 1);
#else
			    scr_page(DN, TermWin.nrow / 4);
#endif
			else
			    scrollbar_setMotion();
#else				/* XTERM_SCROLLBAR */
			scr_page((ev->xbutton.button == Button1 ? DN : UP),
				 (TermWin.nrow *
				  scrollbar_position(ev->xbutton.y) /
				  scrollbar_size())
			    );
#endif				/* XTERM_SCROLLBAR */
			break;
		    }
	    }
	    return;
	}
#if (MENUBAR_MAX)
	if (isMenuBarWindow(ev->xany.window)) {
	    menubar_control(&(ev->xbutton));
	    return;
	}
#endif				/* MENUBAR_MAX */
	break;

    case ButtonRelease:
	csrO = 0;        /* reset csr Offset */
	reportmode = (bypass_keystate ?
		      0 : (PrivateModes & PrivMode_mouse_report));

	if (scrollbar_isUpDn()) {
	    scrollbar_setNone();
	    scrollbar_show(0);
#ifdef SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
	    refresh_type &= ~SMOOTH_REFRESH;
#endif
	}
	if (ev->xany.window == TermWin.vt) {
	    if (ev->xbutton.subwindow != None)
		Gr_ButtonRelease(ev->xbutton.x, ev->xbutton.y);
	    else {
		if (reportmode) {
		    /* mouse report from vt window */
#ifdef MOUSE_REPORT_DOUBLECLICK
		    /* only report the release of 'slow' single clicks */
		    if (MEvent.button != AnyButton &&
			(ev->xbutton.button != MEvent.button ||
			 (ev->xbutton.time - MEvent.time > MULTICLICK_TIME/2))
			)
		      {
			  MEvent.clicks = 0;
			  MEvent.button = AnyButton;
			mouse_report(&(ev->xbutton));
		    }
#else	/* MOUSE_REPORT_DOUBLECLICK */
		    MEvent.button = AnyButton;
		    mouse_report (&(ev->xbutton));
#endif	/* MOUSE_REPORT_DOUBLECLICK */
		    return;
		}
	    /*
	     * dumb hack to compensate for the failure of click-and-drag
	     * when overriding mouse reporting
	     */
		if ((PrivateModes & PrivMode_mouse_report) &&
		    (bypass_keystate) &&
		    (ev->xbutton.button == Button1) &&
		    (MEvent.clicks <= 1))
		    selection_extend(ev->xbutton.x, ev->xbutton.y, 0);

		switch (ev->xbutton.button) {
		case Button1:
		case Button3:
		    selection_make(ev->xbutton.time);
		    break;

		case Button2:
		    selection_request(ev->xbutton.time,
				      ev->xbutton.x, ev->xbutton.y);
		    break;
		}
	    }
	}
#if (MENUBAR_MAX)
	else if (isMenuBarWindow(ev->xany.window)) {
	    menubar_control(&(ev->xbutton));
	}
#endif				/* MENUBAR_MAX */
	break;

    case MotionNotify:
#if (MENUBAR_MAX)
	if (isMenuBarWindow(ev->xany.window)) {
	    menubar_control(&(ev->xbutton));
	    break;
	}
#endif				/* MENUBAR_MAX */
	if ((PrivateModes & PrivMode_mouse_report) && !(bypass_keystate))
	    break;

	if (ev->xany.window == TermWin.vt) {
	    if ((ev->xbutton.state & (Button1Mask | Button3Mask))) {
		Window          unused_root, unused_child;
		int             unused_root_x, unused_root_y;
		unsigned int    unused_mask;

		while (XCheckTypedWindowEvent(Xdisplay, TermWin.vt,
					      MotionNotify, ev)) ;
		XQueryPointer(Xdisplay, TermWin.vt,
			      &unused_root, &unused_child,
			      &unused_root_x, &unused_root_y,
			      &(ev->xbutton.x), &(ev->xbutton.y),
			      &unused_mask);
#ifdef MOUSE_THRESHOLD
	    /* deal with a `jumpy' mouse */
		if ((ev->xmotion.time - MEvent.time) > MOUSE_THRESHOLD)
#endif
		    selection_extend((ev->xbutton.x), (ev->xbutton.y),
				     (ev->xbutton.state & Button3Mask));
	    }
	} else if ((ev->xany.window == scrollBar.win) && scrollbar_isMotion()) {
	    Window          unused_root, unused_child;
	    int             unused_root_x, unused_root_y;
	    unsigned int    unused_mask;

	    while (XCheckTypedWindowEvent(Xdisplay, scrollBar.win,
					  MotionNotify, ev)) ;
	    XQueryPointer(Xdisplay, scrollBar.win,
			  &unused_root, &unused_child,
			  &unused_root_x, &unused_root_y,
			  &(ev->xbutton.x), &(ev->xbutton.y),
			  &unused_mask);
	    scr_move_to(scrollbar_position(ev->xbutton.y) - csrO,
			scrollbar_size());
	    scr_refresh(refresh_type);
	    refresh_count = refresh_limit = 0;
	    scrollbar_show(1);
	}
	break;
    }
}
/*}}} */

/*{{{ tt_write(), tt_printf() - output to command */
/*
 * Send count characters directly to the command
 */
/* PROTO */
void
tt_write(const unsigned char *buf, unsigned int count, XEvent *event)
{
#ifdef XCIN_SUPPORT
/*  Modified by T.H.Hsieh for xcin support */

    int k_status;
    u_char chstr[256];
    int send_key(Display *display, Window win, XKeyEvent *eve, char *buf);

    if (event == NULL)
        v_writeBig(cmd_fd,(char *)buf, count);
    else {
        k_status=send_key(Xdisplay, TermWin.parent, (XKeyEvent *)event, chstr);
        if (!k_status) 
	    v_writeBig(cmd_fd, (char *)buf, count);
        else if (chstr[0]) {
            v_writeBig(cmd_fd, (char *)chstr, strlen(chstr));
        }
    }
/* End of change for xcin */
#else
    v_writeBig(cmd_fd,(char *)buf, count);
#endif
#if 0
    /* hangs in write with a big paste fm selection hops 19-Sep-97*/
    while (count > 0) {
	int             n = write(cmd_fd, buf, count);

	if (n > 0) {
	    count -= n;
	    buf += n;
	}
    }
#endif    
}

/*
 * Send printf() formatted output to the command.
 * Only use for small ammounts of data.
 */
/* PROTO */
void
tt_printf(const unsigned char *fmt,...)
{
    static unsigned char buf[256];
    va_list         arg_ptr;

    va_start(arg_ptr, fmt);
    vsprintf(buf, fmt, arg_ptr);
    va_end(arg_ptr);
    tt_write(buf, strlen(buf), NULL);
}

/*}}} */

/*{{{ print pipe */
/*----------------------------------------------------------------------*/
#ifdef PRINTPIPE
/* PROTO */
FILE           *
popen_printer(void)
{
    FILE           *stream = popen(rs_print_pipe, "w");

    if (stream == NULL)
	print_error("can't open printer pipe");
    return stream;
}

/* PROTO */
int
pclose_printer(FILE * stream)
{
    fflush(stream);
/* pclose() reported not to work on SunOS 4.1.3 */
#if defined (__sun__)
/* pclose works provided SIGCHLD handler uses waitpid */
    return pclose(stream);	/* return fclose (stream); */
#else
    return pclose(stream);
#endif
}

/*
 * simulate attached vt100 printer
 */
/* PROTO */
void
process_print_pipe(void)
{
    const char     *const escape_seq = "\033[4i";
    const char     *const rev_escape_seq = "i4[\033";
    int             index;
    FILE           *fd;

    if ((fd = popen_printer()) != NULL) {
	for (index = 0; index < 4; /* nil */ ) {
	    unsigned char   ch = cmd_getc();

	    if (ch == escape_seq[index])
		index++;
	    else if (index)
		for ( /*nil */ ; index > 0; index--)
		    fputc(rev_escape_seq[index - 1], fd);

	    if (index == 0)
		fputc(ch, fd);
	}
	pclose_printer(fd);
    }
}
#endif				/* PRINTPIPE */
/*}}} */

/*{{{ process escape sequences */
/* PROTO */
void
process_escape_seq(void)
{
    unsigned char   ch = cmd_getc();

    switch (ch) {
    /* case 1:        do_tek_mode (); break; */
    case '#':
	if (cmd_getc() == '8')
	    scr_E();
	break;
    case '(':
	scr_charset_set(0, cmd_getc());
	break;
    case ')':
	scr_charset_set(1, cmd_getc());
	break;
    case '*':
	scr_charset_set(2, cmd_getc());
	break;
    case '+':
	scr_charset_set(3, cmd_getc());
	break;
#if defined(KANJI) || defined(BIG5)
    case '$':
	scr_charset_set(-2, cmd_getc());
	break;
#endif
    case '7':
	scr_cursor(SAVE);
	break;
    case '8':
	scr_cursor(RESTORE);
	break;
    case '=':
    case '>':
	PrivMode((ch == '='), PrivMode_aplKP);
	break;
    case '@':
	(void)cmd_getc();
	break;
    case 'D':
	scr_index(UP);
	break;
    case 'E':
	scr_add_lines("\n\r", 1, 2);
	break;
    case 'G':
	process_graphics();
	break;
    case 'H':
	scr_set_tab(1);
	break;
    case 'M':
	scr_index(DN);
	break;
    /*case 'N': scr_single_shift (2);   break; */
    /*case 'O': scr_single_shift (3);   break; */
    case 'Z':
	tt_printf(ESCZ_ANSWER);
	break;			/* steal obsolete ESC [ c */
    case '[':
	process_csi_seq();
	break;
    case ']':
	process_xterm_seq();
	break;
    case 'c':
	scr_poweron();
	break;
    case 'n':
	scr_charset_choose(2);
	break;
    case 'o':
	scr_charset_choose(3);
	break;
    }
}
/*}}} */

/*{{{ process CSI (code sequence introducer) sequences `ESC[' */
/* PROTO */
void
process_csi_seq(void)
{
    unsigned char   ch, priv;
    unsigned int    nargs;
    int             arg[ESC_ARGS];

    nargs = 0;
    arg[0] = 0;
    arg[1] = 0;

    priv = 0;
    ch = cmd_getc();
    if (ch >= '<' && ch <= '?') {
	priv = ch;
	ch = cmd_getc();
    }
/* read any numerical arguments */
    do {
	int             n;

	for (n = 0; isdigit(ch); ch = cmd_getc())
	    n = n * 10 + (ch - '0');

	if (nargs < ESC_ARGS)
	    arg[nargs++] = n;
	if (ch == '\b') {
	    scr_backspace();
	} else if (ch == 033) {
	    process_escape_seq();
	    return;
	} else if (ch < ' ') {
	    scr_add_lines(&ch, 0, 1);
	    return;
	}
	if (ch < '@')
	    ch = cmd_getc();
    }
    while (ch >= ' ' && ch < '@');
    if (ch == 033) {
	process_escape_seq();
	return;
    } else if (ch < ' ')
	return;

    switch (ch) {
#ifdef PRINTPIPE
    case 'i':			/* printing */
	switch (arg[0]) {
	case 0:
	    scr_printscreen(0);
	    break;
	case 5:
	    process_print_pipe();
	    break;
	}
	break;
#endif
    case 'A':
    case 'e':			/* up <n> */
	scr_gotorc((arg[0] ? -arg[0] : -1), 0, RELATIVE);
	break;
    case 'B':			/* down <n> */
	scr_gotorc((arg[0] ? +arg[0] : +1), 0, RELATIVE);
	break;
    case 'C':
    case 'a':			/* right <n> */
	scr_gotorc(0, (arg[0] ? +arg[0] : +1), RELATIVE);
	break;
    case 'D':			/* left <n> */
	scr_gotorc(0, (arg[0] ? -arg[0] : -1), RELATIVE);
	break;
    case 'E':			/* down <n> & to first column */
	scr_gotorc((arg[0] ? +arg[0] : +1), 0, R_RELATIVE);
	break;
    case 'F':			/* up <n> & to first column */
	scr_gotorc((arg[0] ? -arg[0] : -1), 0, R_RELATIVE);
	break;
    case 'G':
    case '`':			/* move to col <n> */
	scr_gotorc(0, (arg[0] ? arg[0] - 1 : +1), R_RELATIVE);
	break;
    case 'd':			/* move to row <n> */
	scr_gotorc((arg[0] ? arg[0] - 1 : +1), 0, C_RELATIVE);
	break;
    case 'H':
    case 'f':			/* position cursor */
	switch (nargs) {
	case 0:
	    scr_gotorc(0, 0, 0);
	    break;
	case 1:
	    scr_gotorc((arg[0] ? arg[0] - 1 : 0), 0, 0);
	    break;
	default:
	    scr_gotorc(arg[0] - 1, arg[1] - 1, 0);
	    break;
	}
	break;
    case 'I':
	scr_tab(arg[0] ? +arg[0] : +1);
	break;
    case 'Z':
	scr_tab(arg[0] ? -arg[0] : -1);
	break;
    case 'J':
	scr_erase_screen(arg[0]);
	break;
    case 'K':
	scr_erase_line(arg[0]);
	break;
    case '@':
	scr_insdel_chars((arg[0] ? arg[0] : 1), INSERT);
	break;
    case 'L':
	scr_insdel_lines((arg[0] ? arg[0] : 1), INSERT);
	break;
    case 'M':
	scr_insdel_lines((arg[0] ? arg[0] : 1), DELETE);
	break;
    case 'X':
	scr_insdel_chars((arg[0] ? arg[0] : 1), ERASE);
	break;
    case 'P':
	scr_insdel_chars((arg[0] ? arg[0] : 1), DELETE);
	break;

    case 'c':
	tt_printf(VT100_ANS);
	break;
    case 'm':
	process_sgr_mode(nargs, arg);
	break;
    case 'n':			/* request for information */
	switch (arg[0]) {
	case 5:
	    tt_printf("\033[0n");
	    break;		/* ready */
	case 6:
	    scr_report_position();
	    break;
#if defined (ENABLE_DISPLAY_ANSWER)
	case 7:
	    tt_printf("%s\n", display_name);
	    break;
#endif
	case 8:
	    xterm_seq(XTerm_title, APL_NAME "-" VERSION);
	    break;
	}
	break;
    case 'r':			/* set top and bottom margins */
	if (priv != '?') {
	    if (nargs < 2 || arg[0] >= arg[1])
		scr_scroll_region(0, 10000);
	    else
		scr_scroll_region(arg[0] - 1, arg[1] - 1);
	    break;
	}
    /* drop */
    case 's':
    case 't':
    case 'h':
    case 'l':
	process_terminal_mode(ch, priv, nargs, arg);
	break;
    case 'g':
	switch (arg[0]) {
	case 0:
	    scr_set_tab(0);
	    break;		/* delete tab */
	case 3:
	    scr_set_tab(-1);
	    break;		/* clear all tabs */
	}
	break;
    case 'W':
	switch (arg[0]) {
	case 0:
	    scr_set_tab(1);
	    break;		/* = ESC H */
	case 2:
	    scr_set_tab(0);
	    break;		/* = ESC [ 0 g */
	case 5:
	    scr_set_tab(-1);
	    break;		/* = ESC [ 3 g */
	}
	break;
    }
}
/*}}} */

/*{{{ process xterm text parameters sequences `ESC ] Ps ; Pt BEL' */
/* PROTO */
void
process_xterm_seq(void)
{
    unsigned char   ch, string[STRING_MAX];
    int             arg;

    ch = cmd_getc();
    for (arg = 0; isdigit(ch); ch = cmd_getc())
	arg = arg * 10 + (ch - '0');

    if (ch == ';') {
	int             n = 0;

	while ((ch = cmd_getc()) != 007) {
	    if (ch) {
		if (ch == '\t')
		    ch = ' ';	/* translate '\t' to space */
		else if (ch < ' ')
		    return;	/* control character - exit */

		if (n < sizeof(string) - 1)
		    string[n++] = ch;
	    }
	}
	string[n] = '\0';
    /*
     * menubar_dispatch() violates the constness of the string,
     * so do it here
     */
	if (arg == XTerm_Menu)
	    menubar_dispatch(string);
	else
	    xterm_seq(arg, string);
    }
}
/*}}} */

/*{{{ process DEC private mode sequences `ESC [ ? Ps mode' */
/*
 * mode can only have the following values:
 *      'l' = low
 *      'h' = high
 *      's' = save
 *      'r' = restore
 *      't' = toggle
 * so no need for fancy checking
 */
/* PROTO */
void
process_terminal_mode(int mode, int priv, unsigned int nargs, int arg[])
{
    unsigned int    i;
    int             state;

    if (nargs == 0)
	return;

/* make lo/hi boolean */
    switch (mode) {
    case 'l':
	mode = 0;
	break;
    case 'h':
	mode = 1;
	break;
    }

    switch (priv) {
    case 0:
	if (mode && mode != 1)
	    return;		/* only do high/low */
	for (i = 0; i < nargs; i++)
	    switch (arg[i]) {
	    case 4:
		scr_insert_mode(mode);
		break;
	    /* case 38:  TEK mode */
	    }
	break;

#define PrivCases(bit)	\
if (mode == 't') state = !(PrivateModes & bit); else state = mode;\
switch (state) {\
case 's': SavedModes |= (PrivateModes & bit); continue; break;\
case 'r': state = (SavedModes & bit) ? 1 : 0;/*drop*/\
default:  PrivMode (state, bit); }

    case '?':
	for (i = 0; i < nargs; i++)
	    switch (arg[i]) {
	    case 1:		/* application cursor keys */
		PrivCases(PrivMode_aplCUR);
		break;

	    /* case 2:   - reset charsets to USASCII */

	    case 3:		/* 80/132 */
		PrivCases(PrivMode_132);
		if (PrivateModes & PrivMode_132OK)
		    set_width(state ? 132 : 80);
		break;

	    /* case 4:   - smooth scrolling */

	    case 5:		/* reverse video */
		PrivCases(PrivMode_rVideo);
		scr_rvideo_mode(state);
		break;

	    case 6:		/* relative/absolute origins  */
		PrivCases(PrivMode_relOrigin);
		scr_relative_origin(state);
		break;

	    case 7:		/* autowrap */
		PrivCases(PrivMode_Autowrap);
		scr_autowrap(state);
		break;

	    /* case 8:   - auto repeat, can't do on a per window basis */

	    case 9:		/* X10 mouse reporting */
		PrivCases(PrivMode_MouseX10);
	    /* orthogonal */
		if (PrivateModes & PrivMode_MouseX10)
		    PrivateModes &= ~(PrivMode_MouseX11);
		break;

#if (MENUBAR_MAX)
#ifdef menuBar_esc
	    case menuBar_esc:
		PrivCases(PrivMode_menuBar);
		map_menuBar(state);
		break;
#endif
#endif				/* MENUBAR_MAX */

#ifdef scrollBar_esc
	    case scrollBar_esc:
		PrivCases(PrivMode_scrollBar);
		map_scrollBar(state);
		break;
#endif
	    case 25:		/* visible/invisible cursor */
		PrivCases(PrivMode_VisibleCursor);
		scr_cursor_visible(state);
		break;

	    case 35:
		PrivCases(PrivMode_ShiftKeys);
		break;

	    case 40:		/* 80 <--> 132 mode */
		PrivCases(PrivMode_132OK);
		break;

	    case 47:		/* secondary screen */
		PrivCases(PrivMode_Screen);
		scr_change_screen(state);
		break;

	    case 66:		/* application key pad */
		PrivCases(PrivMode_aplKP);
		break;

	    case 67:
		PrivCases(PrivMode_BackSpace);
		break;

	    case 1000:		/* X11 mouse reporting */
		PrivCases(PrivMode_MouseX11);
	    /* orthogonal */
		if (PrivateModes & PrivMode_MouseX11)
		    PrivateModes &= ~(PrivMode_MouseX10);
		break;

#if 0
	    case 1001:
		break;		/* X11 mouse highlighting */
#endif
	    case 1010:		/* scroll to bottom on TTY output inhibit */
		PrivCases(PrivMode_TtyOutputInh);
		if (PrivateModes & PrivMode_TtyOutputInh)
		    Options |= Opt_scrollTtyOutputInh;
		else
		    Options &= ~Opt_scrollTtyOutputInh;
		break;
	    case 1011:		/* scroll to bottom on key press */
		PrivCases(PrivMode_Keypress);
		if (PrivateModes & PrivMode_Keypress)
		    Options |= Opt_scrollKeypress;
		else
		    Options &= ~Opt_scrollKeypress;
		break;
	    }
#undef PrivCases
	break;
    }
}
/*}}} */

/*{{{ process sgr sequences */
/* PROTO */
void
process_sgr_mode(unsigned int nargs, int arg[])
{
    unsigned int    i;

    if (nargs == 0) {
	scr_rendition(0, ~RS_None);
	return;
    }
    for (i = 0; i < nargs; i++)
	switch (arg[i]) {
	case 0:
	    scr_rendition(0, ~RS_None);
	    break;
	case 1:
	    scr_rendition(1, RS_Bold);
	    break;
	case 4:
	    scr_rendition(1, RS_Uline);
	    break;
	case 5:
	    scr_rendition(1, RS_Blink);
	    break;
	case 7:
	    scr_rendition(1, RS_RVid);
	    break;
	case 22:
	    scr_rendition(0, RS_Bold);
	    break;
	case 24:
	    scr_rendition(0, RS_Uline);
	    break;
	case 25:
	    scr_rendition(0, RS_Blink);
	    break;
	case 27:
	    scr_rendition(0, RS_RVid);
	    break;

	case 30:
	case 31:		/* set fg color */
	case 32:
	case 33:
	case 34:
	case 35:
	case 36:
	case 37:
	    scr_color(minColor + (arg[i] - 30), RS_Bold);
	    break;
	case 39:		/* default fg */
	    scr_color(restoreFG, RS_Bold);
	    break;

	case 40:
	case 41:		/* set bg color */
	case 42:
	case 43:
	case 44:
	case 45:
	case 46:
	case 47:
	    scr_color(minColor + (arg[i] - 40), RS_Blink);
	    break;
	case 49:		/* default bg */
	    scr_color(restoreBG, RS_Blink);
	    break;
	}
}
/*}}} */

/*{{{ process Rob Nation's own graphics mode sequences */
/* PROTO */
void
process_graphics(void)
{
    unsigned char   ch, cmd = cmd_getc();

#ifndef RXVT_GRAPHICS
    if (cmd == 'Q') {		/* query graphics */
	tt_printf("\033G0\n");	/* no graphics */
	return;
    }
/* swallow other graphics sequences until terminating ':' */
    do
	ch = cmd_getc();
    while (ch != ':');
#else
    int             nargs;
    int             args[NGRX_PTS];
    unsigned char  *text = NULL;

    if (cmd == 'Q') {		/* query graphics */
	tt_printf("\033G1\n");	/* yes, graphics (color) */
	return;
    }
    for (nargs = 0; nargs < (sizeof(args) / sizeof(args[0])) - 1; /*nil */ ) {
	int             neg;

	ch = cmd_getc();
	neg = (ch == '-');
	if (neg || ch == '+')
	    ch = cmd_getc();

	for (args[nargs] = 0; isdigit(ch); ch = cmd_getc())
	    args[nargs] = args[nargs] * 10 + (ch - '0');
	if (neg)
	    args[nargs] = -args[nargs];

	nargs++;
	args[nargs] = 0;
	if (ch != ';')
	    break;
    }

    if ((cmd == 'T') && (nargs >= 5)) {
	int             i, len = args[4];

	text = MALLOC((len + 1) * sizeof(char));

	if (text != NULL) {
	    for (i = 0; i < len; i++)
		text[i] = cmd_getc();
	    text[len] = '\0';
	}
    }
    Gr_do_graphics(cmd, nargs, args, text);
#endif
}
/*}}} */

/*{{{ Read and process output from the application */
/* PROTO */
void
main_loop(void)
{
    int             ch;

    do {
	while ((ch = cmd_getc()) == 0) ;	/* wait for something */
	if (ch >= ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
	/* Read a text string from the input buffer */
	    int             nlines = 0;
	    unsigned char  *str;

	/*
	 * point to the start of the string,
	 * decrement first since it was post incremented in cmd_getc()
	 */
	    str = --cmdbuf_ptr;
	    while (cmdbuf_ptr < cmdbuf_endp) {
		ch = *cmdbuf_ptr++;
		if (ch >= ' ' || ch == '\t' || ch == '\r') {
		/* nothing */
		} else if (ch == '\n') {
		    nlines++;
		    if (++refresh_count >= (refresh_limit * (TermWin.nrow - 1)))
			break;
		} else {	/* unprintable */
		    cmdbuf_ptr--;
		    break;
		}
	    }
	    scr_add_lines(str, nlines, (cmdbuf_ptr - str));
	} else {
	    switch (ch) {
	    case 005:		/* terminal Status */
		tt_printf(VT100_ANS);
		break;
	    case 007:		/* bell */
		scr_bell();
		break;
	    case '\b':		/* backspace */
		scr_backspace();
		break;
	    case 013:		/* vertical tab, form feed */
	    case 014:
		scr_index(UP);
		break;
	    case 016:		/* shift out - acs */
		scr_charset_choose(1);
		break;
	    case 017:		/* shift in - acs */
		scr_charset_choose(0);
		break;
	    case 033:		/* escape char */
		process_escape_seq();
		break;
	    }
	}
    } while (ch != EOF);
}

/* ---------------------------------------------------------------------- */
/* Addresses pasting large amounts of data and rxvt hang
 * code pinched from xterm and applied originally to rxvt-2.18
 * Hops
 */

static char *v_buffer;		/* pointer to physical buffer */
static char *v_bufstr = NULL;	/* beginning of area to write */
static char *v_bufptr;		/* end of area to write */
static char *v_bufend;		/* end of physical buffer */

/* output a burst of any pending data fm a paste... */
static int
v_doPending()
{
    if (v_bufstr >= v_bufptr)
        return 0;
    v_writeBig(cmd_fd, NULL, 0);
    return 1;
}

/* Write data to the pty as typed by the user, pasted with the mouse,
 * or generated by us in response to a query ESC sequence.
 * Code Pinched from xterm 
 */
static void
v_writeBig(int f, char *d, int len)
{
	int riten;
	int c = len;

	if (v_bufstr == NULL  &&  len > 0)
	{
	        v_buffer = malloc(len);
		v_bufstr = v_buffer;
		v_bufptr = v_buffer;
		v_bufend = v_buffer + len;
	}

	/*
	 * Append to the block we already have.
	 * Always doing this simplifies the code, and
	 * isn't too bad, either.  If this is a short
	 * block, it isn't too expensive, and if this is
	 * a long block, we won't be able to write it all
	 * anyway.
	 */

	if (len > 0)
	{
	    if (v_bufend < v_bufptr + len) { /* we've run out of room */
		if (v_bufstr != v_buffer) {
		    /* there is unused space, move everything down */
		    /* possibly overlapping bcopy here */

		    /* bcopy(v_bufstr, v_buffer, v_bufptr - v_bufstr); */
		    memcpy(v_buffer, v_bufstr, v_bufptr - v_bufstr);
		    v_bufptr -= v_bufstr - v_buffer;
		    v_bufstr = v_buffer;
		}
		if (v_bufend < v_bufptr + len)
		{
		    /* still won't fit: get more space */
		    /* Don't use XtRealloc because an error is not fatal. */
		    int size = v_bufptr - v_buffer; /* save across realloc */
		    v_buffer = realloc(v_buffer, size + len);
		    if (v_buffer)
		    {
			v_bufstr = v_buffer;
			v_bufptr = v_buffer + size;
			v_bufend = v_bufptr + len;
		    }
		    else
		    {
			/* no memory: ignore entire write request */
			fprintf(stderr, "rxvt: cannot allocate buffer space\n");
			v_buffer = v_bufstr; /* restore clobbered pointer */
			c = 0;
		    }
		}
	    }
	    if (v_bufend >= v_bufptr + len)
	    {   /* new stuff will fit */
		memcpy(v_bufptr, d, len); /* bcopy(d, v_bufptr, len); */
		v_bufptr += len;
	    }
	}

	/*
	 * Write out as much of the buffer as we can.
	 * Be careful not to overflow the pty's input silo.
	 * We are conservative here and only write
	 * a small amount at a time.
	 *
	 * If we can't push all the data into the pty yet, we expect write
	 * to return a non-negative number less than the length requested
	 * (if some data written) or -1 and set errno to EAGAIN,
	 * EWOULDBLOCK, or EINTR (if no data written).
	 *
	 * (Not all systems do this, sigh, so the code is actually
	 * a little more forgiving.)
	 */

#define MAX_PTY_WRITE 128	/* 1/2 POSIX minimum MAX_INPUT */

	if (v_bufptr > v_bufstr)
	{
	    riten = write(f, v_bufstr, v_bufptr - v_bufstr <= MAX_PTY_WRITE ?
			  	       v_bufptr - v_bufstr : MAX_PTY_WRITE);
	    if (riten < 0)
	    {
		riten = 0;
	    }
	    v_bufstr += riten;
	    if (v_bufstr >= v_bufptr) /* we wrote it all */
		v_bufstr = v_bufptr = v_buffer;
	}

	/*
	 * If we have lots of unused memory allocated, return it
	 */
	if (v_bufend - v_bufptr > 1024)
	{   /* arbitrary hysteresis */
	    /* save pointers across realloc */
	    int start = v_bufstr - v_buffer;
	    int size = v_bufptr - v_buffer;
	    int allocsize = size ? size : 1;
	    
	    v_buffer = realloc(v_buffer, allocsize);
	    if (v_buffer)
	    {
		v_bufstr = v_buffer + start;
		v_bufptr = v_buffer + size;
		v_bufend = v_buffer + allocsize;
	    }
	    else
	    {
		/* should we print a warning if couldn't return memory? */
		v_buffer = v_bufstr - start; /* restore clobbered pointer */
	    }
	}
}

/*}}} */
/*----------------------- end-of-file (C source) -----------------------*/